2013-02-01 91 views
-3

我有一个JButtons的数组,我已经在它们上面添加了一个ActionListener带有ActionListener和事件关键空间的JButton数组

然后我把new Thread(){ public void run(){} }.start();。当前JButton的背景将变成红色,3秒后变为白色,阵列中的下一个按钮变红。

现在我想为SPACE添加一个KeyEvent。这个想法是,当背景是红色的,我输入SPACE它应该关注当前按钮并为他执行动作监听器。 3秒后我输入SPACE再次按下阵列中的下一个按钮。

我需要一个解决方案。

+2

-1这是StackOverflow。如果您想让某人为您编码,请在职位上发帖。 – turnt

+4

你有什么尝试?你卡在哪里?考虑发布代码,一个编译,运行,显示你的问题,没有与你的问题无关的代码或获取代码运行的小程序,[sscce](http://sscce.org)。 –

回答

1

我以前见过这种类型的东西,如果我没有弄错的话,它是关于向禁用用户提供功能(如果没有,那是我以前见过的)。

首先...永远不要,从任何Thread以外的任何UI组件创建/修改其他事件调度线程。事实上,对于这个问题,我怀疑你实际上是否需要任何线程。

查看信息Concurrency in Swing

你也应该不需要任何类型的KeyListener。在最坏的情况下,您可能需要提供Key Binding,但在大多数外观和感觉下,空间被支持为“默认”接受操作,如输入

你真正想要做的是简单地将焦点移到突出显示的按钮上。

public class TestHelpButton { 

    public static void main(String[] args) { 
     new TestHelpButton(); 
    } 

    public TestHelpButton() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (Exception ex) { 
       } 

       JFrame frame = new JFrame("Test"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private JButton[] buttons = new JButton[]{ 
      new JButton(new BasicAction("Don't Panic")), 
      new JButton(new BasicAction("Panic")), 
      new JButton(new BasicAction("Cup of Tea")), 
      new JButton(new BasicAction("Destory the world")),}; 
     private int activeIndex = -1; 

     public TestPane() { 
      setLayout(new GridBagLayout()); 
      for (JButton btn : buttons) { 
       add(btn); 
      } 

      updateSelection(); 

      Timer timer = new Timer(3000, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        updateSelection(); 
       } 
      }); 
      timer.setRepeats(true); 
      timer.setCoalesce(true); 
      timer.start(); 
     } 

     protected void updateSelection() { 
      if (activeIndex >= 0) { 
       JButton btn = buttons[activeIndex]; 
       btn.setBackground(UIManager.getColor("Button.background")); 
      } 

      activeIndex++; 
      if (activeIndex > buttons.length - 1) { 
       activeIndex = 0; 
      } 
      JButton btn = buttons[activeIndex]; 
      btn.setBackground(Color.RED); 
      btn.requestFocusInWindow(); 
     } 
    } 

    public class BasicAction extends AbstractAction { 

     public BasicAction(String text) { 
      putValue(NAME, text); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      JOptionPane.showMessageDialog(null, getValue(NAME), "Helper", JOptionPane.INFORMATION_MESSAGE); 
     } 
    } 
} 

我提供一个工作示例的唯一原因是基于我的假设,这是为了向残疾用户提供额外的支持。