ButtonClick 上的 Java 图形重绘() [英] Java Graphics repaint() on ButtonClick
本文介绍了ButtonClick 上的 Java 图形重绘()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码并且想在按钮被按下时重新绘制我的图形:
I have this code and want to repaint my graphic when the Button gets pressed:
public class JDraw extends JFrame {
/**
* Draws a figur in a JFrame.
* The color of it is random and can get changed by a button.
*/
public static JButton okButton = new JButton("change color");
public JDraw(String newTitel) {
super.setTitle(newTitel);
}
//Main method
public static void main(String str[]) {
JDraw window = new JDraw("Graphic");
window.setSize(300, 450);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//JDraw.repaint(); <-- problem
}
});
}
@Override
public void paint(final Graphics g) {
super.paint(g);
Random rand = new Random();
int r1 = rand.nextInt(255);
int b1 = rand.nextInt(255);
int g1 = rand.nextInt(255);
g.setColor(new Color(r1, g1, b1));
//head
g.drawOval(100, 50, 100, 100);
g.fillOval(100, 50, 100, 100); // filled
//more drawing stuff.....
}
}
但是我不知道该怎么做,因为我无法在 ActionPerfomed 中进行重绘.错误:无法从静态上下文中引用非静态方法 repaint()
However I have no idea how to do it, because I cant do the repaint in my ActionPerfomed. Error: non-static method repaint() cannot be referenced from a static context
希望有人能帮忙.:)
推荐答案
您需要在 actionPerformed
中进行以下调用:
You need to make the following call in your actionPerformed
:
window.repaint();
为了能够在你的actionPerformed
中引用window
,你需要让你的window变量final
:
To be able to reference window
from within you actionPerformed
, you need to make your window variable final
:
final JDraw window = ...;
但是,如果我能提出一些改进建议:
However, if I can suggest a few improvements:
- 不要扩展
JFrame
- 不要覆盖
JFrame
的 - 而是创建一个扩展
JComponent
或JPanel
的类,并将其设置为JFrame
的内容窗格 - 与其覆盖
paint(Graphics)
,不如覆盖paintComponent(Graphics)
- 你的
okButton
不应该是static
.而是将所有代码移动到像initUI()
这样的非静态方法中,并使用像new JDraw().initUI();
这样的代码 - 将启动 UI 的代码包装在
SwingUtilities.invokeLater(Runnable)
中,以便从事件调度线程正确启动 UI.
paint(Graphics)
- Don't extend
JFrame
- Don't override
paint(Graphics)
ofJFrame
- Instead create a class that extends
JComponent
orJPanel
and set it as the content pane of theJFrame
- Instead of overrding
paint(Graphics)
, rather overridepaintComponent(Graphics)
- Your
okButton
should not bestatic
. Instead move all your code in a non-static method likeinitUI()
and have a code likenew JDraw().initUI();
- Wrap the code starting your UI in a
SwingUtilities.invokeLater(Runnable)
so that your UI is properly initiated from the Event Dispatching Thread.
这篇关于ButtonClick 上的 Java 图形重绘()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文