[英]Using repaint() method properly
I have a button that when pressed calls a changecolor() method in a different class where some drawing is done. 我有一个按钮,当按下该按钮时,会在完成某些绘制的另一个类中调用changecolor()方法。 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? 我的问题是调用repaint()以真正更新图形的正确方法是什么? Do I need to somehow call g.repaint() or do something different?
我是否需要以某种方式调用g.repaint()或执行其他操作?
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 如果您正在使用Jframe(很可能是),请执行
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. 如果那不起作用(我有类似的问题),那么您将不得不制作一个JFrame实例而不是对其进行扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.