【发布时间】:2015-08-19 15:17:48
【问题描述】:
Java 大师,
希望在按下 JButton 或 JDialog 失去焦点时切换 JDialog 的可见性,即当 JDialog 之外的另一个屏幕区域变为活动状态时。失去焦点工作正常,因为它是由 WindowFocusListener 处理的,但我无法获得 JButton 的功能,即第一次单击 => JDialog 可见,第二次单击 => JDialog 不可见,第三次单击 => JDialog 可见。
我真的不想沿着制作 JDialog 模态或计算按钮点击次数的路线走下去。
有任何想法以简单、干净的方式实现上述功能吗?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.*;
public class TestFrameExample {
public static void main(String s[]) {
final JDialog dialog = new JDialog();
final JButton button = new JButton();
JFrame frame = new JFrame("Help me toggle JDialog!");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("Dialog visibility should toggle when JButton is pressed!");
button.setText("Toggle Dialog");
button.setFocusable(false);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
dialog.setVisible(!dialog.isVisible());
dialog.setLocation(new Point(button.getLocationOnScreen().x, button.getLocationOnScreen().y+30));
}
});
dialog.setSize(new Dimension(110,80));
dialog.setVisible(false);
dialog.setBackground(null);
dialog.setModal(false);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(false);
dialog.setUndecorated(true);
dialog.addWindowFocusListener(new WindowFocusListener(){
public void windowLostFocus(WindowEvent arg0) {
dialog.setVisible(false);
}
public void windowGainedFocus(WindowEvent e) {
}
});
((JComponent) dialog.getContentPane()).setBorder(new RoundedBorder(Color.gray, 1,1,12));
((JComponent) dialog.getContentPane()).setOpaque(false);
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(350, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
【问题讨论】:
标签: java swing jbutton jdialog focuslistener