23行的一个小程序!请高手帮忙看一下!追分
import javax.swing.*;
public class Class1 extends JFrame {
public Class1() {
JPanel panel=new JPanel();
JButton button = new JButton("生成");
JTextField text = new JTextField(10);
JComboBox cbox = new JComboBox();
panel.add(button);
panel.add(text);
panel.add(cbox);
this.add(panel);
this.setBounds(100,100,200,150);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Class1 class1 = new Class1();
}
}
我在JPanel上面加了JButton ,JTextField 和JComboBox ,下面请高手帮忙!效果是,在JTextField 里输入一个数字N,点击JButton 后JComboBox 里生成N个数!!比如输入一个数字5,点击按钮后JComboBox 下拉菜单里生成5个数!请高手帮忙改一下代码发上来,谢谢了!解决问题给追20!
参考答案://以下是实现的代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Class1 extends JFrame {
private static final long serialVersionUID = 5660386050876539722L;
JPanel panel = new JPanel();
JButton button = new JButton("生成");
JTextField text = new JTextField(10);
JComboBox cbox = new JComboBox();
public Class1() {
panel.add(button);
panel.add(text);
panel.add(cbox);
this.add(panel);
this.setBounds(100, 100, 200, 150);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void generateItems() {
this.button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
int num = Integer.parseInt(text.getText().trim());
cbox.removeAllItems();
for(int i=0; i<num; i++){
cbox.addItem(""+(i+1));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "请输入一个整数!", "输入错误", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
public static void main(String[] args) {
Class1 class1 = new Class1();
class1.generateItems();
}
}