java - 当 Java AWT 框架上的元素发生更改时,如何更新它?

标签 java awt paintcomponent

我是编程新手,我似乎无法解决这个问题:如何更改应用程序的框架?这是一款扫雷游戏。程序逻辑良好,事件正常工作,但框架本身没有重新绘制本身...我的小程序没有这种问题..我怎样才能使这个工作正常?

public void paint(Graphics g) {
    Graphics2D g2=(Graphics2D)g;
    _Main.toPaint(g2);
}
public void update(Graphics g) {
    Graphics offgc;
    Image offScreen=null;
    Dimension d=size();

    offScreen=createImage(d.height, d.width);
    offgc=offScreen.getGraphics();

    offgc.setColor(getBackground());
    offgc.fillRect(0, 0, d.width, d.height);
    offgc.setColor(getForeground());

    paint(offgc);
    g.drawImage(offScreen,0,0,this);
}

最佳答案

你的图形似乎画错了。对于 custom paintings您需要使用 paintComponent(...) JComponent 的方法,例如 JPanel,而不是 paint() 方法和自定义 update()。要更新组件图形,只需调用 repaint() 方法。

这是为您绘制的简单示例,请尝试检查:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Example extends JPanel{

    private Random rand = new Random();

    public static void main(String... s){
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final Example example;
        f.add(example = new Example());

        JButton b = new JButton("repaint");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                example.repaint();
            }
        });
        f.add(b, BorderLayout.SOUTH);
        f.setSize(200,200);
        f.setVisible(true);
    }

    public Example(){
        setBackground(Color.WHITE);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        for(int i =0; i<10;i++){
            int nextInt = rand.nextInt(getHeight()-10);
            int nextInt2 = rand.nextInt(getWidth()-10);
            g.fillRect(nextInt2, nextInt, 10, 10);
        }
    }
}

另请阅读安德鲁·汤普森的建议。

关于java - 当 Java AWT 框架上的元素发生更改时,如何更新它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20781549/

相关文章:

java - clientgen 生成的 PortType_Stub 无法转换为 javax.xml.ws.BindingProvider

java - https URL 主机名与客户端信任库中服务器证书上的公用名 (CN) 不匹配

java - jdk12 中 appletviewer 的替代方案

java - 在 JFrame 中显示透明 GIF,而不在播放时保留每一帧? (初学者)

java - 绘制组件方法不适用于 JFrame

Java 正则表达式不工作 - 字符串分割

java - Graphics2d 方法不产生输出

java - JButton 打印多次而不是一次。为什么?

java - 将 JPanel 和 PaintComponent 链接在一起

java - 使用 Swing 在 Java 中绘制多个矩形