我不能使用add.ActionListener(本),所以我可以用
您创建一个实现一个ActionListener类。
最好还是创建一个实现Action的类。 Action与ActionListener相同。好处是可以对键绑定使用Action。
这是一个基本的例子:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition(display.getDocument().getLength());
display.replaceSelection(e.getActionCommand());
}
};
setLayout(new BorderLayout());
display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 5));
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton(text);
button.addActionListener(numberAction);
button.setBorder(new LineBorder(Color.BLACK));
button.setPreferredSize(new Dimension(30, 30));
buttonPanel.add(button);
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CalculatorPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
现在,您可以点击按钮或输入号码和值会被插入到文本字段中。
也许可以考虑使用'Action'代替,参见[如何使用操作(http://docs.oracle.com/javase /tutorial/uiswing/misc/action.html) – MadProgrammer
@kina'我无法使用add.ActionListener(this)'我会将其解释为“您仍然可以使用ActionListener”只是您不想让容器类实现了一个ActionListener。对? – user3437460