ButtonClick 上的 Java 图形重绘() [英] Java Graphics repaint() on ButtonClick

查看:32
本文介绍了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:

  1. 不要扩展JFrame
  2. 不要覆盖JFrame
  3. paint(Graphics)
  4. 而是创建一个扩展 JComponentJPanel 的类,并将其设置为 JFrame
  5. 的内容窗格
  6. 与其覆盖paint(Graphics),不如覆盖paintComponent(Graphics)
  7. 你的 okButton 不应该是 static.而是将所有代码移动到像 initUI() 这样的非静态方法中,并使用像 new JDraw().initUI();
  8. 这样的代码
  9. 将启动 UI 的代码包装在 SwingUtilities.invokeLater(Runnable) 中,以便从事件调度线程正确启动 UI.
  1. Don't extend JFrame
  2. Don't override paint(Graphics) of JFrame
  3. Instead create a class that extends JComponent or JPanel and set it as the content pane of the JFrame
  4. Instead of overrding paint(Graphics), rather override paintComponent(Graphics)
  5. Your okButton should not be static. Instead move all your code in a non-static method like initUI() and have a code like new JDraw().initUI();
  6. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆