我有一个JButton变量用于创建不同数字的不同按钮
JButton numb;
numb = new JButton("7");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 30;
c.ipady = 30;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
displayPanel.add(numb, c);
numb.setFont(new Font("arial",Font.BOLD,20));
numb.addActionListener(this);
numb = new JButton("8");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 30;
c.ipady = 30;
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
displayPanel.add(numb, c);
numb.setFont(new Font("arial",Font.BOLD,20));
numb.addActionListener(this);
numb = new JButton("9");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 30;
c.ipady = 30;
c.gridx = 2;
c.gridy = 3;
c.gridwidth = 1;
displayPanel.add(numb, c);
numb.setFont(new Font("arial",Font.BOLD,20));
numb.addActionListener(this);
喜欢这样
当点击我的按钮时,我会从按下的按钮中读取文本
我的actionPerformed看起来像这样
public void actionPerformed(ActionEvent e) {
// add your event handling code here
if (e.getSource()==numb){
String button = (String)e.getActionCommand();
display.setText(button);
System.out.println(button);
}else if (e.getSource()==opButton){
System.out.println(button);
}
}
答案 0 :(得分:2)
你可以打印出点击的按钮文本,如下所示:
JButton button = (JButton) e.getSource();
String text = button.getText();
display.setText(text);
System.out.println(text);
......但是你要做的事情并不是很清楚。特别是,您已经在几个不同的时间重新分配了numb
的值 - 它无法引用这些按钮的所有。您可能希望为所有按钮提供一个通用操作命令,例如“数字”。然后你可以使用:
private static final String DIGIT_COMMAND = "digit";
// Assign the action command of each button as DIGIT_COMMAND...
...
public void actionPerformed(ActionEvent e) {
if (DIGIT_COMMAND.equals(e.getActionCommand()) {
JButton button = (JButton) e.getSource();
String text = button.getText();
display.setText(text);
System.out.println(text);
} else {
// Handle other commands
}
}