I need to create a comboBox with multiple chechboxes in my java swing gui. My first thought was to create a custom comboBox with its own CellRenderer but then I decided to go with a more "friendly" solution and use JMenu with JCheckBox items inside.
The problem is, that when I create the menu and place it inside my JPanel, the menu is not active and it does not open when being clicked. Any ideas what may be the cause of this behavior? Is it even possible to use JMenu like this?
This is a sample of my code:
JMenu menu;
panelCenter.add(new JLabel("Selection"));;
panelCenter.add(prepareSelection(menu));
private JMenu prepareSelection(JMenu menu) {
menu = new JMenu("Select items");
for (int i = 0; i < 10; i++) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem("item " + i);
menu.add(item);
}
return menu;
}
Thanks for any help!
The place to add a JMenuBar is not in the JPanel, but in the layeredPane. You should add the JMenuBar, and it will reside at the top of the layeredPane. The rest of it will be covered by your contentPane. Once the JMenuBar is up you can modify the JMenus and the JMenuItems any time.
Here is a picture from Ivor Horton's Beginning Java:
Solved. First added JMenuBar to my JPanel and then add JMenus to it.
menuBar = new JMenuBar();
prepareSelection(menuInput); // prepare menus
prepareSelection(menuOutput);
panelCenter.add(menuBar);
Related
In JMenuBar there are many JMenu, one of them is 'Tables'. In this JMenu I added many JMenuItem's from database, but i don't know how can i add action listener to them. Can anyone tell how?
I don't know how you are adding everything dynamically but in this case you should be able to add an ActionListener to every object into whatever looping code you're facing. I will put here below and example of a for loop passing through a List of JMenuItems.
for(int i = 0; i < menuItemsList.size(); i++){
JMenuItem item = menuItemList.get(i);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
//the code you want to execute in the event
}
});
}
In this case every JMenuItem will have an event.
Hope this can help, I can't do to much if you do not put an example of your code.
Regards.
I've added a a custom JPane and a custom JMenuBar to my JFrame. The JPane shows up just fine, but not the JMenuBar. I've defined the frame and the menu bar in different classes
Here's the frame class:
public class pixelFrame { //This frame will hold the a pixelPane for art creation. This will also hold a menu bar, defined in another file.
pixelPane editingArea;
pixelMenuBar menuBar;
public pixelFrame()
{
EventQueue.invokeLater(new Runnable() { //create a new thread at runtime
#Override
public void run() { //when the program runs, do the following
JFrame frame = new JFrame("Pixel Art Creator"); //create a new JFrame (similar to a regular window), and give it the following title
editingArea = new pixelPane();
menuBar = new pixelMenuBar();
frame.add(editingArea); //add a pixelPane named editingArea to the JFrame
frame.setJMenuBar(menuBar); //adds a menu to the JFrame
frame.pack(); //make the window big enough to fit all components (in this case, editingArea)
frame.setLocationRelativeTo(null); //set window to the center of the screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Stop the thread and terminate the program.
frame.validate();
frame.setVisible(true); //You can see the window.
menuBar.setVisible(true);
}
});
}
public static void main(String[] args)
{
pixelPane.gridEnabled = true; //changing another variable from pixelPane just for testing.
new pixelFrame(); //create an instance of pixelFrame.
}
}
And here's the menu bar:
public class pixelMenuBar extends JMenuBar {
/**
*
*/
private static final long serialVersionUID = 1L;
JMenuBar menuBar;
JMenu file, tool;
JMenuItem save, load, changeColor;
JCheckBoxMenuItem gLines;
public pixelMenuBar() {
menuBar = new JMenuBar();
//creates a "File" menu in the menu bar
file= new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
menuBar.add(file); //add the menu to the menu bar
//creates a "Tools" menu in the menu bar
tool = new JMenu("Tools");
tool.setMnemonic(KeyEvent.VK_T);
menuBar.add(tool);
//Menu items that go under the File menu
save = new JMenuItem("Save File"); //save and export the image as an .svg file
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.CTRL_DOWN_MASK,KeyEvent.VK_S)); //a Ctrl+S hotkey. Handy dandy!
file.add(save);//adds the Save button to the File menu
load = new JMenuItem("Load File"); //load the file into BufferedImage, make it into a JLabel and add it to the panel.
load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.CTRL_DOWN_MASK,KeyEvent.VK_L));//a Ctrl+L hotkey. Also handy dandy!
file.add(load);//adds the Load button to the File menu
//Menu items that will go under the Tools menu
gLines = new JCheckBoxMenuItem("Gridlines"); //creates a new checkbox for enabling grid lines. will toggle pixelPane.gridEnabled
gLines.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.CTRL_DOWN_MASK,KeyEvent.VK_G));
tool.add(gLines);//adds the gridlines tool to the Tools menu
tool.addSeparator(); //adds a separating line in the Tools menu. Organization.
changeColor = new JMenuItem("Change Color");//creates a new menu item that will let the user the color of the pixel. Uses a color picker
tool.add(changeColor);//adds Change Color to the Tools menu
}
}
Am I not adding something to the UI correctly? I double checked that I'm using addJMenuBar() and not addMenuBar().
First of all class names SHOULD start with an upper case character. Have you ever seen a class in the Java API that doesn't? Follow Java conventions. Learn by example.
public class pixelMenuBar extends JMenuBar
{
...
public pixelMenuBar()
{
menuBar = new JMenuBar();
Your class "is a " JMenuBar, but the first thing you do in the class is create a JMenuBar.
Don't create the JMenuBar!
Just add the menu items to the JMenuBar class itself:
//menuBar.add(file); //add the menu to the menu bar
add(file); //add the menu to the menu bar
In reality there is no need to even have a PixelMenuBar class, since you are not adding any new functionality to the JMenuBar. Just add a method to your main class like createMenuBar(...) that creates the JMenuBar and adds the JMenu/JMenuItem objects.
I'm learning GUI programming in java, and trying to modify an existing programme to add a new menu bar at the top of the frame.
The main method is below. The MainPanel class extends JPanel and contains the main components of the programme (a basic game).
public static void main(String[] args) {
JFrame frame = new JFrame("Sokuban");
MainPanel panel = new MainPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
I'm not sure if I should add a new JPanel, add it to the JFrame, and then within that add buttons? Or create a JMenuBar, within the existing panel, or frame, and then use BorderLayout.NORTH to arrange it?
Just playing around with things I found on google, I've tried the following snippets separately (haven't put all code in):
JMenuBar menuBar = new JMenuBar();
frame.add(new Button("Button"), BorderLayout.SOUTH);
panel.BorderLayout.SOUTH;
JPanel frame2 = new JPanel();
window.add(frame2, BorderLayout.NORTH);
JButton b1 = new JButton();
frame2.setSize(500,500);
b1.setSize(400,400);
b1.setVisible(true);
b1.setText("Button");
frame2.add(b1);
frame2.setVisible(true);
I can't figure out which direction I should be going in. Any pointers v much appreciated!
First : https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html :)
This is quite easy tutorial of JMenuBar. :)
And if you one want to only a button on JBarMenu :
How to make a JMenu have Button behaviour in a JMenuBar
I'm not sure if I should add a new JPanel, add it to the JFrame, and then within that add buttons? Or create a JMenuBar, within the existing panel, or frame, and then use BorderLayout.NORTH to arrange it?
Here are some personal experience that I can share with you:
I will usually plan the appearance of my user interface first (Either on paper on in my mind). After that, decide a suitable layout manager for the container.
I can have nested panels with more than 1 layout if the UI is complicated.
But ultimately, I will usually have a main panel which hold every other components (subpanels / buttons / textFields..).
Add the main panel into the JFrame. (You can have a customized JPanel, and we rarely need a customized JFrame).
As for the menu bar:
Add JMenuItem to JMenu
Add JMenu to JMenuBar
Add JMenuBar to the Frame using frame.setJMenuBar(menuBar);
The following image should help you in understanding of the hierarchy:
Don't do that, check this out it's what you're looking for
This link is for a JMenuBar
https://docs.oracle.com/javase/7/docs/api/java/awt/MenuBar.html
This link is for a JMenu https://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html
This link is for a JMenuItem
https://docs.oracle.com/javase/7/docs/api/javax/swing/JMenuItem.html
You don't need a new JFrame to create a menu, you can use the JMenuBar();
JMenuBar myMenu = new JMenuBar();
//The above snippet does not create or add menus it's simply the container that holds them
JMenu fileMenu = new JMenu("File"); // This will create a menu named file
JMenuItem openChoice = new JMenuItem("Open"); /* This will create an option under
the fileMenu named open*/
//To Actually add these things you would do this
setJMenuBar(myMenu);
myMenu.add(fileMenu); // This adds fileMenu to the menubar
fileMenu.add(openChoice); // This adds openChocie to the JMenu named fileOption
Now the above code was a very basic example as to how to setup a menu I would sugesst following the code I outlined here and as you learn to improve upon this as this is just a starting point for you!
I've created a JPopupMenu with two items (add,remove). I want "addItem" to have a sub popup menu. The hierarchy is like this:
add
pizza
cake
...
remove
my code:
JPopupMenu menu = new JPopupMenu();
menu.add(new JMenuItem("remove"));
JMenuItem addItem = new JMenuItem("add");
menu.add(addItem);
addItem.add(new JPopupMenu()); // it is not working for me
Once I move the mouse close to "add item", the menu disappears.
please help me to build this popup menu.
Use a JMenu (sub class of JMenuItem).
JPopupMenu menu = new JPopupMenu();
menu.add(new JMenuItem("remove"));
JMenuItem addItem = new JMenu("add");
menu.add(addItem);
addItem.add(new JMenuItem("pizza"));
addItem.add(new JMenuItem("cake"));
I try to make my JMenuBar to activate first JMenu on Alt KeyEvent, but without opening popup, so that one could open popup with arrows keystrokes later. Just like it is done in NetBeans, Mozilla, any other program window.
Here is the code that works not as intended. The worst side effect is that it reacts on alt+tab combination, and it definitely should not popup menu on alt+tab. I just need to make a menu go to the "armed" state and be able to traverse menus by arrow keys (arrows right & left to "arm" menus and arrow down to open "armed" menu popup). Is there any simple way to make this happen?
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class Test5 extends JFrame {
public Test5() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pan = new JPanel(new BorderLayout());
final JMenuBar bar = new JMenuBar();
final JMenu menu = new JMenu("File", false);
menu.setMnemonic(KeyEvent.VK_ALT);
JMenuItem item = new JMenuItem("All");
JMenuItem item2 = new JMenuItem("Exit");
menu.add(item);
menu.add(item2);
JMenu menu1 = new JMenu("Test");
JMenuItem item1 = new JMenuItem("All");
menu1.add(item1);
bar.add(menu);
bar.add(menu1);
setJMenuBar(bar);
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
new Test5();
}
}
Solved thanks to Guillaume Polet:
There is some code in com.sun.java.swing.plaf.windows.WindowsLookAndFeel class, wich works with Alt keystrokes:
public void initialize() {
super.initialize();
// some more initialization here
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventPostProcessor(WindowsRootPaneUI.altProcessor);
}
And the AltProcessor class does all the magic.
If you don't have any custom LaF, you can just use WindowsLookAndFeel as it is, or there is proper example how to process Alt events in menus for your own special LaF.
Before starting your GUI, invoke this line:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
And remove the mnemonic.
This will automatically install the desired behaviour on Windows.
If you need this on all platforms, then you will have to go with KeyBindings, but since this behaviour is only observed on Windows, I don't find it problematic to recreate it only on Windows.
no idea why, but about answering the question
1st step
have to use KeyBindings and with output to the Swing Action (adviced) or ActionListener
there are two methods menu.setArmed(true) or menu.setSelected(true)
but in both cases JMenu is selected forever then to required 2nd. step to add MenuListener and restore previous selected or armed to false