日期:2014-05-20  浏览次数:20604 次

请哪位前辈帮我看一下这段代码的问题~~~~
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);

}
}

}


------解决方案--------------------
类名尽量不要用中文。

不过第一个问题是:
private class ButtonListener implements ActionListener
是个私有类,那别的类就没法“new ButtonListener()”了,修改为:
class ButtonListener implements ActionListener

其实就是把private这个关键字删掉。
------解决方案--------------------
首先label.setText("抽取的随机数为:" + temp); 中的label引用在 ButtonListener类里面里面,请问你这个引用从哪儿来的?你没有定义,怎么会有label呢?接着是new ButtonListener()明显错了啊!再就是你问问题有说出你想实现什么样的功能,这样才会更好的帮你解决!
------解决方案--------------------
最好不要把所有的东西都写在main方法中那样都成一团了,那样既难看又容易出错。还是把他们写成函数更清晰点。另外我感觉的对属性这个概念挺模糊的!前面两个类没设一个属性,都被你写到main函数中去了,感觉不是面向对象了。(如有表述出错大家改正)。
------解决方案--------------------
类名不要用中文
会出现一些莫名其妙的错误的