怎样将Button和键盘上的按键建立起一一对应的关系 比如我做了个按键1,鼠标监听的已经弄好了,我想将它和键盘上的1键建立起对应的关系啊? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class T{ public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } final JTextField tf = new JTextField(); tf.setEnabled(false); JPanel p = new JPanel(new GridLayout(0, 3, 5, 5)); for (int i = 0; i <= 9; i++) { final JButton btn = new JButton(String.valueOf(i)); p.add(btn); btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke((char)(i + '0')), "PressKeyAction"); btn.getActionMap().put("PressKeyAction", new AbstractAction() { public void actionPerformed(ActionEvent e) { btn.doClick(); } }); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tf.setText(tf.getText() + btn.getText()); } }); } JFrame f = new JFrame(); JComponent contentPane = (JComponent) f.getContentPane(); contentPane.setLayout(new BorderLayout(0, 5)); contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); f.getContentPane().add(p, BorderLayout.CENTER); f.getContentPane().add(tf, BorderLayout.NORTH); f.pack(); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }} Java中的死锁问题 在Java tutorial中的经典问题 Alphonse 和 Gaston 是好朋友。下面是程序。 关于java数组的一道题目 List 泛型报错,哪写错了? socket中的IO类的疑惑!求救!!! 请帮我看一下这个输入输出类错在哪里? 简单问题? java mail 请问java里的类到底存放在哪个物理目录下? 怎样显示保存和打开对话框? applet一个奇怪的技巧 在JAVA中如何实现链表? 如何让JTree初始化的时候全部展开?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.*;public class T
{
public static void main(String[] args)
{
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
} final JTextField tf = new JTextField();
tf.setEnabled(false);
JPanel p = new JPanel(new GridLayout(0, 3, 5, 5));
for (int i = 0; i <= 9; i++) {
final JButton btn = new JButton(String.valueOf(i));
p.add(btn);
btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke((char)(i + '0')), "PressKeyAction");
btn.getActionMap().put("PressKeyAction", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
btn.doClick();
}
});
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tf.setText(tf.getText() + btn.getText());
}
});
}
JFrame f = new JFrame();
JComponent contentPane = (JComponent) f.getContentPane();
contentPane.setLayout(new BorderLayout(0, 5));
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
f.getContentPane().add(p, BorderLayout.CENTER);
f.getContentPane().add(tf, BorderLayout.NORTH);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}