在Swing中,这比需要做的难。因此,我没有为您提供教程,而是创建了一个完整的示例。
import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;public class ToolbarDemo { public static void main(String[] args) { final Jframe frame = new Jframe(); frame.setPreferredSize(new Dimension(600, 400)); final JToolBar toolBar = new JToolBar(); //Create the popup menu. final JPopupMenu popup = new JPopupMenu(); popup.add(new JMenuItem(new AbstractAction("Option 1") { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(frame, "Option 1 selected"); } })); popup.add(new JMenuItem(new AbstractAction("Option 2") { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(frame, "Option 2 selected"); } })); final JButton button = new JButton("Options"); button.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { popup.show(e.getComponent(), e.getX(), e.getY()); } }); toolBar.add(button); frame.getContentPane().add(toolBar, BorderLayout.NORTH); frame.pack(); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); }}


