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);
}
}}
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和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);
}
}
}