我有一个弹出式菜单,但当我点击某些东西时它会关闭。
大多数时候这没问题,但有时需要它不会在点击时关闭!
这是我正在处理的一段代码,可以帮助您重现我所拥有的:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Try{
public static void main(String[] args) {
JFrame frame = new JFrame("Trial");
JPopupMenu menu = new JPopupMenu();
JLabel label = new JLabel("This is a popup menu!");
menu.add(label);
frame.setSize(900, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
menu.show(frame, 450, 250);
}
}
我想要的是,如果我点击框架,菜单不会关闭!
答案 0 :(得分:2)
适合工作的合适工具。
考虑一个非模态、未修饰的 dialog(而不是 JPopupMenu
)。
这是您需要的那种东西吗?
import java.awt.Color;
import javax.swing.*;
public class Try{
public static void main(String[] args) {
JFrame frame = new JFrame("Trial");
JLabel label = new JLabel("This is a popup menu!");
label.setBorder(BorderFactory.createLineBorder(Color.red, 2));
frame.setSize(900, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JDialog dlg = new JDialog(frame);
dlg.add(label);
dlg.setUndecorated(true);
dlg.pack();
dlg.setLocationRelativeTo(frame);
dlg.setVisible(true);
}
}
这是我电脑上的样子。
如果您点击 JFrame
,对话框仍然可见。
答案 1 :(得分:2)
所以这可以通过 JPopupMenu 本身实现,不需要 JDialog。
我必须重写 setVisible 方法并允许仅在调用 close 方法后关闭弹出窗口!
这是弹出菜单只会在 5000 毫秒后关闭而不是在点击时关闭的代码!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Try{
public static void main(String[] args) {
JFrame frame = new JFrame("Trial");
MyPopupMenu menu = new MyPopupMenu();
JLabel label = new JLabel("This is a popup menu!");
menu.add(label);
frame.setSize(900, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
menu.show(frame, 450, 250);
Timer timer = new Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menu.closePopup();
((Timer)evt.getSource()).stop();
}
});
timer.start();
}
}
class MyPopupMenu extends JPopupMenu{
private boolean isHideAllowed;
public MyPopupMenu(){
super();
this.isHideAllowed = false;
}
@Override
public void setVisible(boolean visibility){
if(isHideAllowed && !visibility)
super.setVisible(false);
else if(!isHideAllowed && visibility)
super.setVisible(true);
}
public void closePopup(){
this.isHideAllowed = true;
this.setVisible(false);
}
}
答案 2 :(得分:-1)
您需要设置正确的defaultCloseOperation-
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Try{
public static void main(String[] args) {
JFrame frame = new JFrame("Trial");
JPopupMenu menu = new JPopupMenu();
JLabel label = new JLabel("This is a popup menu!");
menu.add(label);
frame.setSize(900, 500);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addWindowsListener(new WindowAdapter(){
//Determine whether you should call frame.dispose or hide.
});
menu.show(frame, 450, 250);
}
}