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!
Related
I have a game made with my game engine Java class.
The game engine uses paintComponent to draw the elements.
Here is a snippet from the game:
gamepic
I want to add this game an extra JLabel and JMenu to the top or the button of the game.
Here is my code:
public class LabyrinthGUI {
private JFrame frame;
private GameEngine gameArea;
private String PlayerName;
public LabyrinthGUI(String PlayerName) {
frame = new JFrame("GAME");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//making new manu bar
JMenuBar mb = new JMenuBar();
JMenu sg = new JMenu("Settings");
JMenuItem ng = new JMenuItem("New game");
mb.add(ng);
mb.add(sg);
frame.getContentPane().add(mb);
gameArea = new GameEngine(PlayerName);//This is a game engine
JLabel l1 = new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
frame.add(l1);
frame.getContentPane().add(gameArea);
frame.setPreferredSize(new Dimension(800, 600));
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
The problem with my code is it does not seem to add the JLabel and JMenuBar to the game.
To add a JMenuBar to your JFrame you have to use the setJMenuBar() method:
public void setJMenuBar(JMenuBar menubar)
Sets the menubar for this frame.
Parameters:
menubar - the menubar being placed in the frame
See Also:
getJMenuBar()
So you use it like:
frame.setJMenuBar(mb);
For the label and the game engine being added to the content pane: A JFrame uses the BorderLayout layout manager as default for placing the components on the pane. See the documentation of JFrame:
The default content pane will have a BorderLayout manager set on it.
Because you haven't specify the locations where exactly you want to place the components with the BorderLayout layout manager, the component will be placed in the CENTER. However there can only be one component at a slot defined by the BorderLayout layout manager. The latest added component will override previous placed components (in the same slot), so your added JLabel will be overridden by the later added game engine. Depending on how/where you want to place the JLabel and your game engine, you have to use a different layout manager or specify where you want to place the components with the BorderLayout layout manager.
The way to add a JMenuBar to a JFrame is not:
frame.getContentPane().add(mb);
but:
this.frame.setJMenuBar(mb);
Take a look at Creating Menus section in the Java Tutorial.
I'm trying to create a pretty simple application that has a JSplitPane (which is divided into a JTabbedPane and a JPanel) above a status bar panel. I want to use a simple layout (i.e. BoxLayout, FlowLayout, or BorderLayout), but I've tried and they all give me the same error. I've simplified the code as much as possible to show the error.
The error is that there should only be 2 regions in the main box layout (the frame): a top (with the JSplitPane, which has the black border) and a bottom (with the JPanel status bar). However, when I add the status bar, a third region is created in the upper left that contains nothing. Any ideas on how to get rid of it?
public static void main(String[] args) {
JFrame frame = new JFrame("Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
// Create left side of the application
JTabbedPane tabby = new JTabbedPane(JTabbedPane.LEFT);
// Create right side of the application
JPanel rightPanel = new JPanel(new BorderLayout());
// Create the status bar at the bottom
JPanel statusBar = new JPanel(new BorderLayout());
JPanel statusBarPanel = new JPanel();
statusBarLabel = new JLabel("Status Bar");
statusBarPanel.add(statusBarLabel);
parent.add(statusBarPanel);
JSplitPane mainPain = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tabby, rightPanel);
frame.add(mainPain);
frame.add(statusBar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I'm trying to create a pretty simple application that has a JSplitPane (which is divided into a JTabbedPane and a JPanel) above a status bar panel.
Normally you would just use the default BorderLayout of the frame and then do:
frame.add(splitPane, BorderLayout.CENTER);
frame.add(statusBar, BorderLayout.PAGE_END);
A status bar is typically one or more labels that display information so they are display in a fixed size at the bottom.
The other panel will then contain the main components of the application. These components will then get any extra space available to the frame as it is resized.
but I've tried and they all give me the same error
parent.add(statusBarPanel);
The variable "parent" doesn't exist. Get rid of it. Add the status bar to the frame as shown above.
not sure if thats it, but it seems, like you add 2 Panels when adding the Statusbar.
You got a statusBarPanel which is added to "parent", and statusBar, which is added to the frame itself. Maybe thats your 3rd Panel.
Not getting any errors however the program only displays the word "menu" at the top in the program. It doesn't display the 3 JMenu items: "home", "about" and "explore".
JPanel p5 = new JPanel(new GridBagLayout());
p5.setVisible(true);
fw.add(p5, BorderLayout.PAGE_START);
JMenu menu = new JMenu("Menu");
menu.setVisible(true);
menu.add("home");
menu.add("about");
menu.add("explore");
JMenuBar menubar = new JMenuBar();
fw.setJMenuBar(menubar); //ADDED THIS LINE. STILL DOESN'T WORK.
menubar.setVisible(true);
menubar.add(menu);
p5.add(menu);
I've added JMenu to JMenuBar (everything JMenu, JMenubar and JPanel is set to visible). Also I added JPanel (p5) to "first window (fw) and added menu to p5. I'm not sure why my menu items are not being displayed.
UPDATE: MCVE (Minimal Complete and Verifiable Example) as requested.
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
public class TestingClass extends JFrame {
public static void main(String[] args) {
FirstWindow fw = new FirstWindow();
fw.setSize(400, 600);
fw.setDefaultCloseOperation(EXIT_ON_CLOSE);
fw.setVisible(true);
JPanel p5 = new JPanel(new GridBagLayout());
p5.setVisible(true);
fw.add(p5);
JMenu menu = new JMenu("Menu");
menu.setVisible(true);
menu.add("home");
menu.add("about");
menu.add("explore");
JMenuBar menubar = new JMenuBar();
fw.setJMenuBar(menubar); // THE UPDATED LINE OF CODE.
menubar.setVisible(true);
menubar.add(menu);
p5.add(menu);
}
}
As you run the program, you will see the words "menu" displayed. The items: "home, about and explore" from JMenu are not displayed. Does anybody know what I'm doing wrong?
An MCVE of a run-time problem should compile cleanly. That shows 3 compilation errors. One is a missing import (easily fixable), but the other two relate to the missing FirstWindow.
Nevertheless, once a few tweaks were made, the problem becomes clear. A component can only appear in one place. By adding it to the panel as well (commented out below), it cannot appear in the menu.
import java.awt.*;
import javax.swing.*;
public class TestingClass extends JFrame {
public static void main(String[] args) {
JFrame fw = new JFrame();
fw.setSize(400, 200); // for screenshot
fw.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p5 = new JPanel(new GridBagLayout());
p5.setVisible(true);
fw.add(p5);
JMenu menu = new JMenu("Menu");
//menu.setVisible(true);
menu.add("home");
menu.add("about");
menu.add("explore");
JMenuBar menubar = new JMenuBar();
fw.setJMenuBar(menubar); // THE UPDATED LINE OF CODE.
//menubar.setVisible(true);
menubar.add(menu);
//p5.add(menu); // WTF?
fw.setVisible(true); //should be done after all components are added
}
}
You need to add the menuBar to the frame:
frame.setJMenuBar( menuBar );
Also, you don't need do make Swing components visible since they are visible by default (except for top level contains, like JFrame which you do need to set visible).
You need to call setVisible() after adding component! So first add all components. Add the highest level component to the JFrame(JPanel in your case) and the only call setVisible() for the JFrame. No need to call on every component.
JMenu menu = new JMenu("Menu");
menu.add("home");
menu.add("about");
menu.add("explore");
//rest of the components
//add panelto the frame
frame.getContentPane.add(p5);
//set menubar for the frame
frame.setJMenuBar( menuBar );
//set visibility for frame to true
frame.setVisible(true);
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.
How can I add q menu bar to change the layout of a Jung graph (ie: StaticLayout, SpringLayout, etc)?
Infact this is what I already have:
JFrame frame = new JFrame("JUNG2 based GraphVisualization Tool");
// Create a graph
SparseMultigraph<MyNode, MyEdge> graph = new SparseMultigraph<MyNode, MyEdge>();
// We want to give the Nodes a point where to be (for later use)
//Map<MyNode, Point2D> vertexLocations = new HashMap<MyNode, Point2D>();
// Also we need a Layout
Layout<MyNode, MyEdge> layout = new StaticLayout(graph);
layout.setSize(new Dimension(600, 600));
// VisualizationViewer to Visualize our nodes and edges
VisualizationViewer<MyNode, MyEdge> vv = new VisualizationViewer<MyNode, MyEdge>(layout);
vv.setPreferredSize(new Dimension(650, 650));
// To show the vertex and EdgeLabels
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
// Our mouse should be usable in different modes
EditingModalGraphMouse mouse = new EditingModalGraphMouse(vv.getRenderContext(), MyNodeFactory.getInstance(), MyEdgeFactory.getInstance());
// Default values for new edges
MyEdgeFactory.setDefaultCapacity(100.0);
MyEdgeFactory.setDefaultWeight(5.0);
// Popupmenu
PopupNodeEdgeMenuMousePlugin nodeEdgePlugin = new PopupNodeEdgeMenuMousePlugin();
JPopupMenu nodeMenu = new MyMouseMenus.NodeMenu();
JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame);
nodeEdgePlugin.setNodePopup(nodeMenu);
nodeEdgePlugin.setEdgePopup(edgeMenu);
// The already existing popup editing plugin has to be removed
mouse.remove(mouse.getPopupEditingPlugin());
// And the new one has to be added
mouse.add(nodeEdgePlugin);
// set up the new mouse for the VisualizationViewer
vv.setGraphMouse(mouse);
// A JFrame to show all the stuff
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(vv);
// To change the mouse modes, the tutorial shows a menuBar. Think it would be nice to have a toolbar here!
JMenuBar menuBar = new JMenuBar();
JMenu modeMenu = mouse.getModeMenu();
modeMenu.setText("Mouse Mode");
modeMenu.setIcon(null);
modeMenu.setPreferredSize(new Dimension(80,20));
menuBar.add(modeMenu);
frame.setJMenuBar(menuBar);
mouse.setMode(ModalGraphMouse.Mode.EDITING);
frame.pack();
frame.setVisible(true);
Sorry I am new to java so it would be great if you suggest me what to do according to my code.Thanks
The fact that you have a Jung graph doesn't really change what you need to do.
1. Create a JMenuBar and attach it to the JFrame you need to menu on.
2. Add JMenuItems that either have Actions or ActionListeners tied to them.
3. Create a method or methods in your GUI that change the layout of the container with the Graph. (Might have to add/remove components or possibly just rebuild that part of the GUI completely).
4. Have the ActionListener call the appropriate method.