I want to open a new JFrame by clicking a button (btnAdd); I have tried to create an actionlistener but I am having no luck; the code runs but nothing happens when the button is clicked. The methods in question are the last two in the following code. Any help is much appreciated!
package AdvancedWeatherApp;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionListener;
import weatherforecast.FetchWeatherForecast;
public class MainFrame extends JFrame implements ListSelectionListener {
private boolean initialized = false;
private Actions actions = new Actions();
private javax.swing.JScrollPane jspFavouritesList = new javax.swing.JScrollPane();
private javax.swing.DefaultListModel<String> listModel = new javax.swing.DefaultListModel<String>();
private javax.swing.JList<String> favouritesList = new javax.swing.JList<String>(
listModel);
private javax.swing.JLabel lblAcknowledgement = new javax.swing.JLabel();
private javax.swing.JLabel lblTitle = new javax.swing.JLabel();
private javax.swing.JButton btnAdd = new javax.swing.JButton();
private javax.swing.JButton btnRemove = new javax.swing.JButton();
public void initialize() {
initializeGui();
initializeEvents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/**
*
*/
private void initializeGui() {
if (initialized)
return;
initialized = true;
this.setSize(500, 400);
Dimension windowSize = this.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(screenSize.width / 2 - windowSize.width / 2,
screenSize.height / 2 - windowSize.height / 2);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
setLayout(new BorderLayout());
setTitle("Favourite Weather Locations");
JPanel jpSouth = new JPanel();
jpSouth.setLayout(new FlowLayout());
JPanel jpNorth = new JPanel();
jpNorth.setLayout(new FlowLayout());
JPanel jpCenter = new JPanel();
jpCenter.setLayout(new BoxLayout(jpCenter, BoxLayout.PAGE_AXIS));
JPanel jpEast = new JPanel();
JPanel jpWest = new JPanel();
getContentPane().setBackground(Color.WHITE);
jpEast.setBackground(Color.WHITE);
jpWest.setBackground(Color.WHITE);
jpCenter.setBackground(Color.WHITE);
getContentPane().add(jspFavouritesList);
jpCenter.add(jspFavouritesList);
jspFavouritesList.setViewportView(favouritesList);
favouritesList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
favouritesList.addListSelectionListener(this);
jpCenter.add(btnAdd);
jpCenter.add(btnRemove);
jpCenter.setAlignmentY(CENTER_ALIGNMENT);
btnAdd.setText("Add Location");
btnAdd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAdd.setFont(new Font("Calibri", Font.PLAIN, 18));
jpCenter.add(btnRemove);
btnRemove.setText("Remove Location");
btnRemove.setAlignmentX(Component.CENTER_ALIGNMENT);
btnRemove.setFont(new Font("Calibri", Font.PLAIN, 18));
getContentPane().add(jpEast, BorderLayout.EAST);
getContentPane().add(jpWest, BorderLayout.WEST);
getContentPane().add(jpSouth);
jpSouth.add(lblAcknowledgement);
add(lblAcknowledgement, BorderLayout.SOUTH);
lblAcknowledgement.setText(FetchWeatherForecast.getAcknowledgement());
lblAcknowledgement.setHorizontalAlignment(SwingConstants.CENTER);
lblAcknowledgement.setFont(new Font("Tahoma", Font.ITALIC, 12));
getContentPane().add(jpNorth);
jpNorth.add(lblTitle);
add(lblTitle, BorderLayout.NORTH);
lblTitle.setText("Your Favourite Locations");
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setFont(new Font("Calibri", Font.PLAIN, 32));
lblTitle.setForeground(Color.DARK_GRAY);
getContentPane().add(jpCenter);
}
private void initializeEvents() {
// TODO: Add action listeners, etc
}
public class Actions implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
command = command == null ? "" : command;
// TODO: add if...if else... for action commands
}
}
public void dispose() {
// TODO: Save settings
// super.dispose();
System.exit(0);
}
public void setVisible(boolean b) {
initialize();
super.setVisible(b);
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource() == btnAdd) {
showNewFrame();
//OPEN THE SEARCH WINDOW
}
}
private void showNewFrame() {
JFrame frame = new JFrame("Search Window" );
frame.setSize( 500,120 );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead for managing updates that may need to exist between frames. The preferred approach is to
use a modal JDialog if another window is required. This is discussed more here.
Use this :
btnAdd.addActionListener(this);
#Override
public void actionPerformed(ActionEvent e)
{
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
Type this inside the button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
ActionListener ActList = new ActionListener();
ActList.setVisible(true);
}
see my last line
{
ActList.setVisible(true);
}
Related
The idea is to have one "global" JFrame which I can then add/remove JPanels as needed to make a smooth flowing application. Currently, when I try changing from the first JPanel to the second, the second won't display. My code is below:
Handler (class to run the app):
package com.example.Startup;
import com.example.Global.Global_Frame;
public class Handler
{
public Handler()
{
gf = new Global_Frame();
gf.getAccNum();
gf.setVisible(true);
}
public static void main(String[] args)
{
new Handler();
}
Global_Frame gf = null;
}
public static void main(String[] args)
{
new Handler();
}
Global_Vars gv = null;
Global_Frame gf = null;
}
Global Frame:
package com.example.Global;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import com.example.FirstRun.AccDetails;
import com.example.FirstRun.FirstTimeRun;
public class Global_Frame extends JFrame
{
private static final long serialVersionUID = 1L;
ActionListener val = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
getUserDetails();
}
};
public Global_Frame()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // get look and feel based on OS
}
catch (ClassNotFoundException ex) // catch all errors that may occur
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (UnsupportedLookAndFeelException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run() //run the class's constructor, therefore starting the UI being built
{
initComponents();
}
});
}
public void initComponents()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
revalidate(); // revalidate the elements that will be displayed
repaint(); // repainting what is displayed if going coming from a different form
pack(); // packaging everything up to use
setLocationRelativeTo(null); // setting form position central
}
public void getAccNum()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
FirstTimeRun panel1 = new FirstTimeRun(val);
add(panel1);
revalidate();
repaint();
pack();
}
public void getUserDetails()
{
getContentPane().removeAll();
resizing(750, 500);
AccDetails panel2 = new AccDetails();
add(panel2);
revalidate();
repaint();
pack();
}
private void resizing(int width, int height)
{
timer = new Timer (10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
getContentPane().removeAll();
setPreferredSize(new Dimension(sizeW, sizeH));
revalidate();
repaint();
pack();
if (!wToggle)
sizeW += 2;
if (!hToggle)
sizeH += 2;
if (toggle)
{
setLocationRelativeTo(null);
toggle = false;
}
else
toggle = true;
if (sizeW == width)
wToggle = true;
if (sizeH == height)
hToggle = true;
if (hToggle && wToggle)
timer.stop();
}
});
timer.start();
}
//variables used for window resizing
private Timer timer;
private int sizeW = 600;
private int sizeH = 400;
private boolean toggle = false;
private boolean wToggle = false;
private boolean hToggle = false;
public int accNum = 0;
}
First Panel:
package com.example.FirstRun;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class FirstTimeRun extends JPanel
{
private static final long serialVersionUID = 1L;
public FirstTimeRun()
{
}
public FirstTimeRun(ActionListener val)
{
initComponents(val);
}
private void initComponents(ActionListener val) // method to build initial view for user for installation
{
pnlStart = new JPanel[1];
btnNext = new JButton();
pnlStart[0] = new JPanel();
btnNext.setText("Next"); // adding text to button for starting
btnNext.setPreferredSize(new Dimension(80, 35)); //positioning start button
btnNext.addActionListener(val);
pnlStart[0].add(btnNext); // adding button to JFrame
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlStart[0]);
}
// objects used in UI
private JPanel[] pnlStart;
private JButton btnNext;
}
Second Panel:
package com.example.FirstRun;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AccDetails extends JPanel
{
private static final long serialVersionUID = 1L;
public AccDetails()
{
accAssets();
}
private void accAssets()
{
// instantiating elements of the GUI
pnlAccDetails = new JPanel[2];
lblWelcome = new JLabel();
lblMain = new JLabel();
for (int i = 0; i < 2; i++)
pnlAccDetails[i] = new JPanel();
lblWelcome.setText("Welcome to Example_App"); // label welcoming user
pnlAccDetails[0].setLayout(new BoxLayout(pnlAccDetails[0], BoxLayout.LINE_AXIS));
pnlAccDetails[0].add(lblWelcome); // adding label to form
lblMain.setText("<html>The following information that is collected will be used as part of the Example_App process to ensure that each user has unique Example_App paths. Please fill in all areas of the following tabs:</html>"); // main label that explains what happens, html used for formatting
pnlAccDetails[1].setLayout(new BorderLayout());
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_START);
pnlAccDetails[1].add(lblMain, BorderLayout.CENTER); //adding label to JFrame
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_END);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlAccDetails[0]);
add(pnlAccDetails[1]);
}
private JLabel lblWelcome;
private JLabel lblMain;
private JPanel[] pnlAccDetails;
}
I have tried using both a CardLayout and the "revalidate();" "repaint();" and "pack();" options and I'm stumped as to why it's not showing. Thanks in advance for any help that can be offered.
EDIT:
While cutting down my code, if the "resizing" method is removed, the objects are shown when the panels change. I would like to avoid having to remove this completely as it's a smooth transition for changing the JFrame size.
#John smith it is basic example of switch from one panel to other panel I hope this will help you to sort out your problem
Code:
package stack;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class RemoveAndAddPanel implements ActionListener{
JFrame frame;
JPanel firstPanel;
JPanel secondPanel;
JPanel controlPanel;
JButton nextButton;
public RemoveAndAddPanel() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.add(new JLabel("FirstPanel"));
firstPanel.setPreferredSize(new Dimension(100,100));
secondPanel = new JPanel();
secondPanel.add(new JLabel("Second panel"));
secondPanel.setPreferredSize(new Dimension(100,100));
nextButton = new JButton("Next panel");
controlPanel = new JPanel();
nextButton.addActionListener(this);
controlPanel.add(nextButton);
frame.setLayout(new BorderLayout());
frame.add(firstPanel,BorderLayout.CENTER);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setSize(300,100);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == nextButton) {
frame.remove(firstPanel);
frame.add(secondPanel);
nextButton.setEnabled(false);
}
frame.validate();
}
public static void main(String args[]) {
new RemoveAndAddPanel();
}
}
As mentioned in the edit, the problem lay within the resizing method. When the timer stopped, it wouldn't go anywhere, causing the UI to not load. The fix to the code is clearing the screen and adding the call to resizing to the actionlistener. Then adding a call to the next method after:
timer.stop();
Thanks for getting me to remove the mess around it and find the source of the problem #matt & #Hovercraft Full of Eels upvotes for both of you.
The main thing to consider while changing panel in a jframe is the layout, for a body(main) panel to change to any other panel the parent panel must be of type CardLayout body.setLayout(new java.awt.CardLayout());
After that you can now easily switch between panels wiht the sample code below
private void updateViewLayout(final HomeUI UI, final JPanel paneeelee){
final JPanel body = UI.getBody(); //this is the JFrame body panel and must be of type cardLayout
System.out.println("Page Loader Changing View");
new SwingWorker<Object, Object>() {
#Override
protected Object doInBackground() throws Exception {
body.removeAll();//remove all visible panel before
body.add(paneeelee);
body.revalidate();
body.repaint();
return null;
}
#Override
protected void done() {
UI.getLoader().setVisible(false);
}
}.execute();
}
So I started to go into OOP and also started to learn about swing library but I have trouble. When I try to remove all of the JFrame components it doesnt work. What I want to do is when the user clicks a button I have to remove all the JFrame components and add new ones but it doesn't work despite that I used removeAll() repait(), revalidate() etc. Here is my code for the BankApp class:
import javax.swing.*;
public class BankApp{
public static void main(String[] args) {
BankGUI object1;
object1 = new BankGUI();
object1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object1.setSize(700, 500);
object1.setLocationRelativeTo(null);
object1.setResizable(false);
object1.setVisible(true);
}
}
Here is the BankGUI:
import javax.swing.*;
import java.awt.*;
public class BankGUI extends JFrame{
private JButton CreateAccount;
private JButton LoginAccount;
private JButton Exit;
private JButton AboutButton;
private JButton ExitButton;
private JLabel IntroText;
public BankGUI(){
super("Banking App");
createMainMenu();
}
public void createMainMenu(){
add(Box.createRigidArea(new Dimension(0,40)));
IntroText = new JLabel("Banking Application");
IntroText.setMaximumSize(new Dimension(280,60));
IntroText.setFont(new Font("Serif", Font.PLAIN, 34));
IntroText.setAlignmentX(CENTER_ALIGNMENT);
add(IntroText);
add(Box.createRigidArea(new Dimension(0,40)));
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
CreateAccount = new JButton("Register");
CreateAccount.setMaximumSize(new Dimension(200,50));
CreateAccount.setFont(new Font("Serif", Font.PLAIN, 24));
CreateAccount.setAlignmentX(CENTER_ALIGNMENT);
CreateAccount.setFocusable(false);
add(CreateAccount);
add(Box.createRigidArea(new Dimension(0,20)));
LoginAccount = new JButton("Login");
LoginAccount.setMaximumSize(new Dimension(200,50));
LoginAccount.setFont(new Font("Serif", Font.PLAIN, 24));
LoginAccount.setAlignmentX(CENTER_ALIGNMENT);
LoginAccount.setFocusable(false);
add(LoginAccount);
add(Box.createRigidArea(new Dimension(0,20)));
AboutButton = new JButton("About");
AboutButton.setMaximumSize(new Dimension(200,50));
AboutButton.setFont(new Font("Serif", Font.PLAIN, 24));
AboutButton.setAlignmentX(CENTER_ALIGNMENT);
AboutButton.setFocusable(false);
add(AboutButton);
add(Box.createRigidArea(new Dimension(0,20)));
ExitButton = new JButton("Exit");
ExitButton.setMaximumSize(new Dimension(200,50));
ExitButton.setFont(new Font("Serif", Font.PLAIN, 24));
ExitButton.setAlignmentX(CENTER_ALIGNMENT);
ExitButton.setFocusable(false);
add(ExitButton);
ButtonListener actionListener = new ButtonListener(CreateAccount, LoginAccount, AboutButton, ExitButton);
CreateAccount.addActionListener(actionListener);
LoginAccount.addActionListener(actionListener);
AboutButton.addActionListener(actionListener);
ExitButton.addActionListener(actionListener);
}
}
And here is my ButtonListener Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonListener implements ActionListener{
private JButton CreateAccount;
private JButton LoginAccount;
private JButton AboutButton;
private JButton ExitButton;
public ButtonListener(JButton button1,JButton button2,JButton button3,JButton button4){
CreateAccount = button1;
LoginAccount = button2;
AboutButton = button3;
ExitButton = button4;
}
#Override
public void actionPerformed(ActionEvent e) {
BankGUI bankgui = new BankGUI();
if(e.getSource() == CreateAccount){
System.out.println("This prints out");
}else if(e.getSource() == ExitButton){
bankgui.getContentPane().removeAll();
bankgui.removeAll();
bankgui.validate();
bankgui.repaint();
System.out.println("Code reaches here but it doesnt clear the screen");
}
}
}
When I try to do it nothing happens despite that I revalidate and repaint I'm not sure why.I just want to clear the JFrame. I'm 100% sure that the code reaches the methods but for some reason they don't work.
Maybe its obvious mistake but I'm not seeing it.
Any help would be appreciated.
In your actionPerformed method, you are creating another instance of BankGUI, this is, in no way, connected to the instance which is been displayed to the user...
#Override
public void actionPerformed(ActionEvent e) {
BankGUI bankgui = new BankGUI();
//...
}
There are a few ways you "might" correct this, most of them aren't pretty.
You could pass a reference of BankGUI to the ButtonListener along with the buttons. I don't like this idea, as it provides the means for ButtonListener to start doing things to BankGUI it really has no responsibility for doing.
You could use SwingUtilities.getWindowAncestor, passing a reference of the button which was triggered, to get a reference to the window. This has the sam problem as the previous idea, but it also makes assumptions about the structure of the UI, which, ButtonListener shouldn't care about.
In both cases, this couples ButtonListener to BankGUI.
A better solution would be to provide some kind of "navigation manager". The ButtonListener would take a reference of it and when one of the buttons is actioned, would notify the "navigation manager", asking it to perform the actual task.
This de-couples the ButtonListener from the implementation of the UI.
This is all about concepts of "isolation of responsibility", "code reusability" and "model-view-controller"
Overall, a simpler and more practical solution would be to use a CardLayout, which will further de-couple the UI and make it easier to isolate functionality to their own classes/components and allow the primary UI to switch between them
import java.awt.CardLayout;
import static java.awt.Component.CENTER_ALIGNMENT;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JavaApplication101 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BankGUI object1;
object1 = new BankGUI();
object1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object1.pack();
object1.setLocationRelativeTo(null);
object1.setVisible(true);
}
});
}
public interface BankNavigationController {
public void setView(String command);
}
public static class CardLayoutBankNavigationController implements BankNavigationController {
private Container parent;
private CardLayout layout;
public CardLayoutBankNavigationController(Container parent, CardLayout layout) {
this.parent = parent;
this.layout = layout;
}
#Override
public void setView(String command) {
layout.show(parent, command);
}
}
public static class BankGUI extends JFrame {
private CardLayoutBankNavigationController controller;
public BankGUI() {
super("Banking App");
CardLayout layout = new CardLayout();
setLayout(layout);
controller = new CardLayoutBankNavigationController(getContentPane(), layout);
add("Main Menu", createMainMenu());
add("Register", otherView("Register"));
add("Login", otherView("Login"));
add("About", otherView("About"));
add("Exit", otherView("Exit"));
controller.setView("Main Menu");
}
public JPanel otherView(String named) {
JPanel view = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
view.add(new JLabel(named), gbc);
JButton mainMenu = new JButton("Main Menu");
view.add(mainMenu, gbc);
ButtonListener actionListener = new ButtonListener(controller);
mainMenu.addActionListener(actionListener);
return view;
}
public JPanel createMainMenu() {
JPanel menu = new JPanel();
menu.setLayout(new BoxLayout(menu, BoxLayout.PAGE_AXIS));
menu.add(Box.createRigidArea(new Dimension(0, 40)));
JLabel IntroText = new JLabel("Banking Application");
IntroText.setMaximumSize(new Dimension(280, 60));
IntroText.setFont(new Font("Serif", Font.PLAIN, 34));
IntroText.setAlignmentX(CENTER_ALIGNMENT);
menu.add(IntroText);
menu.add(Box.createRigidArea(new Dimension(0, 40)));
JButton CreateAccount = new JButton("Register");
CreateAccount.setMaximumSize(new Dimension(200, 50));
CreateAccount.setFont(new Font("Serif", Font.PLAIN, 24));
CreateAccount.setAlignmentX(CENTER_ALIGNMENT);
CreateAccount.setFocusable(false);
menu.add(CreateAccount);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton LoginAccount = new JButton("Login");
LoginAccount.setMaximumSize(new Dimension(200, 50));
LoginAccount.setFont(new Font("Serif", Font.PLAIN, 24));
LoginAccount.setAlignmentX(CENTER_ALIGNMENT);
LoginAccount.setFocusable(false);
menu.add(LoginAccount);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton AboutButton = new JButton("About");
AboutButton.setMaximumSize(new Dimension(200, 50));
AboutButton.setFont(new Font("Serif", Font.PLAIN, 24));
AboutButton.setAlignmentX(CENTER_ALIGNMENT);
AboutButton.setFocusable(false);
menu.add(AboutButton);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton ExitButton = new JButton("Exit");
ExitButton.setMaximumSize(new Dimension(200, 50));
ExitButton.setFont(new Font("Serif", Font.PLAIN, 24));
ExitButton.setAlignmentX(CENTER_ALIGNMENT);
ExitButton.setFocusable(false);
menu.add(ExitButton);
ButtonListener actionListener = new ButtonListener(controller);
CreateAccount.addActionListener(actionListener);
LoginAccount.addActionListener(actionListener);
AboutButton.addActionListener(actionListener);
ExitButton.addActionListener(actionListener);
return menu;
}
}
public static class ButtonListener implements ActionListener {
private BankNavigationController controller;
public ButtonListener(BankNavigationController controller) {
this.controller = controller;
}
#Override
public void actionPerformed(ActionEvent e) {
controller.setView(e.getActionCommand());
}
}
}
I am making family tree and this is my problem. I have screens NewFamilyTree.java and NewPerson.java.
NewFamilyTree.java:
public class NewFamilyTree {
...
private void initialize() {
frame = new JFrame();
frame.setTitle("New family tree");
frame.setBounds(100, 100, 906, 569);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane();
tabbedPane.addTab("Tree", null, scrollPane, null);
panel_1 = new JPanel();
scrollPane.setViewportView(panel_1);
panel_1.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
NewPerson.java:
public class NewPerson{
...
buttonAdd = new JButton("Add");
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String names = textFieldNames.getText();
String dateBirth = textFieldDateOfBirth.getText();
String bio = textAreaBio.getText();
Data newData = new Data(names, dateBirth, bio, fileID);
//code that puts new label on scrollpane from NewFamilyTree.java
}
});
buttonAdd.setBackground(new Color(30, 144, 255));
frame.getContentPane().add(buttonAdd, "cell 2 6,grow");
}
I need to put new JLabel from class NewPerson, by pressing on button Add, on the JScrollPane of NewFamilytree.java. Hope someone can help, I searched a lot and couldn't help myself.
EDIT: After the answer from #mjr.
I added public JPanel panel_1; in NewFamilyTree. In Add action performed I added:
JLabel lblHomer = new JLabel("Homer");
lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
panel_1.add(lblHomer, "cell 7 5");
No errors, but - nothing happens after I press the add button. I also added NewPerson EXTENDS NewFamilyTree, ofc.
NewPerson doesn't need extend from NewFamilyTree, it's not adding any functionality to the class
Instead of using a JFrame in NewPerson, consider using a modal JDialog instead. See How to Make Dialogs for more details
Limit the exposure of components between classes. There is no reason why NewFamilyTree should be able to access the "window" been used by NewPerson. There's no reason why NewPerson should be adding anything to NewFamilyTree
Don't mix heavy weight components (like java.awt.Button) with light weight components, this can cause no end of issues...
You need to change the way you think of things. Instead of trying to make the NewPerson update the UI of the NewFamilyTree, have NewPerson gather the details from the user and pass this information back to NewFamilyTree so it can use it...
For example...
JButton newPersonButton = new JButton("New Person");
newPersonButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Data data = NewPerson.createPerson(frame);
if (data != null) {
JLabel lblHomer = new JLabel(data.names);
panel_1.add(lblHomer, "cell 7 5");
panel_1.revalidate();
}
}
});
This basically uses a static method createPerson which passes back a instance of Data (or null if the user cancelled the operation), which NewFamilyTree can then use. It decouples the code, as NewPerson is not relient on anything from NewFamilyTree and NewFamilyTree maintains control. This clearly defines the areas of responsibility between the two classes, it also means that NewPerson could be called from anywhere...
The createPerson method looks, something like, this...
public static Data createPerson(Component comp) {
NewPerson newPerson = new NewPerson();
Window win = SwingUtilities.getWindowAncestor(comp);
JDialog dialog = null;
if (win instanceof Frame) {
dialog = new JDialog((Frame) win, "New person", true);
} else if (win instanceof Dialog) {
dialog = new JDialog((Dialog) win, "New person", true);
} else {
dialog = new JDialog((Frame) null, "New person", true);
}
newPerson.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
Window win = SwingUtilities.getWindowAncestor((Component) source);
win.dispose();
}
}
});
dialog.add(newPerson);
dialog.setVisible(true);
return newPerson.getData();
}
It basically creates and instance of JDialog, shows it to the user and waits until the NewPerson class triggers an ActionEvent, which it uses to dispose of the dialog. It then asks the instance of NewPerson for the data...
And because there's a whole bunch of functionality I've not talked about, here's a fully runnable example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
public class NewFamilyTree {
private JFrame frame;
private JPanel panel_1;
private JScrollPane scrollPane;
private JTabbedPane tabbedPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NewFamilyTree window = new NewFamilyTree();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public NewFamilyTree() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("New family tree");
frame.getContentPane().setBackground(new Color(135, 206, 250));
frame.setBounds(100, 100, 906, 569);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(new Color(30, 144, 255));
frame.getContentPane().add(panel, BorderLayout.EAST);
panel.setLayout(new MigLayout("", "[]", "[][][][][][][][]"));
JButton newPersonButton = new JButton("New Person");
newPersonButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Data data = NewPerson.createPerson(frame);
if (data != null) {
JLabel lblHomer = new JLabel(data.names);
// lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
panel_1.add(lblHomer, "cell 7 5");
panel_1.revalidate();
}
}
});
panel.add(newPersonButton, "cell 0 5");
JButton btnNewButton_1 = new JButton("New button");
panel.add(btnNewButton_1, "cell 0 6");
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
scrollPane = new JScrollPane();
tabbedPane.addTab("Tree", null, scrollPane, null);
panel_1 = new JPanel();
scrollPane.setViewportView(panel_1);
panel_1.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
// JLabel lblHomer = new JLabel("Homer");
// lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
// panel_1.add(lblHomer, "cell 7 5");
JScrollPane scrollPane_1 = new JScrollPane();
tabbedPane.addTab("Info", null, scrollPane_1, null);
frame.repaint();
}
//
// /**
// * Launch the application.
// */
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// NewPerson window = new NewPerson();
// window.frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
public static class NewPerson extends JPanel {
private JTextField textFieldNames;
private JButton selectPictureButton;
private JLabel labelDateOfBirth;
private JTextField textFieldDateOfBirth;
private JLabel labelShortBio;
private JTextArea textAreaBio;
private JLabel labelSelectPicture;
private JButton buttonAdd;
private String fileID;
private Data data;
/**
* Create the application.
*/
private NewPerson() {
initialize();
}
public static Data createPerson(Component comp) {
NewPerson newPerson = new NewPerson();
Window win = SwingUtilities.getWindowAncestor(comp);
JDialog dialog = null;
if (win instanceof Frame) {
dialog = new JDialog((Frame) win, "New person", true);
} else if (win instanceof Dialog) {
dialog = new JDialog((Dialog) win, "New person", true);
} else {
dialog = new JDialog((Frame) null, "New person", true);
}
newPerson.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
Window win = SwingUtilities.getWindowAncestor((Component) source);
win.dispose();
}
}
});
dialog.add(newPerson);
dialog.pack();
dialog.setLocationRelativeTo(comp);
dialog.setVisible(true);
return newPerson.getData();
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners != null && listeners.length > 0) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "created");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
public Data getData() {
return data;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setBackground(new Color(135, 206, 250));
setLayout(new MigLayout("", "[][][grow]", "[][][][grow][][][]"));
JLabel labelNames = new JLabel("Name and Surname:");
add(labelNames, "cell 1 1,alignx trailing");
textFieldNames = new JTextField();
add(textFieldNames, "cell 2 1,growx");
textFieldNames.setColumns(10);
labelDateOfBirth = new JLabel("Date of birth:");
add(labelDateOfBirth, "cell 1 2,alignx center,aligny center");
textFieldDateOfBirth = new JTextField();
add(textFieldDateOfBirth, "cell 2 2,growx");
textFieldDateOfBirth.setColumns(10);
labelShortBio = new JLabel("Bio:");
add(labelShortBio, "cell 1 3,alignx center,aligny center");
textAreaBio = new JTextArea();
add(textAreaBio, "cell 2 3,grow");
labelSelectPicture = new JLabel("Select picture:");
add(labelSelectPicture, "cell 1 4,alignx center,aligny center");
selectPictureButton = new JButton("...");
selectPictureButton.setBackground(new Color(30, 144, 255));
selectPictureButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser chooser = new JFileChooser(new File(System.getProperty("user.home") + "\\Desktop"));
chooser.setDialogTitle("Select Location");
chooser.setFileSelectionMode(JFileChooser.APPROVE_OPTION);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
fileID = chooser.getSelectedFile().getPath();
// txtField.setText(fileID);
}
}
});
add(selectPictureButton, "cell 2 4");
buttonAdd = new JButton("Add");
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String names = textFieldNames.getText();
String dateBirth = textFieldDateOfBirth.getText();
String bio = textAreaBio.getText();
data = new Data(names, dateBirth, bio, fileID);
fireActionPerformed();
}
});
buttonAdd.setBackground(new Color(30, 144, 255));
add(buttonAdd, "cell 2 6,grow");
}
}
public static class Data {
private final String names;
private final String dateBirth;
private final String bio;
private final String fileID;
private Data(String names, String dateBirth, String bio, String fileID) {
this.names = names;
this.dateBirth = dateBirth;
this.bio = bio;
this.fileID = fileID;
}
}
}
Don't rely on static to provide functionality across classes. If you HAVE to have something from another class, pass it as a reference. static is not your friend and you should be careful and wary of it's use
Don't expose the fields of your class without very good reason, rely on interfaces to allow classes to provide or get information. This limits what other classes can do.
Separate and isolate responsibility
Take a look at How to Use Trees
The same way that NewFamilyTree's frame is accessible in NewPerson when you add the button to it, the scrollPane must also be accessible in NewPerson, if you want to add a label from that class. So just do the same thing with scrollPane as what you did with frame to be able to use it in NewPerson.
I assumed that the JScrollPane and addButton are in different frames... although it will work for sure if they are in the same frame.
Basically you need to provide getters for the JScrollPane and the JPanel, so that they can be accessed from the NewPerson class.
In the action listener of the buttonAdd, you need to increase the preferred size of the panel,, if the labels don't feet in the current size of the panel. The scrollbars will appear automatically when the preferred size of the panel are bigger that the view size of the JScrollPane.
Please see the code below:
NewFamilyTree.jva:
package dva.test001;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class NewFamilyTree {
private JFrame frame;
private JScrollPane scrollPane;
private JPanel panel;
public NewFamilyTree() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setTitle("New family tree");
frame.setBounds(100, 100, 906, 569);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
panel = new JPanel();
panel.setPreferredSize(new Dimension(700, 300));
panel.setLayout(null);
scrollPane = new JScrollPane(panel);
tabbedPane.addTab("Tree", null, scrollPane, null);
frame.setVisible(true);
}
public static void main(String[] args) {
NewFamilyTree ft = new NewFamilyTree();
NewPerson np = new NewPerson(ft);
}
public JFrame getFrame() {
return frame;
}
public JScrollPane getScrollPane() {
return scrollPane;
}
public JPanel getPanel() {
return panel;
}
}
NewPerson.java:
package dva.test001;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class NewPerson {
private NewFamilyTree familyTree;
private static final int labelHeight = 30;
public NewPerson(NewFamilyTree familyTree) {
this.familyTree = familyTree;
init();
}
public void init() {
JFrame frame = new JFrame();
frame.setTitle("New Person");
frame.setBounds(100, 500, 906, 100);
JButton buttonAdd = new JButton("Add");
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String names = "names"; //textFieldNames.getText();
String dateBirth = "date"; //textFieldDateOfBirth.getText();
String bio = "bio"; //textAreaBio.getText();
//Data newData = new Data(names, dateBirth, bio, fileID);
//code that puts new label on scrollpane from NewFamilyTree.java
JLabel lbl = new JLabel(names);
int top = familyTree.getPanel().getComponentCount() * labelHeight;
if(top + labelHeight > familyTree.getPanel().getHeight()) {
familyTree.getPanel().setPreferredSize(new Dimension(familyTree.getPanel().getWidth(), top + labelHeight));
familyTree.getScrollPane().revalidate();
}
familyTree.getPanel().add(lbl);
lbl.setBounds(10, top, 100, labelHeight);
}
});
buttonAdd.setBackground(new Color(30, 144, 255));
frame.getContentPane().add(buttonAdd);
frame.setVisible(true);
}
}
I am trying to open a new JFrame window with a button click event. There is lots of info on this site but nothing that helps me because I think it is not so much the code I have, but the order it is executed (however I am uncertain).
This is the code for the frame holding the button that I want to initiate the event:
package messing with swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.border.EmptyBorder;
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<String> courseList = new ArrayList<String>();
public ReportGUI(){
reportInterface();
allReportsBtn();
examinnerFileRead();
courseFileRead();
comboBoxes();
}
private void examinnerFileRead(){
try{
Scanner scan = new Scanner(new File("Examiner.txt"));
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void courseFileRead(){
try{
Scanner scan = new Scanner(new File("Course.txt"));
while(scan.hasNextLine()){
courseList.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame AllDataGUI = new JFrame();
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = list.toArray(new String[list.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
String[] comboBox2Array = courseList.toArray(new String[courseList.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
add(panel, BorderLayout.LINE_START);
}
If you don't want to delve into the above code, the button ActionListener is here:
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
This is the code in the class holding the JFrame I want to open:
package messing with swing;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class ViewCourseGUI extends JFrame{
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Courses taught by this examiner");
private JTextArea textArea = new JTextArea();
public void ViewCoursesGUI(){
panels();
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
Could someone please point me in the right direction?
As pointed out by PM 77-3
I had:
public void ViewCoursesGUI(){
panels();
}
When I should have had:
public ViewCourseGUI(){
panels();
}
A Combination of syntax and spelling errors.
Set the visibility of the JFrame you want to open, to true in the actionListener:
ViewCourseGUI viewCourseGUI = new ViewCourseGUI();
viewCourseGUI.setVisible(true);
This will open the new JFrame window once you click the button.
Let ReportGUI implement ActionListener. Then you will implement actionPerformed for the button click. On button click, create the second frame (if it doesn't exist). Finally, set the second frame visible (if it is currently not visible):
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ReportGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 8679886300517958494L;
private JButton button;
private ViewCourseGUI frame2 = null;
public ReportGUI() {
//frame1 stuff
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setLayout(new FlowLayout());
//create button
button = new JButton("Open other frame");
button.addActionListener(this);
add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReportGUI frame = new ReportGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
if (frame2 == null)
frame2 = new ViewCourseGUI();
if (!frame2.isVisible())
frame2.setVisible(true);
}
}
}
This is a simple example. You'll have to add the rest of your code here.
this is the first time I've had a look at JFrames and JPannels and I've come a little stuck.
What I am trying to do is this, I wish to have an starting screen then based on the users button choice it swaps to another screen. To start I have only 2 screens, however once I've moved on there will be multiple screens. I've looked at CardLayout and while that is good it's not the way I wish to go I want to be able to do this first. Here is what I have.
Main.java
import java.awt.BorderLayout;
public class Main extends JFrame {
private JPanel contentPane;
protected boolean someCondition = false;
/**
* Launch the application.
*/
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();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
if( someCondition == false ){
showTest();
someCondition = test.needToReg();
}else{
showTest2();
}
}
private void showTest(){
contentPane.removeAll();
contentPane.add(new test());
setContentPane(contentPane);
revalidate();
repaint();
}
private void showTest2(){
contentPane.removeAll();
contentPane.add(new test2());
setContentPane(contentPane);
revalidate();
repaint();
}
}
test.java
import javax.swing.JPanel;
public class test extends JPanel {
private JTextField textField;
protected static boolean toReg = false;
/**
* Create the panel.
*/
public test() {
setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
System.out.println("Before " + toReg);
toReg = true;
System.out.println("After " + toReg);
}
});
btnNewButton.setBounds(188, 166, 89, 23);
add(btnNewButton);
textField = new JTextField();
textField.setBounds(150, 135, 86, 20);
add(textField);
textField.setColumns(10);
JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
rdbtnNewRadioButton.setBounds(6, 166, 109, 23);
add(rdbtnNewRadioButton);
}
public static boolean needToReg(){
return toReg;
}
}
test2.java
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
public class test2 extends JPanel {
/**
* Create the panel.
*/
public test2() {
setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(56, 59, 89, 23);
add(btnNewButton);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(122, 165, 46, 14);
add(lblNewLabel);
}
}
Running the program with the outputs I included I get this.
Mouse Clicked
Before false
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
I hope it's clear what I am trying to do and I hope you can lend a hand with this. Thanks
Try this out
On clicking the screenSwapper button in the main frame a new Panel is added to the main frame that can have multiple components I have added one button only
On second click this panel is removed and second panel is added to the main frame and previous one is removed.
The swapping is carried as you click the button continuously
You may use two singletons if you want to preserve once created panel in case of MyPanel1 and MyPanel2
You may add more components on each panel and test.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame {
public boolean switcher;
public JPanel currentPanel;
public JPanel panel1;
public JPanel panel2;
public Test() {
this.switcher = false;
this.currentPanel = null;
this.setSize(200, 200);
panel1 = new JPanel();
JButton screenSwapper = new JButton("Screen Swapper");
panel1.add(screenSwapper);
panel2 = new JPanel();
this.getContentPane().setLayout(new GridLayout(2, 2));
this.getContentPane().add(panel1);
this.getContentPane().add(panel2);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
screenSwapper.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (switcher == false) {
currentPanel = new MyPanel1();
switcher = true;
if (panel2.getComponentCount() != 0) {
panel2.removeAll();
}
} else {
switcher = false;
currentPanel = new MyPanel2();
if (panel2.getComponentCount() != 0) {
panel2.removeAll();
}
}
panel2.add(currentPanel);
panel2.repaint();
panel2.revalidate();
}
});
}
public static void main(String[] args) {
Test t = new Test();
}
}
This is the first panel
import java.awt.BorderLayout;
import java.awt.Button;
import javax.swing.JPanel;
public class MyPanel1 extends JPanel{
public MyPanel1() {
// TODO Auto-generated constructor stub
this.setLayout(new BorderLayout());
this.add(new Button("Button1"));
}
}
This is the second Panel
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MyPanel2 extends JPanel {
public MyPanel2() {
this.setLayout(new BorderLayout());
this.add(new JButton("button2"));
}
}