我怎样才能使这个JButton工作

时间:2015-05-14 00:04:05

标签: java swing jbutton

我正在处理一个代码,当您按下按钮并输出该数字时,该代码将生成一个随机数。我已经编写了这个代码并且它编译但是当我按下按钮时没有任何作用。有人可以请帮助。这是我的一些代码。

public class slotmachine extends JApplet {

    JButton b1 = new JButton("START");
    JPanel p;
    int Int1;

    public slotmachine() {
        init();

    }

    public void init() {

        this.setLayout(null);
        this.setSize(1000, 1000);

        JButton b1 = new JButton("START");
        b1.setBounds(100, 100, 100, 100);

        getContentPane().add(b1);
        repaint();

    }

    public void run() {
        b1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Random random1 = new Random();
                int Int1 = random1.nextInt(11);

            }

        });
    }

    public void paint(Graphics g) {

        g.drawString("Your number is" + Int1, 30, 30);

    }
}

1 个答案:

答案 0 :(得分:4)

  1. 避免使用null布局,像素完美布局是现代ui设计中的错觉。影响组件个体大小的因素太多,您无法控制。 Swing旨在与布局管理器一起工作,放弃这些将导致问题和问题的结束,您将花费越来越多的时间来纠正
  2. 您可以在按钮的Int1内创建ActionListener的本地变量。这与班级的Int1无关。
  3. 您永远不会告诉用户界面更新
  4. 你没有打电话给super.paint打破了油漆链(为一些非常奇怪和奇妙的图形故障做好准备)
  5. 您使用b1Int1犯了同样的错误。您创建了一个实例级别字段,但在init中使用局部变量对其进行了遮蔽,这意味着在调用start时,b1null,这将导致NullPointerxception 1}}
  6. 相反,在您的小程序中添加JLabel,使用它的setText方法显示随机值

    b1.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
            Random random1 = new Random();
            int Int1 = random1.nextInt(11);
            lable.setText(Integer.toString(Int1));
        }
    
    });
    

    另外,如果可能的话,我会避免使用JApplet,他们有自己的一系列问题,这些问题会让学生在学习Swing API时变得更加困难。相反,请尝试使用JPanel作为主容器,然后将其添加到JFrame的实例中。

    另外,请看一下:

    了解更多详情

相关问题