繁体   English   中英

正确使用repaint()方法

[英]Using repaint() method properly

我有一个按钮,当按下该按钮时,会在完成某些绘制的另一个类中调用changecolor()方法。 按钮侦听器工作正常,并且从一些日志记录中我看到颜色实际上已更改,但是我的图形未更新。 这是我当前的实现:

(单击按钮时将调用此方法)

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();  
    }
}

我的图形是通过上述方法在同一文件中创建的,如下所示:

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

我的问题是调用repaint()以真正更新图形的正确方法是什么? 我是否需要以某种方式调用g.repaint()或执行其他操作?

创建框架的单独类:

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);


}



}

如果您正在使用Jframe(很可能是),请执行

    yourFrame.repaint();

可选

    yourPanel.repaint();

在这种情况下,您可以

    public MainWindow mw = new MainWindow();

    mw.repaint();

如果那不起作用(我有类似的问题),那么您将不得不制作一个JFrame实例而不是对其进行扩展。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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