简体   繁体   中英

Using repaint() method properly

I have a button that when pressed calls a changecolor() method in a different class where some drawing is done. The button listener works fine and I see from some logging that the color was in fact changed but my drawing is not updated. This is my current implementation:

(This method is called when a button is clicked)

public void changeWarningLightColor(){
    System.out.println("change color method called");
    if(warningLights.equals(Color.GREEN)){
        warningLights=Color.RED;
        System.out.println(warningLights);
        repaint();  
    }
    else{
        warningLights=Color.GREEN;
        repaint();  
    }
}

and my drawing is created in the same file in the above method as follows:

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
            g.drawSomething();
            //draw a bunch of lines
}

My question is what is the proper way to call repaint() in order to actually update the drawing? Do I need to somehow call g.repaint() or do something different?

Separate class where the frame is created:

public class MainWindow extends JFrame {

public MainWindow(){
    JPanel Window = new JPanel(); 
    JPanel LeftSidePanel = new JPanel();
    LeftSidePanel.setLayout(new BorderLayout());

    LeftSidePanel.add(new DrawStatus(),BorderLayout.CENTER); //where the drawing is added

    Window.setLayout(new BoxLayout(Window,0));
    Window.add(LeftSidePanel);

    add(Window);    

}

public static void main(String[] args)  {
    //main method for showing the frame we created with the panels, and circles inside it 
    MainWindow frame = new MainWindow();
    frame.setSize((int) (.75*Toolkit.getDefaultToolkit().getScreenSize().getWidth()),(int) (.75*Toolkit.getDefaultToolkit().getScreenSize().getHeight()));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.setTitle("DVPWS v1.0");
    frame.setResizable(false);

    MenuBar menu = new MenuBar();
    frame.setJMenuBar(menu);
    frame.setVisible(true);


}



}

If you are using a Jframe (most likely are) do

    yourFrame.repaint();

Optionally

    yourPanel.repaint();

In this case you could do

    public MainWindow mw = new MainWindow();

    mw.repaint();

If that doesnt work(i had a similar problem) than your going to have to make an instance of JFrame instead of extending it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM