gpt4 book ai didi

java - 构造函数放在哪里?

转载 作者:行者123 更新时间:2023-12-01 06:32:21 25 4
gpt4 key购买 nike

我修复了代码并更新了,但现在我不知道在哪里放置构造函数:

private JPanel panel;
public RollButton(JPanel panel){
this.panel = panel;
}

我查看了一些放置构造函数的示例,它似乎放置在我的 RollButton 类周围,但我尝试多次将其放置在多个位置,但我不能看来是对的。

代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.Random;

public class DiceRollGUI {

public static JLabel label;
public static JFrame frame;
public static JPanel panel;
private static JButton button;
private static JButton buttonRollDie;
private static JLabel diceRoll;

public static void main (String[] args) {
JFrame frame = new JFrame("Dice Roll GUI");
JPanel contentPanel = new JPanel(new GridLayout(0,2,5,10));
button = new JButton("Roll");;

frame.setVisible(true);
frame.setResizable(false);
frame.setSize(750, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setActionCommand("Roll");
button.addActionListener(new RollButton());
panel.setPreferredSize(new Dimension(750, 500));
frame.setContentPane(panel);
frame.pack();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.add(button);


button.setAlignmentX(Component.CENTER_ALIGNMENT);
}

private static class RollButton implements ActionListener {

public void actionPerformed(ActionEvent event){
int roll = (int) (Math.round((Math.random() * 5) + 1));
ImageIcon dice = null;

if(roll == 1){
dice = new ImageIcon("DiceRollGUI Pictures/dice_face_1.png");
}
else if(roll == 2){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_2.png");
}
else if(roll == 3){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_3.png");
}
else if(roll == 4){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_4.png");
}
else if(roll == 5){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_5.png");
}
else if(roll == 6){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_6.png");;
}
JLabel diceRoll = new JLabel("",dice, JLabel.CENTER);

panel.add(diceRoll);
panel.revalidate();



}
}
}

最佳答案

编辑:这是一个 NullPointerException 或者正如我们中的一些人所说的,一个 NPE。

这里的关键是了解如何修复大多数 NPE:

  1. 找到引发 NPE 的行。异常堆栈跟踪会告诉您,例如您的堆栈跟踪会告诉您 at DiceRollGUI$RollButton.actionPerformed(DiceRollGUI.java:40) ,意思是在 DiceRollGUI.java 类的第 40 行。
  2. 检查您是否对该行上的变量调用了任何方法,或者是否以其他方式“取消引用”变量。
  3. 检查该行上的任何变量是否为空(调试器可以提供帮助,或者如果失败,可以在感兴趣的行之前帮助)。
  4. 然后在程序中回溯,看看为什么该变量在您认为不是 null 的情况下却为 null。

在您的情况下,您的 JLabel 标签为 null,因为,因为您从未初始化它。在尝试使用它之前,您需要为其分配一个新的 JLabel 对象。

此外,正如我在评论中提到的,将来,如果您询问有关异常或错误的问题,请始终发布完整的异常或错误消息,并为我们指出哪一行导致了问题。错误消息通常会准确地告诉您它是哪一行,但是您必须将行号转换为程序中的实际行。

关于java - 构造函数放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21818893/

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