JMenuBar to JFrame - java

I have a menu bar in a JFrame JF when i click on the menubar item a new JFrame JF1 is created and is displayed , but when i clicked on the close button of JF1 , both JFrame are closed . When i click on close button of JF1 , i want only JF1 to be closed , not JF
JMenuBar menubar;
JMenu help;
JMenuItem about;
public GUI() {
setLayout(new FlowLayout());
menubar = new JMenuBar();
add(menubar);
help = new JMenu("Help");
menubar.add(help);
}`

a new JFrame JF1 is created and is displayed
Don't create a new JFrame an application should only have a single JFrame.
Instead create a JDialog. See: The Use of Multiple JFrames: Good or Bad Practice? for more information.
Also you don't add a JMenuBar to a JFrame using the add(...) method. See How to Use Menu Bars for the better way to do that.

I recomend you to use DesktopPane and JInternalFrame.
To the main Frame you make a change: contentPane (JPanel) will be JDesktopPane.
The JFrame that it's displayed whit the click will be a JInternalFrame.
In the actionListener of the JMenuItem, you will do this:
MyInternalFrame internalFrame = new MyInternalFrame();
internalFrame.show();
contentPane.add(internalFrame);
MyInternalFrame is the class of the Frame displayed (a class that extends JInternalFrame).
To close "internalFrame", just add a button to the layout whit the text "Quit" and in the actionListener of its you put "dispose()".
Try it and tell if it works ;)
--EDIT---
MAIN CLASS (The JFRAME)
public class Main extends JFrame {
private JDesktopPane contentPane;
private JMenuBar menuBar;
private JMenu mnExample;
private JMenuItem mntmAbout;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(20, 20, 800, 800);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnExample = new JMenu("Help");
menuBar.add(mnExample);
mntmAbout = new JMenuItem("About");
mntmAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
About frame = new About();
frame.show();
contentPane.add(frame);
}
});
mnExample.add(mntmAbout);
contentPane = new JDesktopPane();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
}
}
ABOUT CLASS (The JINTERNALFRAME)
public class About extends JInternalFrame {
public About() {
setBounds(100, 100, 544, 372);
JLabel lblSomeText = new JLabel("Some Text");
getContentPane().add(lblSomeText, BorderLayout.CENTER);
JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
getContentPane().add(btnClose, BorderLayout.SOUTH);
}
}

Related

Java GUI switching between panels on button click

I am learning Java and I have to develop an application using a GUI. I have the application working in command line already, but the GUI is driving me insane and costing me in lost hours of head banging and research which is leading nowhere. Can you please help me get the basics working so that i can develop further from there. I want to have a single frame application that can switch between frames on a button click. I created a frame and added three panels P1-P3. These are set as Card Layout (from what i read from forums). Then I added additional panels to these to which i have set colour and buttons.
'''
public class MyMainForm extends JFrame{
private JPanel P1;
private JPanel P2;
private JPanel P3;
private JButton btnFrame1;
private JButton btnFrame2;
private JButton button1;
private JTextField thisIsPanel3TextField;
private JButton btn2Frame1;
private final JFrame frame = new JFrame("MyMain Frame");
public MyMainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(P1);
pack();
setSize(1000,800);
//setLocation(null);
btnFrame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btnFrame2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P2.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P3.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btn2Frame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
}
public static void main(String[] args) {
MyMainForm MyMainForm = new MyMainForm();
MyMainForm.setVisible(true);
}
}
'''
I can display P2 or P3 with this new code example above. When i try to go from P2 or P3 back to P1 the content pane doesn't show? Do i need to revalidate the content pane for this to work? I really need to be able to go from P1 to P2
The easiest way to do this is to use a CardLayout. Just follow this example:
JFrame frame = new JFrame();
JPanel p1 = new JPanel();
p1.setBackground(Color.RED);
JPanel p2 = new JPanel();
p2.setBackground(Color.WHITE);
JPanel p3 = new JPanel();
p3.setBackground(Color.BLUE);
//Create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
cards.add(p1, "Panel 1");
cards.add(p2, "Panel 2");
cards.add(p3, "Panel 3");
// Add your card container to the frame
Container pane = frame.getContentPane();
pane.add(cards, BorderLayout.CENTER);
JButton btn = new JButton("Click me!");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.next(cards);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(btn);
pane.add(btnPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
Alternatively, you can switch to a specific panel by calling cl.show(cards, "Panel X") where X is the number of the panel. This is because the swing argument is the name I assigned to each "card" and the show method recalls panels added to CardLayout by name. For your example, each button should have a listener that uses this method to "show" its assigned panel.

How can I open a JPanel from a menu?

I'm trying to create a menu and from it I need to open a JPanel. How can I do that?
I want to the user to press "individual details" for example and then for it to open an area where i can add buttons and textfields.
public class Payroll{
public static void main(String[] args) {
JFrame frame = new JFrame(" Payroll ");
//create the employees details menu
JMenu employees = new JMenu("Employees");
employees.setMnemonic(KeyEvent.VK_E);
// add employees items
JMenuItem details = new JMenuItem("Individual Details");
details.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
/**********missing code is here, how can i open a JPanel from here?**/
}
});
employees.add(details);
//menu bar
JMenuBar menuBar = new JMenuBar( );
menuBar.add(employees);
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(700,550);
frame.setVisible(true);
}
}
you can create a another class which has a jpanel and fields for take userinput .and then create a instance of it inside menuitem actionPerformed event...
for example ;
this is the class which has panel
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyPanel {
public MyPanel() {
JFrame f=new JFrame();
f.setSize(300,200);
f.setLayout(new GridLayout(1, 1));
JPanel p=new JPanel();
p.setLayout(new GridLayout(3, 1, 2, 2));
JTextField t1=new JTextField(20);
p.add(t1);
f.add(p);
f.setVisible(true);
}
}
and make a instance of it inside event ..
public class Payroll{
public static void main(String[] args) {
JFrame frame = new JFrame(" Payroll ");
JMenu employees = new JMenu("Employees");
employees.setMnemonic(KeyEvent.VK_E);
// add employees items
JMenuItem details = new JMenuItem("Individual Details");
details.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
MyPanel panel=new MyPanel(); // call MyPanel here
}
});
employees.add(details);
//menu bar
JMenuBar menuBar = new JMenuBar( );
menuBar.add(employees);
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(700,550);
frame.setVisible(true);
}
}
You can try like below,
JPanel panel = new JPanel();
JButton okButton = new JButton("OK");
panel.add(okButton);
JButton cancelButton = new JButton("Cancel");
panel.add(cancelButton);
frame.add(panel);

Java ActionListener not listening to event

anyone can tell why the class OpenMenuListener doesnt send a feedback when i click the open button in my Gui ? The erase button works though. It sends me a feedback. I'm exausted.
import java.awt.*;
import javax.swing.*;
public class DrawingApplication extends JFrame {
JComponent drawingArea;
class EraseButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked erase");
}
}
class OpenMenuListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked open");
}
}
public DrawingApplication() {
JPanel frame = new JPanel();
add(frame);
// panel1.add( new JButton(Figuur),BorderLayout.CENTER);
drawingArea = new JLabel();
// label1.add(drawingArea);
frame.add(drawingArea);
// Creates a menubar for a JFrame
JMenuBar menuBar = new JMenuBar();
// Add the menubar to the frame
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenu open = new JMenu("Open");
fileMenu.add(open);
fileMenu.addSeparator();
JMenu save = new JMenu("Save");
fileMenu.add(save);
fileMenu.addSeparator();
JMenu close =new JMenu("Close");
fileMenu.add(close);
JMenu helpMenu = new JMenu("Help");
menuBar.add(helpMenu);
helpMenu.add(new JMenu("Info"));
JPanel panel2 = new JPanel();
add(BorderLayout.SOUTH, frame);
frame.add(new JLabel("figuurkeuze"));
frame.add(panel2);
setVisible(true);
JRadioButton rectButton = new JRadioButton("Rectangle");
JRadioButton triangleButton = new JRadioButton("Triangle");
JRadioButton circleButton = new JRadioButton("Circle");
frame.add(rectButton);
frame.add(triangleButton);
frame.add(circleButton);
JButton erase = new JButton("Erase");
frame.add(erase);
EraseButtonListener eraselistener = new EraseButtonListener();
erase.addActionListener(eraselistener);
OpenMenuListener openMenuListener = new OpenMenuListener();
open.addActionListener(openMenuListener);
}
public static void main(String[] args) {
DrawingApplication frame = new DrawingApplication();
frame.setTitle("My prgram");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
It seems a problem of name aliasing, you add the listener to the open variable which is declared as a JMenuItem, so you are adding the ActionListener to the menu item instead that to a button (that you never declare since there is no JButton open = new JButton("open") anywhere).

JToolBar not showing

I had a simple drawing application. I need to add a menu and a toolbar on the left side.
So now, instead of using a simple JFrame, I'm creating a simple class that extends JFrame. I was able to add the menu following some examples online, but can't figure out how to add a JToolBar. I've tried a few different ways, but nothing works. I don't get an error, everything complies just fine, but I don't see any JToolBar.
Here's the code for my JFrame, I hope you can help.
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
// JPanel panel = new JPanel();
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton newb = new JButton("new");
toolbar.add(newb);
// toolbar.setOpaque(true);
toolbar.setLocation(100, 100);
toolbar.setVisible(true);
// toolbar.setMinimumSize(new Dimension(100, 100));
// toolbar.setAlignmentX(0);
// panel.add(toolbar);
add(toolbar, BorderLayout.NORTH);
getContentPane().add(toolbar, BorderLayout.NORTH);
// getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
setTitle(title);
pack();
setLocationRelativeTo(null); // Center window.
}
// OpenAction
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
its work fine, and you don't need to setVisible tool bar because its showing by default, also don't add the tool bar two time in the same place (NORTH)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MenuDemo {
public static void main(String... args) {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
JFrame menu = new Menu("Testing");
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setVisible(true);
}
}
);
}
}
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
JButton newb = new JButton("new");
toolbar.add(newb);
add(toolbar, BorderLayout.NORTH);
setTitle(title);
setLocationRelativeTo(null);
pack();
}
// OpenAction
private class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
My problem was that I was the way I was instantiating my JFrame. I was using a helper function like this one:
public static JFrame openInJFrame(Container content, int width, int height,
String title, Color bgColor) {
// ...
frame.setContentPane(content);
frame.setVisible(true);
return (frame);
}
So my JToolBar was getting replaced by the Container object...
Thanks guys! Your answers helped me figure out my problem.

updating a panel

I have a panel on my frame .and by clicking on a button I want to delete the old panel and make the other panel and add that panel to my frame.(also I use netbeans)
would you please help me that how can i do that?thanks
JFrame frame = new JFrame();
final JPanel origPanel = new JPanel();
frame.add(origPanel, BorderLayout.CENTER);
MouseListener ml = new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
// Mouse clicked on panel so remove existing panel and add a new one.
frame.remove(origPanel);
frame.add(createNewPanel(), BorderLayout.CENTER);
// Revalidate frame to cause it to layout the new panel correctly.
frame.revalidate();
// Stop listening to origPanel (prevent dangling reference).
origPanel.removeMouseListener(this);
}
}
origPanel.addMouseListener(ml);
This way:
final JFrame frame = new JFrame();
frame.setSize(200, 200);
final JPanel panelA = new JPanel();
final JPanel panelB = new JPanel();
JButton button = new JButton("Switch");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(panelA);
frame.add(panelB);
frame.show();
}
});
JLabel label = new JLabel("This is panel B. Panel A is gone!");
panelB.add(label);
panelA.add(button);
frame.add(panelB);
frame.add(panelA);
frame.show();

Categories

Resources