Java Gurus,
当按下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);
}
}
答案 0 :(得分:0)
dialog.setVisible(!dialog.isVisible());