我正在完成一项学校作业。我们有10个按钮,让我们先说10个字母的alpahabet。例如,当您点击“A' A'按钮,角色' A'被添加到jLabel。
我知道我可以为每个按钮编写新功能,但还有更好的方法吗?就像我通过参数传递字母并仅使用1个函数一样?或者以某种方式可以检测到什么按钮称为我的事件处理程序并根据它添加字母?
答案 0 :(得分:3)
是的,您可以使用actionCommand
。这里有一些例子。 How to use Buttons
示例:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ButtonExample {
private JPanel panel;
private JLabel label;
public ButtonExample(){
panel = new JPanel();
label = new JLabel(" ");
ActionListener listener = new MyActionListener();
JButton buttonA = new JButton("Press me A");
buttonA.setActionCommand("A");
buttonA.addActionListener(listener);
JButton buttonB = new JButton("Press me B");
buttonB.setActionCommand("B");
buttonB.addActionListener(listener);
JButton buttonC = new JButton("Press me C");
buttonC.setActionCommand("C");
buttonC.addActionListener(listener);
panel.add(buttonA);
panel.add(buttonB);
panel.add(buttonC);
}
private class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String text = (label.getText() == null || label.getText().isEmpty() )?"":label.getText();
label.setText(text+e.getActionCommand());
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Textfield example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(Boolean.TRUE);
ButtonExample buttonExample =new ButtonExample();
frame.add(buttonExample.panel,BorderLayout.CENTER);
frame.add(buttonExample.label,BorderLayout.NORTH);
//Display the window.
frame.pack();
frame.setVisible(Boolean.TRUE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
答案 1 :(得分:0)
你可以这样做
Yourlabel.setText(yourbutton.getText());
它会将您的按钮名称A设置为您想要的标签! 这只是一个暗示,你可以得到一个想法。