gpt4 book ai didi

java - 编号和循环问题

转载 作者:搜寻专家 更新时间:2023-11-01 03:05:17 24 4
gpt4 key购买 nike

我是编程新手,很难解决这个问题。我正在尝试根据在 JTextField 中输入的数字 build 一堵墙,但该数字不能超过 20。我无法显示错误消息,也无法 build 砖墙。有人可以帮我弄清楚我做错了什么吗?

public class Wall extends JApplet implements ActionListener {

JTextField enter;
Boolean submit;
JLabel bricks;
JButton build;
JPanel top;
Image zombie;
int value;

public void init() {
setLayout(new BorderLayout());

top = new JPanel();
build = new JButton("AHHHHHH...ZOMBIES!"); //button for building wall
bricks = new JLabel("Enter between 1 & 20 rows to contruct:");
enter = new JTextField(2);

top.add(build); //add zombie button
top.add(bricks); //add intructions
top.add(enter); //add text field
add(top, BorderLayout.NORTH);


build.addActionListener(this);


}

public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == build) {
int value = Integer.parseInt(build.getText());
if (value > 0 && value < 21) {
submit = true;
repaint();
} else {
submit = false;
repaint();
}

}
}

public void paint(Graphics g) {
super.paint(g);

//add zombie image
Image zombie = getImage(getCodeBase(), "Zombie.jpg");
g.drawImage(zombie, 0, 45, this);

if (submit = false) //add error message
{
g.setColor(Color.WHITE);
g.setFont(new Font("TimesRoman", Font.BOLD, 40));
g.drawString("You must enter a number between 1 & 20!", 400, 100); //add message
}

int brick_width = 50;
int brick_height = 20;
int spacing = 1;
int x = 0;
while (x < 21) {
drawBrick(g, nextInt(brick_width + spacing), nextInt(brick_height + spacing));
x = x + getWidth() + 50;
x = x - 25 + getWidth() + 50;
x++;

}

}

public void drawBrick(Graphics g, int x, int y) {
g.setColor(new Color(150, 0, 0));
g.fillRect(0, 635, 50, 20);
}
}

最佳答案

而不是在 top-level containers 上绘画比如直接用JApplet,就得用JPanel在上面画画。只需覆盖 JPanel()paintComponent() 方法。永远不要忘记在覆盖的方法中调用 super.paintComponent(g)

示例代码:

top = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
...
// your custom painting code goes here
}
};

注意:

submit == false!submit 是检查它的正确方法,但它仍然会导致 NullPointerException 因为您从未初始化实例变量提交

使用原始 boolean 而不是 Boolean 来避免此类异常或正确初始化它。

Boolean submit = false;

关于java - 编号和循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24933917/

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