Menu bar not showing in JFrame - java

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.

Related

Swing Actions - Linking Menus and Toolbar

I've been studying Java Swing and I'm working on learning actions.
I can successfully create action objects and use them to link items from a JToolBar to JMenuItems. My problem, is that the constructed actions display both icons and text in the toolbar (should only be the icons).
Check out the following code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MenuDemo{
MenuDemo(){
JFrame jfrm = new JFrame("Complete Menu Demo");
jfrm.setSize(220, 200);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar jmb = new JMenuBar();
/* Make the action object */
ImageIcon setIcon = new ImageIcon("setBP.png");
DebugAction setAct = new DebugAction("Set Breakpoint",
setIcon, KeyEvent.VK_S,
KeyEvent.VK_B, "Set Breakpoint");
/* Make the toolbar */
JButton jbtnSet = new JButton(setAct);
JToolBar jtb = new JToolBar("Breakpoints");
jtb.add(jbtnSet);
/* Make the menu */
JMenu jmDebug = new JMenu("Debug");
JMenuItem jmiSetBP = new JMenuItem(setAct);
jmDebug.add(jmiSetBP);
jmb.add(jmDebug);
jfrm.getContentPane().add(jtb, BorderLayout.NORTH);
jfrm.setJMenuBar(jmb);
jfrm.setVisible(true);
}
class DebugAction extends AbstractAction{
public DebugAction(String name, Icon image, int mnem,
int accel, String tTip){
super(name, image);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel,
InputEvent.CTRL_MASK));
putValue(MNEMONIC_KEY, new Integer(mnem));
putValue(SHORT_DESCRIPTION, tTip);
}
public void actionPerformed(ActionEvent ae){
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new MenuDemo();
}
});
}
}
This program yields the following GUI:
I just want the green button in the JToolBar, not text. I think my problem code is in the DebugAction constructor, where I call super(name, image). For the toolbar buttons, I would only want to pass in the image. But for the menu I want both. How can I "turn off" the text for the JToolBar items? Thanks!
How can I "turn off" the text for the JToolBar items?
You turn it off using:
JButton button = new JButton( action );
button.setHideActionText( true );
Or, you can just reset the text on the button:
JButton button = new JButton( action );
button.setText("");
I accepted camickr's answer, but there is a caveat.
For identification purposes, I am grabbing the actionCommand of these buttons. Both setHideActionText(true); and button.setText("") do remove the text, but both produce errors when I try to grab the actionCommand.
To fix this, I explicitly set the actionCommand when I create the action object by adding the additional line in the constructor:
putValue(ACTION_COMMAND_KEY, sometext);
This fixed the errors.

How to make JMenuBar activate menu without popping it up?

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

Creating a JPanel

My main class displays a JMenuBar. This JMenuBar is managed from "calculator.ui.MenuBar."
public JMenuBar createMenuBar()
{
JMenuBar menuBar = new JMenuBar();
new calculator.ui.MenuBar(menuBar);
return menuBar;
}
MenuBar creates my "File" JMenu and "Insert" JMenu.
public MenuBar(JMenuBar menuBar)
{
new FileMenu(menuBar);
new InsertMenu(menuBar);
}
FileMenu contains all the options for "File." In the File class, there is a JMenuItem called "New Calculator." Now, when you click "New Calculator," I want the JPanel in my main class to create an instance of Calculator in my main class.
newFileSubMenu = new JMenu("New...");
calculatorFileSubMenu = new JMenuItem("New Calculator");
calculatorFileSubMenu.getAccessibleContext().setAccessibleDescription(
"New Calculator");
newFileSubMenu.add(calculatorFileSubMenu);
ActionListener newCalculatorListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
newCalculator();
}
};
calculatorFileSubMenu.addActionListener(newCalculatorListener);
This is the code for my main class JPanel:
public Container createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
JTabbedPane tabbedPane = new JTabbedPane();
return contentPane;
}
My questions are related to the design of my program. For each instance of Calculator, I want to:
Create a JPanel within the main JPanel that contains my Calculator (what stumps me here is how do I - from my FileMenu class - create a JPanel that's in my main class?).
Make sure that the Calculator object refreshes.
Note: I also want my JPanels to be in TabbedPanes (if that changes anything; if it doesn't, then I can figure that part out once I know the answer for the first question.)
Thanks for your help, I hope I've been clear enough in what I want to do.
In your menu item's Action, you can use setSelectedIndex() on your JTabbedPane to select the pane holding an existing calculator instance. You can use setComponentAt() to replace the content of any tab with an instance of your calculator.
There's a related example here.

a GUI java program needing an action event button

I am making a simple java program that represents a Microsoft Word menu bar, and in the file menu I add an exit button... it does nothing.
I need your help to tell me what to do to make the exit button actually exit and close the program.
Here is my code:
public class MicrosoftWordMenu {
public static void main(String [] args)
{
JPanel panel = new JPanel();
JFrame frame = new JFrame("Microsoft Word");
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenu menu1 = new JMenu("Edit");
JMenu menu2 = new JMenu("View");
JMenu menu3 = new JMenu("Insert");
JMenu menu4 = new JMenu("Format");
JMenu menu5 = new JMenu("Tools");
JMenu menu6 = new JMenu("Table");
JMenu menu7 = new JMenu("Window");
JMenu menu8 = new JMenu("Help");
frame.add(bar, BorderLayout.NORTH);
frame.add(panel);
bar.add(menu);
bar.add(menu1);
bar.add(menu2);
bar.add(menu3);
bar.add(menu4);
bar.add(menu5);
bar.add(menu6);
bar.add(menu7);
bar.add(menu8);
JMenuItem menuitem = new JMenuItem("New...");
JMenuItem menuitem1 = new JMenuItem("Open...");
JMenuItem menuitem2 = new JMenuItem("Close");
JMenuItem menuitem3 = new JMenuItem("Save");
JMenuItem menuitem4 = new JMenuItem("Save as...");
JMenuItem menuitem5 = new JMenuItem("Save as web page...");
JMenuItem menuitem6 = new JMenuItem("Web page preview ");
JMenuItem menuitem7 = new JMenuItem("Print ");
JMenuItem menuitem8 = new JMenuItem("Exit");
menu.add(menuitem);
menu.add(menuitem1);
menu.add(menuitem2);
menu.add(menuitem3);
menu.add(menuitem4);
menu.add(menuitem5);
menu.add(menuitem6);
menu.add(menuitem7);
menu.add(menuitem8);
frame.setSize(600,100);
frame.setVisible(true);
}
}
Also consider using Action to let components share functionality, as shown here.
Calling System.exit(0) on menu selection would do just fine.
At the moment you're just creating the GUI element, but they're basically empty shells. In particular, you've created items that appear on the menu, but you haven't added any behaviour to those items. (Since you haven't told your program anywhere what to do when an item is clicked, what did you think would happen)?
In order to provide this behaviour, you'll need to register an ActionListener, which will be called when something happens on an element, and will let you take an appropriate action at that point (such as calling System.exit(0). See the tutorial on Writing [Swing] Event listeners for details.
I always extend the AbstractAction class (which implements the ActionListener interface) which allows you to reuse your actions. By extending the AbstractAction, the actionPerformed(ActionEvent e) method will be invoked very time your button is clicked.
public class CloseAction extends AbstractAction {
public CloseAction() {
super("Close");
}
public actionPerformed(ActionEvent e) {
System.exit(1);
}
}
Now, to apply the above action to one of your buttons, you simply need to follow the below piece of code.
CloseButton.setAction(new CloseAction());
The close button will now shut down your application each time it gets pressed.
Use the ExitAction defined in Closing an Application. Then clicking on the Exit menu item will be just like clicking on the Close icon at the top right of the window. This allows for consistency when closing an application in case you ever need to do close processing.
Edit:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
// JMenuItem menuitem8 = new JMenuItem("Exit");
JMenuItem menuitem8 = new JMenuItem( new ExitAction() );

Add functionality to a menu button in java

I am new to Java and I was wondering how to add functionality to menu item?
What I would like it to do, is to set two values to 0.
This is the code I have currently:
JMenuItem clear = new JMenuItem("Clear");
Options.add(clear);
This example is from the book "Java
Foundation Classes in a Nutshell".
Written by David Flanagan. Copyright
(c) 1999 by O'Reilly & Associates.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo {
public static void main(String[] args) {
// Create a window for this demo
JFrame frame = new JFrame("Menu Demo");
JPanel panel = new JPanel();
frame.getContentPane().add(panel, "Center");
// Create an action listener for the menu items we will create
// The MenuItemActionListener class is defined below
ActionListener listener = new MenuItemActionListener(panel);
// Create some menu panes, and fill them with menu items
// The menuItem() method is important. It is defined below.
JMenu file = new JMenu("File");
file.setMnemonic('F');
file.add(menuItem("New", listener, "new", 'N', KeyEvent.VK_N));
file.add(menuItem("Open...", listener, "open", 'O', KeyEvent.VK_O));
file.add(menuItem("Save", listener, "save", 'S', KeyEvent.VK_S));
file.add(menuItem("Save As...", listener, "saveas", 'A', KeyEvent.VK_A));
JMenu edit = new JMenu("Edit");
edit.setMnemonic('E');
edit.add(menuItem("Cut", listener, "cut", 0, KeyEvent.VK_X));
edit.add(menuItem("Copy", listener, "copy", 'C', KeyEvent.VK_C));
edit.add(menuItem("Paste", listener, "paste", 0, KeyEvent.VK_V));
// Create a menubar and add these panes to it.
JMenuBar menubar = new JMenuBar();
menubar.add(file);
menubar.add(edit);
// Add menubar to the main window. Note special method to add menubars
frame.setJMenuBar(menubar);
// Now create a popup menu and add the some stuff to it
final JPopupMenu popup = new JPopupMenu();
popup.add(menuItem("Open...", listener, "open", 0, 0));
popup.addSeparator(); // Add a separator between items
JMenu colors = new JMenu("Colors"); // Create a submenu
popup.add(colors); // and add it to the popup menu
// Now fill the submenu with mutually-exclusive radio buttons
ButtonGroup colorgroup = new ButtonGroup();
colors.add(radioItem("Red", listener, "color(red)", colorgroup));
colors.add(radioItem("Green", listener, "color(green)", colorgroup));
colors.add(radioItem("Blue", listener, "color(blue)", colorgroup));
// Arrange to display the popup menu when the user clicks in the window
panel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
// Check whether this is the right type of event to pop up a popup
// menu on this platform. Usually checks for right button down.
if (e.isPopupTrigger())
popup.show((Component)e.getSource(), e.getX(), e.getY());
}
});
// Finally, make our main window appear
frame.setSize(450, 300);
frame.setVisible(true);
}
// A convenience method for creating menu items.
public static JMenuItem menuItem(String label,
ActionListener listener, String command,
int mnemonic, int acceleratorKey) {
JMenuItem item = new JMenuItem(label);
item.addActionListener(listener);
item.setActionCommand(command);
if (mnemonic != 0) item.setMnemonic((char) mnemonic);
if (acceleratorKey != 0)
item.setAccelerator(KeyStroke.getKeyStroke(acceleratorKey,
java.awt.Event.CTRL_MASK));
return item;
}
// A convenience method for creating radio button menu items.
public static JMenuItem radioItem(String label, ActionListener listener,
String command, ButtonGroup mutExGroup) {
JMenuItem item = new JRadioButtonMenuItem(label);
item.addActionListener(listener);
item.setActionCommand(command);
mutExGroup.add(item);
return item;
}
// A event listener class used with the menu items created above.
// For this demo, it just displays a dialog box when an item is selected.
public static class MenuItemActionListener implements ActionListener {
Component parent;
public MenuItemActionListener(Component parent) { this.parent = parent; }
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
String cmd = item.getActionCommand();
JOptionPane.showMessageDialog(parent, cmd + " was selected.");
}
}
}
Hope it help you get started
You will need to add an ActionListener. This is an interface which must implement a method called actionPerformed.
E.g
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
// Clear two values.
}
});`
This will add an anonymous ActionListener that is invoked once the JMenuItem is clicked.
Hope that helps.

Categories