How can I open a JPanel from a menu? - java

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

Related

How to group two windows into one?

I need to insert the window with the tabbed called "First panel, Second panel, Third panel, Fourth panel" into the window named "Animation".
What should I do so that at the end it looks like: a window that has an animation box with four tabs, a Text box and a User input box?
First class called "Main" :
import java.awt.*;
import javax.swing.*;
public class Main {
JFrame frame = new JFrame("Demo");
JPanel panel = new JPanel();
JLabel square1 = new JLabel("Animation");
JLabel square2 = new JLabel("Text");
JTextField square3 = new JTextField("User Input");
public Main() {
panel.setLayout(new GridLayout(2,2,3,3));
panel.add(square1);
panel.add(square2);
panel.add(square3);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(600,400);
frame.setVisible(true);
}
public static void main(String[] args) {
Tabbed tp = new Tabbed();
tp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
tp.setSize(600,400);
tp.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
}
});
}
}
'Second class called "Tabbed" :'
import javax.swing.*;
public class Tabbed extends JFrame{
private static final long serialVersionUID = 1L;
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
JPanel thirdPanel = new JPanel();
JPanel fourPanel = new JPanel();
JLabel firstLabel = new JLabel("First!");
JLabel secondLabel = new JLabel("Second!");
JLabel thirdLabel = new JLabel("Third!");
JLabel fourLabel = new JLabel("Fourth!");
JTabbedPane tabbedPane = new JTabbedPane();
public Tabbed(){
firstPanel.add(firstLabel);
secondPanel.add(secondLabel);
thirdPanel.add(thirdLabel);
fourPanel.add(fourLabel);
tabbedPane.add("First panel",firstPanel);
tabbedPane.add("Second panel",secondPanel);
tabbedPane.add("Third panel",thirdPanel);
tabbedPane.add("Fourth panel",fourPanel);
add(tabbedPane);
}
}
Here's how I want to combine the two windows :

Java syntax for separating action listeners

Please help me out to separate these ActionListeners in a periodic table that I am attempting to complete. When I execute the program and click on 'H', it opens all the other elements and when the others are clicked, it does not work. So I need a way to separate these using any method...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PeriodicTable
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Elements");
frame.setVisible(true);
frame.setSize(1000,1500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("H");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("He");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Li");
panel.add(button3);
button3.addActionListener (new Action2());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("H");
frame2.setVisible(true);
frame2.setSize(1000,1500);
JLabel label = new JLabel("Hydrogen");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("He");
frame3.setVisible(true);
frame3.setSize(1000,1500);
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Li");
frame4.setVisible(true);
frame4.setSize(1000,1500);
JLabel label = new JLabel("Lithium");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
}
Thanks in advance.
(note: only the first 3 elements are coded for...)
When I execute the program and click on 'H', it opens all other elements
Only one frame opens for me.
and when the others are clicked, it does not work.
Each button opens a single frame for me.
However, button 3 opens the wrong frame because you add the wrong listener to the button:
//button3.addActionListener (new Action2());
button3.addActionListener (new Action3());
Other issues:
You should add the components to the frame BEFORE making the frame visible.
Don't hardcode screen sizes, you never know what size screen other users will be using
So the order of your code might be something like:
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame("He");
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
And of course you really don't want to create dozens of separate ActionListeners. You want to make the listener more generic so it can be shared.
Something like:
static class Action implements ActionListener
{
public Action(String element, String description)
{
this.element = element;
this.description = description;
}
public void actionPerformed (ActionEvent e)
{
JLabel label = new JLabel(description);
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame(element);
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
Then when you create the listener you use:
button3.addActionListener (new Action("HE", "Helium"));

JMenuBar to JFrame

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

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

java swing panel problems

I am having problems adding a panel to my main JFrame and hiding it right away, only making it visilble when a button it pressed. here is my code. Looking for any insight as to what the problem is. Also the label I try to add to the panel doesnt show up either.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cis2430_a4;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Tristan
*/
public class MainWindow extends JFrame implements ActionListener{
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
public MainWindow()
{
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
JLabel intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
add(intro2, BorderLayout.CENTER);
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600,400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
add(addPanel, BorderLayout.CENTER);
addPanel.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent ae)
{
/*String menuChoice = ae.getActionCommand();
if (menuChoice.equals("Add")){
addPanel.setVisible(true);
}*/
add(addPanel);
//addPanel.setVisible(true);
}
}
I have no issue with your example.
You may want to...
1- Make sure you've launched your UI in the context of the Event Dispatching Thread
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
MainWindow frame = new MainWindow();
frame.setVisible(true);
}
});
}
2- Try calling repaint after addPanel.setVisible(true)
3- Try calling invalidate after addPanel.setVisible(true) but before repaint if that doesn't work.
Much better solution is to use Card Layout for this kind of work
UPDATED
After spending some time reading through the code, what I think you seem to be concerned about is the fact that you're "intro" label isn't showing up...
This easily explained. Only one component can exists at any given position within a BorderLayout, so when you add you addPanel, even though it's invisible, it will clobber the intro2 label (effectively removing it from the container).
Below is an example using CardLayout
public class CardWindow extends JFrame implements ActionListener {
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
private JPanel cardPane;
private CardLayout cardLayout;
private final JLabel intro2;
public CardWindow() {
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
cardPane = new JPanel((cardLayout = new CardLayout()));
add(cardPane, BorderLayout.CENTER);
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
cardPane.add(intro2, "intro");
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600, 400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
addPanel.setVisible(false);
cardPane.add(addPanel, "Add");
cardLayout.show(cardPane, "intro");
}
#Override
public void actionPerformed(ActionEvent ae) {
String menuChoice = ae.getActionCommand();
System.out.println(menuChoice);
if (menuChoice.equals("Add")) {
cardLayout.show(cardPane, "Add");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
CardWindow frame = new CardWindow();
frame.setVisible(true);
}
});
}
}
Labels are showing up because you have added a panel after adding the labels on the frame so basically the panels are overlapping the labels.
Also to show different panels you can use
panel.setVisible(true); //For the panel you want to show and false for others
or you can use CardLayout which makes panels as cards and shows one of them at a time.
Just edited the code a little but it seems to work -
public class MainWindow extends JFrame implements ActionListener{
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.setVisible(true);
}
public MainWindow()
{
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
JLabel intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
add(intro2, BorderLayout.CENTER);
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600,400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
add(addPanel, BorderLayout.CENTER);
addPanel.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent ae)
{
String menuChoice = ae.getActionCommand();
if (menuChoice.equals("Add")){
addPanel.setVisible(true);
}
add(addPanel);
//addPanel.setVisible(true);
}
}

Categories

Resources