Search code examples
javaswingpaintcomponent

Problems with paintComponent()


The question concerns 2 classes from my project: The main, and the drawing class. The main class creates the JFrame and places 2 JPanels inside. The first JPanel contains JTextFields where you input the numbers, and JButtons to select different options, also having a Start button and a reset button. The second JPanel is an instance of the drawing class.

The second class, the drawing class is supposed to draw the graphs and then the visual representation of the numbers(triangle/trapezoid). Basically the graphs should be drawn as soon as start the project(no problem until now), and then draw the numbers after the start button is pressed(nothing happens). Here are parts of the code related to the problem.

Public class MainMenu extends JFrame implements ActionListener {
  private JPanel mainPanel;      
  public static void main(String[] args) {
    MainMenu app = new MainMenu();
    app.setVisible(true);
    app.setResizable(false);
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.setBounds(250, 200, 1200, 600); 
  }

  public MainMenu() {
    drawing = new DrawingTool();
    mainPanel.add(drawing);    //draws the graphs on launch
    //extra code. not relevant
  }

  public void Run(){
    // more code
    drawing.updateVariables(numberA,numberB,numberC,operation,precision);
  }

The second class

public class DrawingTool extends JPanel{
boolean numbersUpdated=false;
public void updateVariables(Nr nrA, Nr nrB, Nr nrC, int op, int prec){
  fzzyA = nrA;
  fzzyB = nrB;
  fzzyC = nrC;
  operation = op;
  precision = prec;
}
public void paintComponent(Graphics g){
    //draw the graphs - this works
    if(numbersUpdated){
    //draw the numbers
    }
 }

Also if i would like to reset the drawing JPanel to the point where only the graphs are drawn by pressing the reset button, would it work to only set the numbersUpdates to false?


Solution

  • then draw the numbers after the start button is pressed(nothing happens).

    Whenever you change a property of a Swing component you need to invoke repaint() to tell the component to paint itself.

    So in your updateVariables(...) method you need to add a repaint() statement at the end of the method.