在 Java 中单击按钮创建菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5772396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create menu on button click in Java
提问by Daniel Fath
For a project we want to create a button which will make a tiny menu when it is clicked (the way it works is similar to back button's drop-down menu in Firefox although the way to activate is a simple left click). Only real constraint is that it has to be in Java (preferably swing if possible). So, any ideas, examples, codes on how to do it?
对于一个项目,我们想要创建一个按钮,当它被点击时会产生一个小菜单(它的工作方式类似于 Firefox 中的后退按钮的下拉菜单,尽管激活方式是简单的左键单击)。唯一真正的限制是它必须在 Java 中(如果可能,最好使用 Swing)。那么,关于如何做到这一点的任何想法,示例,代码?
回答by Andrew Thompson
Use a JPopupMenu
. E.G.
使用一个JPopupMenu
. 例如
PopUpMenuDemo.java
弹出菜单演示程序
import java.awt.event.*;
import javax.swing.*;
class PopUpMenuDemo {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JButton b = new JButton("Pop Up");
final JPopupMenu menu = new JPopupMenu("Menu");
menu.add("A");
menu.add("B");
menu.add("C");
b.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
menu.show(b, b.getWidth()/2, b.getHeight()/2);
}
} );
JOptionPane.showMessageDialog(null,b);
}
};
SwingUtilities.invokeLater(r);
}
}
Screenshot
截屏
回答by sepo
I would probably do it like this:
我可能会这样做:
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnClickMe = new JButton("Click me");
btnClickMe.setBounds(10, 30, 89, 23);
frame.getContentPane().add(btnClickMe);
final JPopupMenu menu = new JPopupMenu();
JMenuItem item1 = new JMenuItem("Item1");
JMenuItem item2 = new JMenuItem("Item2");
JMenuItem item3 = new JMenuItem("Item3");
menu.add(item1);
menu.add(item2);
menu.add(item3);
btnClickMe.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e){
if ( e.getButton() == 1 ){ // 1-left, 2-middle, 3-right button
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
回答by Gowtham Gutha
This is the code for menuButton
, it looks like a button, and when you click on it a menu appears. You can customize it by adding the image icon to the menu and by methods:
这是 的代码menuButton
,它看起来像一个按钮,单击它时会出现一个菜单。您可以通过将图像图标添加到菜单和方法来自定义它:
setFocusable(false);
setBorderPainted(false);
setOpaque(false);
If you want to get it like FireFox then set the icon for the menu and call the above methods, and then set the rollover icon, selected icon & rollover selected icon.
如果你想像FireFox一样获得它,那么设置菜单的图标并调用上述方法,然后设置滚动图标,选定图标和滚动选定图标。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class menuButton extends JFrame
{
JMenuBar fileMenuBar,editMenuBar;
JMenu fileMenu,editMenu;
JMenuItem newFile,open,save,saveas,exit;
JMenuItem cut,copy,paste,undo,redo;
public menuButton()
{
setTitle("menu Button");
setSize(500,500);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
fileMenuBar=new JMenuBar();
editMenuBar=new JMenuBar();
fileMenu=new JMenu("File");
editMenu=new JMenu("Edit");
newFile=new JMenuItem("New");
newFile.setAccelerator(KeyStroke.getKeyStroke('N',InputEvent.CTRL_MASK));
open=new JMenuItem("Open");
open.setAccelerator(KeyStroke.getKeyStroke('O',InputEvent.CTRL_MASK));
save=new JMenuItem("Save");
save.setAccelerator(KeyStroke.getKeyStroke('S',InputEvent.CTRL_MASK));
saveas=new JMenuItem("Save As");
saveas.setAccelerator(KeyStroke.getKeyStroke('A',InputEvent.CTRL_MASK));
exit=new JMenuItem("Exit");
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,InputEvent.ALT_MASK));
cut=new JMenuItem("Cut");
cut.setAccelerator(KeyStroke.getKeyStroke('X',InputEvent.CTRL_MASK));
copy=new JMenuItem("Copy");
copy.setAccelerator(KeyStroke.getKeyStroke('C',InputEvent.CTRL_MASK));
paste=new JMenuItem("Paste");
paste.setAccelerator(KeyStroke.getKeyStroke('V',InputEvent.CTRL_MASK));
undo=new JMenuItem("Undo");
undo.setAccelerator(KeyStroke.getKeyStroke('Z',InputEvent.CTRL_MASK));
redo=new JMenuItem("Redo");
redo.setAccelerator(KeyStroke.getKeyStroke('R',InputEvent.CTRL_MASK));
editMenu.add(cut);
editMenu.add(copy);
editMenu.add(paste);
editMenu.addSeparator();
editMenu.add(undo);
editMenu.add(redo);
fileMenu.add(newFile);
fileMenu.add(open);
fileMenu.add(save);
fileMenu.add(saveas);
fileMenu.add(exit);
fileMenuBar.add(fileMenu);
editMenuBar.add(editMenu);
add(fileMenuBar);
add(editMenuBar);
}
public static void main(String args[])
{
new menuButton();
}
}
回答by cMinor
see this it may be help you
看到这个它可能对你有帮助
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class GUI implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
private final BufferedImage offscreenImage; // double buffered image
private final BufferedImage onscreenImage; // double buffered image
private final Graphics2D offscreen;
private final Graphics2D onscreen;
private JFrame frame; // the top-level component
private JPanel center = new JPanel(); // center panel
// create a GUI with a menu, some buttons, and a drawing window of size width-by-height
public GUI(int width, int height) {
offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
onscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
offscreen = (Graphics2D) offscreenImage.getGraphics();
onscreen = (Graphics2D) onscreenImage.getGraphics();
// the drawing panel
ImageIcon icon = new ImageIcon(onscreenImage);
JLabel draw = new JLabel(icon);
draw.addMouseListener(this);
draw.addMouseMotionListener(this);
// label cannot get keyboard focus
center.add(draw);
center.addKeyListener(this);
// west panel of buttons
JPanel west = new JPanel();
west.setLayout(new BoxLayout(west, BoxLayout.PAGE_AXIS));
JButton button1 = new JButton("button 1");
JButton button2 = new JButton("button 2");
JButton button3 = new JButton("button 3");
JButton button4 = new JButton("button 4");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button1.setToolTipText("Click me");
west.add(button1);
west.add(button2);
west.add(button3);
west.add(button4);
// menu
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuSave = new JMenuItem(" Save... ");
menuSave.addActionListener(this);
menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuSave);
// setup the frame and add components
frame = new JFrame();
frame.setJMenuBar(menuBar);
frame.add(west, BorderLayout.WEST);
frame.add(center, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
// give the focus to the center panel
center.requestFocusInWindow();
frame.setVisible(true);
}
// draw picture (gif, jpg, or png) centered on (x, y)
public void picture(int x, int y, String filename) {
ImageIcon icon = new ImageIcon(filename);
Image image = icon.getImage();
offscreen.drawImage(image, x, y, null);
show();
}
// display the drawing canvas on the screen
public void show() {
onscreen.drawImage(offscreenImage, 0, 0, null);
frame.repaint();
}
/*************************************************************************
* Event callbacks
*************************************************************************/
// for buttons and menus
public void actionPerformed(ActionEvent e) {
Object cmd = e.getActionCommand();
if (cmd.equals(" Save... ")) System.out.println("File -> Save");
else if (cmd.equals("button 1")) System.out.println("Button 1 pressed");
else if (cmd.equals("button 2")) System.out.println("Button 2 pressed");
else if (cmd.equals("button 3")) System.out.println("Button 3 pressed");
else if (cmd.equals("button 4")) System.out.println("Button 4 pressed");
else System.out.println("Unknown action");
// don't hog the keyboard focus
center.requestFocusInWindow();
}
// for the mouse
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse pressed at " + x + ", " + y);
offscreen.setColor(Color.BLUE);
offscreen.fillOval(x-3, y-3, 6, 6);
show();
}
public void mouseClicked (MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered (MouseEvent e) { }
public void mouseExited (MouseEvent e) { }
public void mouseDragged (MouseEvent e) { }
public void mouseMoved (MouseEvent e) { }
// for the keyboard
public void keyPressed (KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) {
System.out.println("Key = '" + e.getKeyChar() + "'");
}
// test client
public static void main(String[] args) {
GUI gui = new GUI(800, 471);
gui.picture(0, 0, "map.png");
gui.show();
}
}
回答by Danger
If you like lesser code lines in your code try below code:
如果您喜欢代码中较少的代码行,请尝试以下代码:
Inside your buttons actionPerformed:
在你的按钮 actionPerformed 中:
private void yourButtonActionPerformed(java.awt.event.ActionEvent evt) {
final JPopupMenu yourMenu = new JPopupMenu("Settings");
menu.add("Name");
menu.add("Id");
menu.add(new Button()); // can even add buttons and other components as well.
menu.show(yourButton, yourButton.getWidth()/2, yourButton.getHeight()/2);
}