java jpopupmenu 无法显示_java – 从JButton显示/隐藏JPopupMenu; FocusListener无法正常工作?...
我需要一個帶有附加下拉樣式菜單的JButton.所以我拿了一個JPopupMenu并以你在下面的代碼中看到的方式將它附加到JButton.它需要做的是:
>單擊時顯示彈出窗口
>如果再次點擊,請隱藏它
>如果在彈出窗口中選擇了某個項目,則將其隱藏
>如果用戶點擊屏幕中的其他位置,則隱藏它
這4件事情都有效,但由于我正在使用的布爾標志,如果用戶點擊其他地方或選擇了一個項目,我必須在按鈕上單擊兩次才會再次顯示.這就是為什么我試圖添加一個FocusListener(絕對沒有響應)來修復它并在這些情況下將標志設置為false.
編輯:最后一次嘗試回答帖子……
以下是監聽器:(它在一個擴展JButton的類中,所以第二個監聽器在JButton上.)
// Show popup on left click.
menu.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
System.out.println("LOST FOCUS");
isShowingPopup = false;
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("GAINED FOCUS");
}
});
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("isShowingPopup: " + isShowingPopup);
if (isShowingPopup) {
isShowingPopup = false;
} else {
Component c = (Component) e.getSource();
menu.show(c, -1, c.getHeight());
isShowingPopup = true;
}
}
});
我現在已經用這個太久了.如果有人能給我一個關于這個問題的線索,那就太好了!
謝謝!
碼:
public class Button extends JButton {
// Icon.
private static final ImageIcon ARROW_SOUTH = new ImageIcon("ArrowSouth.png");
// Unit popup menu.
private final JPopupMenu menu;
// Is the popup showing or not?
private boolean isShowingPopup = false;
public Button(int height) {
super(ARROW_SOUTH);
menu = new JPopupMenu(); // menu is populated somewhere else
// FocusListener on the JPopupMenu
menu.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
System.out.println("LOST FOCUS");
isShowingPopup = false;
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("GAINED FOCUS");
}
});
// ComponentListener on the JPopupMenu
menu.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {
System.out.println("SHOWN");
}
@Override
public void componentResized(ComponentEvent e) {
System.out.println("RESIZED");
}
@Override
public void componentMoved(ComponentEvent e) {
System.out.println("MOVED");
}
@Override
public void componentHidden(ComponentEvent e) {
System.out.println("HIDDEN");
}
});
// ActionListener on the JButton
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("isShowingPopup: " + isShowingPopup);
if (isShowingPopup) {
menu.requestFocus();
isShowingPopup = false;
} else {
Component c = (Component) e.getSource();
menu.show(c, -1, c.getHeight());
isShowingPopup = true;
}
}
});
// Skip when navigating with TAB.
setFocusable(true); // Was false first and should be false in the end.
menu.setFocusable(true);
}
}
總結
以上是生活随笔為你收集整理的java jpopupmenu 无法显示_java – 从JButton显示/隐藏JPopupMenu; FocusListener无法正常工作?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java dbcp_Java dbcp连
- 下一篇: html5拍照上传 java_如何使用H