我正在尝试构建一个在按下时JToggleButton
显示 a JDialog
(包含 a JList
)的a 。JToggleButton
并在再次按下JDialog
时消失JToggleButton
,或者如果用户单击离开或在框架中的其他位置(我通过 a 模拟FocusListener
了JList
焦点丢失时的情况)。
依次按下按钮将JDialog
正确显示和隐藏。
但是,问题是当JDialog
可见时,我单击框架上的其他位置,JDialog
焦点丢失时正确消失。但是,JToggleButton
仍然错误地设置为选中状态。这意味着单击JToggleButton
now 不会显示 theJDialog
状态,因为JToggleButton
now 的状态不同步。相反,我需要按JToggleButton
两次才能JDialog
再次看到。我下面的代码示例演示了这个问题。
我似乎无法让失去的焦点JList
与JToggleButton
. 这似乎是一个简单的问题,但我一直在努力寻找解决方案。任何人都可以帮忙吗?谢谢。
请参阅下面的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class MultiComboBox extends JToggleButton
{
public MultiComboBox(JFrame frame, String buttonText)
{
super(buttonText);
JDialog dialog = new JDialog(frame, false);
dialog.setLayout(new BorderLayout());
Object[] items = new Object[] { "one", "two", "three" };
JList list = new JList(items);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane listScrollPane = new JScrollPane(list,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
listScrollPane.setPreferredSize(list.getPreferredSize());
dialog.add(listScrollPane, BorderLayout.CENTER);
dialog.pack();
addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
final JToggleButton button = (JToggleButton) e.getSource();
System.out.println("button clicked: " + button.isSelected());
if (button.isSelected())
{
Point p = button.getLocation();
p.setLocation(p.getX() + 300, p.getY());
SwingUtilities.convertPointToScreen(p, button);
dialog.setLocation(p);
dialog.setVisible(true);
}
else
dialog.setVisible(false);
}
});
list.addFocusListener(new FocusListener()
{
@Override
public void focusGained(FocusEvent e)
{
}
@Override
public void focusLost(FocusEvent e)
{
System.out.println("list focusLost, dialog: " + dialog.isVisible());
dialog.setVisible(false);
}
});
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Test");
frame.setPreferredSize(new Dimension(300, 300));
frame.setLayout(new BorderLayout());
MultiComboBox mcb = new MultiComboBox(frame, "Toggle");
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setPreferredSize(new Dimension(80, 30));
buttonPanel.add(mcb, BorderLayout.CENTER);
JPanel blankPanel = new JPanel(new BorderLayout());
frame.add(blankPanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_START);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}