在哪里放置构造函数?

use*_*392 0 java swing constructor

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

private JPanel panel;
public RollButton(JPanel panel){
    this.panel = panel;
}
Run Code Online (Sandbox Code Playgroud)

我查看了一些放置构造函数的示例,看起来它放在我的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();    



        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 7

编辑:这是一个NullPointerException,或者像我们中的一些人说的那样,是NPE.

这里的关键是学习如何修复大多数NPE:

  1. 找到抛出NPE的行.例外at DiceRollGUI$RollButton.actionPerformed(DiceRollGUI.java:40)堆栈跟踪将告诉您,例如您的DiceRollGUI.java类中的第40行告诉您意义.
  2. 检查是否在该行上调用变量的任何方法,或者是否以其他方式"解除引用"变量.
  3. 检查该行上的任何变量是否为空(调试器可以帮助,或者失败,感兴趣的行之前有几个println 可以帮助).
  4. 然后在你的程序中追溯,看看为什么当你认为它不是时,该变量为null.

在你的情况下,你的JLabel标签是null,因为你永远不会初始化它.在尝试使用它之前,需要为其分配一个新的JLabel对象.

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


Mad*_*mer 6

这很简单NullPointerException,应该通过检查源代码中异常原因的最近行和/或调试程序来解决

当我运行该程序时,我得到以下异常......

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at dicerollgui.DiceRollGUI$RollButton.actionPerformed(DiceRollGUI.java:55)
Run Code Online (Sandbox Code Playgroud)

这指出了我label.setText(" ");actionPerformed方法......

        if(rolldie.equals("Roll")) {
            label.setText(" ");
Run Code Online (Sandbox Code Playgroud)

这自动向我建议label尚未初始化(因此null).

更新...

这个...

JFrame frame = new JFrame();
frame.add(dice6);
Run Code Online (Sandbox Code Playgroud)

对我来说似乎很奇怪.基本上在每个骰子卷上,你创建一个新的JLabel和一个新的,JFrame但你没有显示结果框架......

相反,您应该有一个JLabel维护最后一个卷的值的单个,只需使用setTextsetIcon根据您的要求更改它的状态.

更新了示例

感觉很幸运?

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DiceRoll {

    public static void main(String[] args) {
        new DiceRoll();
    }

    public DiceRoll() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new DicePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class DicePane extends JPanel {

        private JLabel diceRoll;
        private JButton rollDice;

        public DicePane() {
            setLayout(new BorderLayout());

            diceRoll = new JLabel();
            Font font = diceRoll.getFont();
            diceRoll.setFont(font.deriveFont(128f));
            diceRoll.setHorizontalAlignment(JLabel.CENTER);
            add(diceRoll);

            rollDice = new JButton("Papper needs a new pair of shoes");
            rollDice.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int roll = (int) (Math.round((Math.random() * 5) + 1));
                    diceRoll.setText(Integer.toString(roll));
                }
            });

            add(rollDice, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }        
}
Run Code Online (Sandbox Code Playgroud)