问题描述
- tf.setBounds(80,90, 200, 200); 把90改成91试试
-
import java.awt.*;
import java.awt.event.*;
import java.util.Random;import javax.swing.*;
public class Three extends JFrame implements ActionListener{
/** * */ private static final long serialVersionUID = -8560277451929244119L; JTextField tf = new JTextField(); JButton b1 = new JButton("开始"); JButton b2 = new JButton("停止"); JButton b3 = new JButton("END"); boolean isGo = false; public Three() { this.getContentPane().setLayout(null); this.setExtendedState(JFrame.MAXIMIZED_BOTH); tf.setBounds(80,90, 200, 200); b1.setBounds(1,100,10,10); b2.setBounds(1,200,10,10); b3.setBounds(1,300,10,10); this.getContentPane().add(tf); this.getContentPane().add(b1); this.getContentPane().add(b2); this.getContentPane().add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); SymListener sy = new SymListener(); b1.registerKeyboardAction(sy,KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); b2.registerKeyboardAction(sy,KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); b3.registerKeyboardAction(sy,KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); b2.setEnabled(false); this.setVisible(true); tf.setText("888888"); go(); } public void go() { while (true) { if (isGo == true) { String s = ""; for (int j = 1; j <= 1; j++) { int i = (int) (Math.random()*10000+1);//设定奖项总数 if (i < 10) { s = s + "00000" + i; } else if(i<100 & i>=10) { s = s + "0000" + i; }else if(i<1000 & i>=100) { s = s + "000" + i; }else if(i<10000 & i>=1000) { s = s + "00" + i; }else if(i<100000 & i>=10000) { s = s + "0" + i; }else { s = s + i; } } tf.setText(s); } try { Thread.sleep(10); } catch (java.lang.InterruptedException e) { e.printStackTrace(); } } } public void actionPerformed(ActionEvent e) { } public static void main(String[] args) { new Three(); } class SymListener implements ActionListener { public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj == b1) { isGo = true; b1.setEnabled(false); b2.setEnabled(true); } else if (obj == b2) { isGo=false; b2.setEnabled(false); b1.setEnabled(true); }else if (obj == b3) { dispose(); } } }
}
解决方案
我为什么要改呢?为什么呢?
解决方案二:
改后在按空格 看数字变不变 为什么不变了。 BUG吗? 如果把 KeyEvent.VK_SPACE, 换成别的快捷键就没问题
解决方案三:
修改一
//b1.registerKeyboardAction(sy,KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); //搜索这句,然后注释,增加下面,其他按钮也可以一样处理
b1.getInputMap(JComponent.WHEN_FOCUSED).put(
KeyStroke.getKeyStroke((char)KeyEvent.VK_SPACE), "PressKeyAction");
b1.getActionMap().put("PressKeyAction", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
isGo = true;
b1.setEnabled(false);
b2.setEnabled(true);
}
});
修改二
this.setVisible(true);
tf.setText("888888");//搜索这句
b1.requestFocus();//增加获取焦点
时间: 2024-09-19 05:36:38