有没有办法在 Java 中实现下拉按钮,但没有实现JMenuBar
?我需要导入一个带有弹出菜单的按钮。我怎样才能做到这一点?
问问题
786 次
2 回答
1
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class MenuButton extends JToggleButton {
JPopupMenu popup;
public MenuButton(String name, JPopupMenu menu) {
super(name);
this.popup = menu;
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
JToggleButton b = MenuButton.this;
if (b.isSelected()) {
popup.show(b, 0, b.getBounds().height);
} else {
popup.setVisible(false);
}
}
});
popup.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
MenuButton.this.setSelected(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {}
});
}
}
于 2015-04-28T08:22:55.003 回答
1
正如@DavidKroukamp 所说,JPopupMenu 应该可以解决问题。
于 2013-07-03T22:24:11.380 回答