在面板中放置几个按钮(jButton)和一个文本框(jTextField),把按钮的名称改为1,2,3,4,5,6等等,代码要怎么写,才能在文本框上显示按钮的名称,就像计算器和电话按键一样
------解决方案--------------------
你可以学习下;
示例:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JbuttonDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new MyForm();
}
});
}
}
class MyForm extends JFrame{
private static final long serialVersionUID = 1138060324454853838L;
JButton jb1 = null;
JButton jb2 = null;
JButton jb3 = null;
JButton jb4 = null;
JButton jb5 = null;
JButton jb6 = null;
JTextField textField = null;
MyForm(){
jb1 = new JButton("1");
jb2 = new JButton("2");
jb3 = new JButton("3");
jb4 = new JButton("4");
jb5 = new JButton("5");
jb6 = new JButton("6");
ShowNumberListener snl = new ShowNumberListener();
jb1.addActionListener(snl);
jb2.addActionListener(snl);
jb3.addActionListener(snl);
jb4.addActionListener(snl);
jb5.addActionListener(snl);
jb6.addActionListener(snl);
textField = new JTextField(30);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(2, 3));
jp.add(jb1);
jp.add(jb2);
jp.add(jb3);
jp.add(jb4);
jp.add(jb5);
jp.add(jb6);
this.add(textField, BorderLayout.NORTH);
this.add(jp, BorderLayout.CENTER);
this.setSize(200, 100);
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((int)(size.getWidth()/2-100), (int)(size.getHeight()/2-50));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
}
class ShowNumberListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JButton){
JButton jb = (JButton)e.getSource();
String value = jb.getText();
textField.setText(value);
}
}
}
}