gpt4 book ai didi

按下按钮时 Java 重新绘制

转载 作者:行者123 更新时间:2023-12-01 19:05:59 26 4
gpt4 key购买 nike

我在尝试按按钮更新我的主板时遇到了困难(在我的大脑中)。我是否认为 GameBoard 类是需要 repaint()ed 的类?

GameBoard.java

public class GameBoard extends Panel {

static Compass compass = new Compass();
private static final long serialVersionUID = 1;
Graphics2D g2d;

static final Dimension WINDOW_SIZE = new Dimension(1150, 800);

public void boardMaker() throws Exception {
JFrame frame = new JFrame("Display image");

JPanel panel = new JPanel();
/* unimportant stuff

.....


*/

//

DieRoll roll = new DieRoll("Roll Dies");
roll.setC(compass);
roll.setG2D(g2d);
//
Button button = new Button("new");
button.setGameBoard(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
buttonPanel.add(roll);
buttonPanel.setPreferredSize(new Dimension(200,100));

frame.getContentPane().add(buttonPanel, BorderLayout.NORTH);
//
frame.getContentPane().add(panel);
frame.setVisible(true);
}

public void paint(Graphics g) {
// not important I think
}
}

Button.java

public class Button extends JButton implements ActionListener {
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
JFrame frame = new JFrame();
Compass c = new Compass();

GameBoard gb = new GameBoard();


Button(String text) {
this.setText(text);
this.addActionListener(this);
}

void setGameBoard(GameBoard gb) {
this.gb = gb;
}

@Override
public void actionPerformed(ActionEvent e) {
gb.g2d.setColor(Color.black);
gb.g2d.fillRect(100, 100, 100, 200);
gb.repaint();
}
}

这会产生空指针异常。那么知道如何重新绘制我的游戏板吗?如果我因为愚蠢而不得不重写所有内容,我不会生气! ;)

谢谢

最佳答案

您对如何用 Java 绘图有错误的想法。像面板这样的组件会自行绘制,并且所有绘制都发生在 UI 线程上。

查看本教程:docs.oracle.com/javase/tutorial/2d/index.html

关于按下按钮时 Java 重新绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10091105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com