I want to create a Toolbar for my application. If you click a button on that toolbar , it will pop-up a menu , just like the toolbar of eclipse. I don't know how to do it in Swing. Can someone help me please ? I've try google but found nothing.
+1
A:
I think it's the same as in AWT.
You should put an ActionCommand on that button and when it's executed show the pop-up menu according to the mouse coordinates.
Cristina
2009-11-07 10:50:07
A:
I'm not sure I understand you correctly but if you want to know how to make toolbars in Swing check this
Java Tutorials: How to Use Tool Bars and this
jitter
2009-11-07 11:30:34
+2
A:
This is way harder in Swing than it needs to be. So instead of pointing you to tutorials I've created a fully working example.
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);
}
}
Steve McLeod
2009-11-07 15:02:10
I have been doing something like this, but without the JToolBar. Does your solution have the behavior where if you click the button again with the menu up, it pops up the menu again, instead of dismissing it?
Adam Goode
2009-11-07 15:08:17
I also did something slightly differently: popup.show(c, 0, c.getHeight());
Adam Goode
2009-11-07 15:09:33
Thank you. This is the easiest to understand solution that I've found, so I'll use it although it's not exactly a Dropdown JButton.The other solutions are too complicated for me to understand. I've list some of them below.<http://netbeans.dzone.com/news/drop-down-buttons-swing-new-alhttp://www.pushing-pixels.org/?p=199
Dikei
2009-11-07 16:15:26
As far I know, there is no dropdown JButton. You have to craft your own, perhaps by adding an appropriate icon to the JButton.
Steve McLeod
2009-11-08 10:11:07
A:
Hi there,
can you help me in setting the getComponent into a fix location.
Dondell
2010-08-12 03:37:17