如何在JPanel失去焦点后按下JButton

时间:2011-09-27 00:39:01

标签: java swing jbutton

我已经找到了如何使用以下代码将JButton保持在其按下状态:

JButton[] buttons;
.
.
.
public void actionPerformed(ActionEvent e)
{

    for(int i = 0; i < buttons.length; i++)
    {
        if(e.getSource() == buttons[i])
        {
            buttons[i].getModel().setPressed(true);
        }
        else
        {
            buttons[i].getModel().setPressed(false);
        }

    }
}

此代码捕获单击的按钮,按住它,并使面板上的所有其他按钮都未按下。这段代码效果很好......直到窗口失去焦点(或者更具体地说,它的父JPanel失去焦点)。之后,所有按钮都返回到非按下状态。

目前关于如何编写WindowFocusListeners的教程已关闭。有没有办法让JButton的压缩状态因失去焦点而持续存在?

1 个答案:

答案 0 :(得分:16)

为什么不简单地使用一系列JToggleButtons并将它们添加到同一个ButtonGroup对象中?所有的辛苦工作都是为您完成的,因为切换按钮可以按下时保持按下状态。可以把它想象成一个看起来像JButton的JRadioButton(因为实际上,JRadioButton 从JToggleButton下降)。

例如:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class BunchOfButtons extends JPanel {
   private static final String[] TEXTS = {"One", "Two", "Three", "Four", "Five"};
   private ButtonGroup btnGroup = new ButtonGroup();
   private JTextField textField = new JTextField(20);

   public BunchOfButtons() {
      JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      BtnListener btnListener = new BtnListener();
      for (String text : TEXTS) {
         JToggleButton toggleBtn = new JToggleButton(text);
         toggleBtn.addActionListener(btnListener);
         toggleBtn.setActionCommand(text);
         btnPanel.add(toggleBtn);
         btnGroup.add(toggleBtn);
      }

      JPanel otherPanel = new JPanel();
      otherPanel.add(textField ); // just to take focus elsewhere

      setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      setLayout(new GridLayout(0, 1, 0, 15));
      add(btnPanel);
      add(otherPanel);
   }

   private class BtnListener implements ActionListener {
      public void actionPerformed(ActionEvent aEvt) {
         textField.setText(aEvt.getActionCommand());
      }
   }

   private static void createAndShowGui() {
      BunchOfButtons mainPanel = new BunchOfButtons();

      JFrame frame = new JFrame("BunchOfButtons");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}