我有关于JButton的问题。我有20x20 JButtons的GridLayout。我想在单击时获得单个按钮的值。 (x.getText())。
无论单击什么按钮,sout都仅打印右下角的值。
如果我单击左上方的按钮,它将打印19。在这种情况下,我想返回的值为0。
我的代码如下。
public class MainFrame extends Frame implements MouseListener{
JButton button;
public MainFrame() {
setSize(new Dimension(1000, 1000));
addComponents();
}
private void addComponents(){
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel(new GridLayout(1,1));
JPanel center = new JPanel(new GridLayout(20, 20));
JLabel label = new JLabel("test");
top.add(label);
for (int i = 0; i < 20; i ++){
for (int j = 0; j < 20; j ++){
button = new JButton(String.valueOf(i));
button.addMouseListener(this);
center.add(button);
}
}
mainPanel.add(top, BorderLayout.NORTH);
mainPanel.add(center, BorderLayout.CENTER);
add(mainPanel);
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(button.getText());
}
// Also implements multiple other methods from the interface, but irrelevant for my question.
新代码(工作代码):
public class MainFrame extends Frame {
public MainFrame() {
setSize(new Dimension(1000, 1000));
addComponents();
}
private void addComponents(){
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel(new GridLayout(1,1));
JPanel center = new JPanel(new GridLayout(20, 20));
JLabel label = new JLabel("test");
top.add(label);
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = e.getActionCommand();
System.out.println(text);
}
};
for (int i = 0; i < 20; i ++){
for (int j = 0; j < 20; j ++){
JButton button = new JButton(String.valueOf(i));
button.addActionListener(listener);
center.add(button);
}
}
mainPanel.add(top, BorderLayout.NORTH);
mainPanel.add(center, BorderLayout.CENTER);
add(mainPanel);
最佳答案
不要在JButton上使用MouseListener,因为这样做,如果按钮具有焦点,则该按钮将不会对空格键的按下做出响应,并且如果禁用该按钮,MouseListener仍将起作用,这是不正确的行为。
取而代之的是使用ActionListener,仅需要一个,将其添加到每个按钮中,然后从ActionEvent参数获取action命令。
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = e.getActionCommand();
}
}
// add listener to all buttons in a for loop