import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class 随机数 
{
public static void main(String []args)
{
JFrame frame=new JFrame ("抽取随机数");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label=new JLabel ("抽取的随机数为:");

JButton button=new JButton("抽取随机数");
button.addActionListener(new ButtonListener());

JPanel panel=new JPanel();
panel.setPreferredSize(new Dimension());
panel.setLayout(new BoxLayout (label,BoxLayout.Y_AXIS));
panel.setLayout(new BoxLayout (button,BoxLayout.Y_AXIS));
panel.setBackground(Color.cyan);
panel.add(label);
panel.add(button);
}

private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int temp;
Random generator=new Random();

temp=generator.nextInt(100)+1;

label.setText("抽取的随机数为:"+temp);

}
}}

解决方案 »

  1.   

    类名尽量不要用中文。不过第一个问题是:
      private class ButtonListener implements ActionListener
    是个私有类,那别的类就没法“new ButtonListener()”了,修改为:
      class ButtonListener implements ActionListener其实就是把private这个关键字删掉。
      

  2.   

    首先label.setText("抽取的随机数为:" + temp); 中的label引用在 ButtonListener类里面里面,请问你这个引用从哪儿来的?你没有定义,怎么会有label呢?接着是new ButtonListener()明显错了啊!再就是你问问题有说出你想实现什么样的功能,这样才会更好的帮你解决!
      

  3.   


    多谢前辈指点~~~~我想编写一个程序,显示一个按钮和一个标签。当按下按钮时,标签随机显示一个数。嗯,首先类名不用中文,记得了。关于引用label和new ButtonListener()是我在书上看到如下一段代码然后仿照来写的。这段代码是定义了一个面板类,然后在面板中创建组件和监听器类。最后用含有main函数的另一个类引用面板对象。请问,这种方式和我上面的直接在main方法中创建组件和监听器类有什么不同?为什么会这样?import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class PushCounterPanel extends JPanel       {
    private int count;                         
    private JButton push;
    private JLabel label;

    public PushCounterPanel()
    {
    count=0;

    push=new JButton ("Push me");
    push.addActionListener(new ButtonListener());

    label=new JLabel ("Pushes:"+count);

    add(push);
    add(label);

    setPreferredSize(new Dimension (300,40));
    setBackground(Color.cyan);
    }
    //监听器类
    private class ButtonListener implements ActionListener
    {
    public void actionPerformed(ActionEvent event)
    {
    count++;
    label.setText("Pushes:"+count);
    }
    }
    }
      

  4.   

    最好不要把所有的东西都写在main方法中那样都成一团了,那样既难看又容易出错。还是把他们写成函数更清晰点。另外我感觉的对属性这个概念挺模糊的!前面两个类没设一个属性,都被你写到main函数中去了,感觉不是面向对象了。(如有表述出错大家改正)。