java在按下按钮或失去焦点时切换JDialog可见性
爪哇大师
当按下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);
}
}
# 1 楼答案