java JMenuBar not visible? Why? - java

I cannot figure out why my menu bar isn't visible. I have following code:
//Main
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Menu extends JFrame{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(500,350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
menuBar mbObj = new menuBar();
mbObj.menuBar(frame);
}
}
//Menu Bar class
public class menuBar{
private JMenu file,edit;
private JMenuItem nFile ,oFile,sFile,saFile,exit;
private JMenuItem undo,copy,paste;
private JMenuBar bar;
public void menuBar(JFrame frame){
bar = new JMenuBar();
frame.setJMenuBar(bar);
bar.setVisible(true);
file = new JMenu("File");
edit = new JMenu("Edit");
bar.add(file);
bar.add(edit);
}
}

Call setVisible(true) on the top-level window, here a JFrame, only after adding all components, including the JMenuBar. You will also want to avoid calling setSize(...) on anything, and instead use layout managers and call pack() on the JFrame after adding all components and before calling setVisible(true).
So the order should be:
// create JFrame
JFrame frame = new JFrame("Foo");
// here add all components to the JFrame
// .....
// done adding components
frame.pack();
// frame.setLocationRelativeToPlatform(true); // if you wish
frame.setVisible(true);
As an aside class names should begin with an upper case letter, and dont have methods with the exact same name as the class, as that creates a "pseudo"-constructor and will confuse everyone.

Related

MenuListener not working

I am trying to create a JMenu with a MenuListener to exit when selected, but the program is not exiting.
Compiler does not show any error message. Not sure if it is the e.getsource() not working or if it is something else.
Thank you in advance.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class entree implements MenuListener{
JFrame frame;
JMenu exit,teach;
entree(){
Font font=new Font("SansSerif",Font.BOLD,22);
JFrame frame=new JFrame();
ImageIcon icon=new ImageIcon("D:\\Capture_aurora.png");
JLabel bg=new JLabel(icon);
JMenuBar mb=new JMenuBar();
JMenu teach=new JMenu("Teach");
JMenu exit =new JMenu("Exit");
teach.setFont(font);exit.setFont(font);exit.addMenuListener(this);teach.addMenuListener(this);
mb.add(teach);mb.add(Box.createHorizontalGlue());mb.add(exit);
JButton button1=new JButton("Start");
button1.setFont(font);
button1.setBounds(870,820,150,45);
frame.setJMenuBar(mb);
frame.add(button1);
frame.add(bg,BorderLayout.CENTER);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
}
public static void main(String[]args) {new entree();}
public void menuSelected(MenuEvent e) {
if(e.getSource()==exit) {
System.exit(0);frame.dispose();}// Code supposed to work here, but the program won't exit
if(e.getSource()==teach) {}
}
public void menuDeselected(MenuEvent e) {
}
public void menuCanceled(MenuEvent e) {
}
}
Answer to the question
You're shadowing your variables...
public class entree implements MenuListener {
JFrame frame;
JMenu exit, teach;
entree() {
//...
JMenu teach = new JMenu("Teach");
JMenu exit = new JMenu("Exit");
You're creating local variables in the constructor with the same names as the instance fields you are trying to compare later. This means that exit and teach are actually null when you try and compare them in the menuSelected event handler.
Suggestions...
Generally speaking, this really isn't how JMenus are suppose to work, they aren't meant to be "actionable" items, they are meant to be containers for like items (implemented as JMenuItems).
I would consider either using a JToolBar or JPanel with JButtons which is added to the NORTH position of a BorderLayout instead. From a user's perspective, it would make for a more common and expected user experience - IMHO

Separating code into classes (GUI specific) using Java

In a sample program I have one class that places:
GUI components on a JPanel which is inside a JFrame.
A method makeMenu to create a menu bar
An ActionListener inside the makeMenu method to change the JPanels background color when called.
Main method.
public class GUI extends JFrame {
private JPanel jPanelRight;
private JPanel jPanelLeft;
JMenuBar menuBar;
JMenu file, help;
JMenuItem changeColor;
public GUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setJMenuBar(makeMenu()); // call constructor to create the menu
this.setSize(800, 600); // set frame size
this.setVisible(true); // display frame
this.setTitle("understanding objects");
setLayout(new BorderLayout()); // layout manager
jPanelLeft = new JPanel(); //left jpanel
jPanelLeft.setPreferredSize(new Dimension(400, 800)); // to set the size of the left panel
jPanelLeft.setBackground(Color.blue);
jPanelRight = new JPanel(); //right jpanel
jPanelRight.setPreferredSize(new Dimension(400, 600)); // to set the size of the right panel
jPanelRight.setBackground(Color.green);
this.add(jPanelLeft, BorderLayout.WEST); //add jpanel to the left side of the frame
this.add(jPanelRight, BorderLayout.EAST); //add jpanel to the right side of the frame
}//end constructor
public JMenuBar makeMenu() {
menuBar = new JMenuBar(); //menu bar
file = new JMenu("File"); //menu item
menuBar.add(file);
help = new JMenu("Help"); //menu item
menuBar.add(help);
changeColor = new JMenuItem("Change Colour"); //sub menu item
changeColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jPanelRight.setBackground(Color.red);
}
});
file.add(changeColor);
return menuBar;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUI();
}
});
} // end
}//end class
I am trying to separate the code into 3 or 4 classes.
GUI class
ActionListener class
MakeMenu class
Main class (to run program)
one problem that keeps occurring is that i when i separate the code i can only change using System.out.println(); and can not change the GUI i.e. i can print out that the jPanelRight is now red but can not actually change the jPanelRight to red.
I am possibly going about this the wrong way.
A GUI to use a different class to create its menu and another different class to control the actions for the GUI's menu.

Eclipse not displaying JMenu items after adding to and setting JMenuBar visible?

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);

Reusing By Many Frame Classes java

Here is the code I came up with. I am a beginner java programmer who is very confused on what to do. I have to have a "Push me" button and a "Exit" Button created.
The main should also test out this panel. I will need to first instantiate a Frame and then instantiate your ExitPanel and add the ExitPanel to the Frame just before you show the Frame.
What am I doing wrong? Please explain and help thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.FlowLayout;
public class ExitPanel extends JPanel {
public ExitPanel() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout());
JButton Exit = new JButton();
Exit.setText("Exit");
JButton Push = new JButton("Push Me");
// add buttons to frame
add(Exit);
add(Push);
}
public static void main(String[] args) {
ExitPanel exi = new ExitPanel();
exi.pack();
exi.setVisible(true);
exi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
you are instantaiting a JPanel not a frame
change this:
ExitPanel extends JPanel
to:
ExitPanel extends JFrame

Opening a textpane in the same form on a Button click

I am trying to design a basic editor type of GUI in Java using Swing. I have a menu item named New clicking on which I want a blank text area to fill up the GUI. My code is as folows :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UI extends JFrame {
private JMenuBar bar;
private JMenu menu;
private JMenuItem item;
private JTextPane tp;
public UI() {
setLayout(new FlowLayout());
bar = new JMenuBar();
setJMenuBar(bar);
menu = new JMenu("File");
bar.add(menu);
item = new JMenuItem("New");
menu.add(item);
item.addActionListener(new xyz());
}
public class xyz implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
JTextPane tp = new JTextPane();
add(tp);
}
}
public static void main(String args[]) {
// do the rest of the stuffs
}
}
However, even on clicking on the New, I do not get the textPane on the same frame. Can someone please explain.
use JTextPane#setText("") instead of to create a new JTextPane
otherwise you have to notify Container with (re)validate() and repaint()
The text-panes should probably be added to a JTabbedPane if this app. supports multiple documents. If it is intended for 'single document', put the text pane onto the frame at start-up.

Categories