单击按钮上的Java Graphics repaint()
我有此代码,按下按钮时想重新绘制图形:单击按钮上的Java Graphics repaint(),java,swing,Java,Swing,我有此代码,按下按钮时想重新绘制图形: 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)
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.....
}
}
公共类JDraw扩展了JFrame{
/**
*在JFrame中绘制图形。
*它的颜色是随机的,可以通过按钮改变。
*/
公共静态JButton okButton=新JButton(“更改颜色”);
公共JDraw(字符串newitel){
super.setTitle(纽蒂特);
}
//主要方法
公共静态void main(字符串str[]){
JDraw窗口=新的JDraw(“图形”);
设置窗口大小(300450);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
添加(OK按钮,BorderLayout.SOUTH);
okButton.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
//JDraw.repaint();您不能引用类JDraw。您应该使用一个对象。您的示例中的对象是window
。因此,请使用:
window.repaint();
这就像说:人类,走到门口。人类就是类。你不能告诉人类做什么,你需要一个人类的实例,比如奥巴马或圣诞老人。在你的例子中:你不能告诉JDraw重新绘制,但是JDraw类型的对象,即:窗口
你需要在你的操作中执行以下调用
:
window.repaint();
为了能够从内部引用窗口
,操作执行
,您需要将窗口变量设置为final
:
final JDraw window = ...;
但是,如果我能提出一些改进建议:
JFrame
JFrame的paint(Graphics)
JComponent
或JPanel
的类,并将其设置为JFrame
绘制(图形)
,而是覆盖绘制组件(图形)
ok按钮
不应该是静态的
。而是将所有代码移动到一个非静态方法中,如initUI()
,并使用一个代码,如new JDraw().initUI();
SwingUtilities.invokeLater(Runnable)
中,以便从事件调度线程正确启动UI+1:但是,我不同意改进1。不要扩展JPanel,而是JComponent。谢谢!这真的帮助了我!@MartijnCourteaux同意扩展
JComponent
可能是一个更好的选择,尽管扩展JPanel
会自动带来不透明度(至少默认情况下).对于commment#1,除非你将行为添加到一个类中,否则没有必要对其进行扩展,而组合始终是一个更好的选择。这是一个哲学上的选择,但如果你能“组合”,我会“不扩展”,这将提供更好的代码,主要是更易于维护的代码。在这种情况下,绝对不需要扩展。@MartijnCourteaux注意,如果代码绘制在标签中显示的缓冲图像
,则无需扩展JComponent
或JPanel
,也无需重新绘制任何内容(直到在图像上绘制新图纸)。