I want the JPanel at the center of the frame to be replaced when the corresponding buttons present in the JPanel to the left of the frame are pressed.
I am using cardlayout for replacing the panels in the center.
here is the sample code that i used for changing panels on button click ,but it doesn't work. can anyone let me know whats wrong in the code.
Library extends JFrame
Public Library(){
Container container = getContentPane();
container.setLayout( new BorderLayout() );
setExtendedState(JFrame.MAXIMIZED_BOTH);
banner = new BannerPanel();
container.add(banner,BorderLayout.NORTH);
MenuButtons = new MenuButtonPanel();
container.add(MenuButtons,BorderLayout.WEST);
SelectedButtonPanel = new SelectedPanel(container);
setLocationRelativeTo(null);
setVisible( true );
init();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MenuButtonPanel extends JPanel and has multiple buttons in it. The inner class of it ButtonHandler implements hte actionListner for the buttons
//inner class
class ButtonEventHandler implements ActionListener {
public void actionPerformed( ActionEvent event ){
SelectedPanel selectObj = new SelectedPanel();
if("about".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("about");
}
else if("checkout".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("checkout");
}
else if("search".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("search");
}
The SelectedPanel should display the replaced Jpanel in the center of the frame
public SelectedPanel() {}
public SelectedPanel(Container framePane)
{
addSelectedPanel(framePane);
}
public void addSelectedPanel(Container framePane)
{
cardPanel = new JPanel();
//set layout of panel
cardPanel.setLayout(new CardLayout());
cardPanel.setBorder(null);
cardPanel.setForeground(new Color(0, 0, 0));
//this.selObj = selObj;
aboutPanel = new About();
checkoutPanel = new Checkout();
searchPanel = new Search();
cardPanel.add(aboutPanel,ABOUTBUTTON);
cardPanel.add(checkoutPanel,CHECKOUTBUTTON);
cardPanel.add(searchPanel, SEARCHBUTTON);
framePane.add(cardPanel, BorderLayout.CENTER); }
The selectedPanel class also has method showReplacePanel() which is called in the actionPerformed of the buttonClick.
public void showReplacePanel(String selObj)
{
System.out.println("cardlayout entered");
CardLayout cl = (CardLayout)(cardPanel.getLayout());
System.out.println("cardlayout entered");
switch(selObj){
case "about":
cl.show(cardPanel,ABOUTBUTTON);
break;
case "search":
//this.repPanel = searchPanel;
cl.show(cardPanel,SEARCHBUTTON);
break;
case "checkout":
cl.show(cardPanel,CHECKOUTBUTTON);
//this.repPanel = checkoutPanel;
break;
I created an example for you, take a look at the actionPerformed(ActionEvent e) method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelSwap extends JPanel implements ActionListener {
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
public PanelSwap() {
super(new BorderLayout());
firstPanel.setBackground(Color.RED);
secondPanel.setBackground(Color.YELLOW);
JButton swap1 = new JButton("SwapToYellow");
swap1.addActionListener(this);
JButton swap2 = new JButton("SwapToRed");
swap2.addActionListener(this);
firstPanel.add(swap1);
secondPanel.add(swap2);
add(firstPanel);
}
/** Listens to the buttons and perfomr the swap. */
public void actionPerformed(ActionEvent e) {
for (Component component : getComponents())
if (firstPanel == component) {
remove(firstPanel);
add(secondPanel);
} else {
remove(secondPanel);
add(firstPanel);
}
repaint();
revalidate();
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("PanelSwap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new PanelSwap();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Related
I am trying to do have two button in JFrame, and I call the setBounds method of them for setting the positions and size of them and also I passed null to setLayout1 because I want to usesetBounds` method of component.
Now I want to do something with my code that whenever I resize the frame buttons decoration will change in a suitable form like below pictures:
I know it is possible to use create an object from JPanel class and add buttons to it and at the end add created panel object to frame, but I am not allowed to it right now because of some reason (specified by professor).
Is there any way or do you have any suggestion?
My code is like this:
public class Responsive
{
public static void main(String[] args)
{
JFrame jFrame = new JFrame("Responsive JFrame");
jFrame.setLayout(null);
jFrame.setBounds(0,0,400,300);
JButton jButton1 = new JButton("button 1");
JButton jButton2 = new JButton("button 2");
jButton1.setBounds(50,50,100,100);
jButton2.setBounds(150,50,100,100);
jFrame.add(jButton1);
jFrame.add(jButton2);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setVisible(true);
}
}
A FlowLayout with no horizontal spacing, some vertical spacing and large borders could achieve that easily. A null layout manager is never the answer to a 'responsive' robust GUI.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ResponsiveGUI {
private JComponent ui = null;
ResponsiveGUI() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 8));
ui.setBorder(new EmptyBorder(10,40,10,40));
for (int i=1; i<3; i++) {
ui.add(getBigButton(i));
}
}
public JComponent getUI() {
return ui;
}
private final JButton getBigButton(int number) {
JButton b = new JButton("Button " + number);
int pad = 20;
b.setMargin(new Insets(pad, pad, pad, pad));
return b;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ResponsiveGUI o = new ResponsiveGUI();
JFrame f = new JFrame("Responsive GUI");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
You could try to use:
jFrame.addComponentListener(new ComponentListener() {
// this method invokes each time you resize the frame
public void componentResized(ComponentEvent e) {
// your calculations on buttons
}
});
I have two classes here: MainScreen and QueryScreen. MainScreen has already implemented one JTabbedPane on int. QueryScreen extended the MainScreen.
I tried to add one tab calling one event through QueryScreen but its not coming up on the app. Checkout please the sample code:
QueryScreen:
public class QueryScreen extends MainScreen {
private JSplitPane engineList;
final JPanel queryList = new JPanel();
public QueryScreen(){
tabbedPane.addTab( "Query List", queryList );
add( tabbedPane, BorderLayout.CENTER );
}
}
MainScreen:
public class MainScreen extends JFrame implements ActionListener {
/**
*
*/
JMenuBar bar;
JMenu file, register;
JMenuItem close, search;
ImageIcon image1= new ImageIcon("rsc/img/logo.jpg");
JLabel lbImage1;
JTabbedPane tabbedPane = new JTabbedPane();
final JPanel entrance = new JPanel();
/**
*
*/
public MainScreen()
{
lbImage1= new JLabel(image1, JLabel.CENTER);
entrance.add(lbImage1);
tabbedPane.addTab( "Entrance", entrance );
add( tabbedPane, BorderLayout.CENTER );
bar= new JMenuBar();
file= new JMenu("File");
register= new JMenu("Search");
close= new JMenuItem("Close");
close.addActionListener(this);
search= new JMenuItem("Request Query");
search.addActionListener(this);
//Keyboard Shortcut
register.setMnemonic(KeyEvent.VK_S);
file.setMnemonic(KeyEvent.VK_F);
search.setMnemonic(KeyEvent.VK_R);
//Ibimage1.setVerticalTextPosition(SwingConstants.CENTER);
bar.add(file);
bar.add(register);
file.add(close);
register.add(search);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); // Maximized Window or setSize(getMaximumSize());
setTitle("SHST");
setJMenuBar(bar);
setDefaultCloseOperation(0);
WindowListener J=new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
addWindowListener(J);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
Search s= new Search();
s.setVisible(true);
}
}
}
ps: the MainScreen object and the setVisible from it is coming from the run class which has only the call for this MainScreen.
How am I able to add this new tab?
Thanks in advance
Edit One:
In the future please post an SSCCE instead of copy/pasting some classes.
Here's an SSCCE of your MainScreen, with the non-essentials stripped out, and a main method added:
import java.awt.*;
import javax.swing.*;
public class MainScreen extends JFrame
{
JTabbedPane tabbedPane = new JTabbedPane();
final JPanel entrance = new JPanel();
public MainScreen()
{
tabbedPane.addTab("Entrance", entrance);
add(tabbedPane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new MainScreen();
frame.setSize(300, 200);
frame.setVisible(true);
}
});
}
}
... and here's an SSCCE for QueryScreen:
import java.awt.*;
import javax.swing.*;
public class QueryScreen extends MainScreen
{
final JPanel queryList = new JPanel();
public QueryScreen()
{
tabbedPane.addTab("Query List", queryList);
//add( tabbedPane, BorderLayout.CENTER ); /* not needed */
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new QueryScreen();
frame.setSize(300, 200);
frame.setVisible(true);
}
});
}
}
As you can see, this works, and for the most part, all I did was remove unnecessary code and added a main to each.
If you're still having problems, please update your question with an SSCCE and post the specific problem you're having.
I am using eclipse 4.2 with Java.
I have 2 java program : AppWin.java Form1.java
AppWin.java is gui windows application with menu/menu item1.
Form1.java is a Gui Jframe
I like to call Form1.java from AppWin.java by click the menu/menu item1.
When close Form1.java, it is back to AppWin.java.
This is something like MDIFORM. I really cannot find answer.
Please help , if you know eclipse menu.
Thanks
package top;
import java.awt.EventQueue;
public class AppWin {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppWin window = new AppWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
...
With your help, I made a big step.
Thanks to all of you!
Next is my final demo, in windows 7, eclipse 4.2, java Gui
Hope it is helpful to others.
There are 3 parts : AppWin, Form1, Form2. AppWin is top main which call Form1 and Form2 with menu/item.
//1
package top;
import java.awt.EventQueue;
public class AppWin {
private JFrame frame;
private Form1 form1;
private Form2 form2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppWin window = new AppWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AppWin() {
initialize();
form1 = new Form1();
form2 = new Form2();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Menu1");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem = new JMenuItem("menu item1");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
form1.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("menu item2");
mntmNewMenuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
form2.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem_1);
JMenu mnNewMenu_1 = new JMenu("Menu2");
menuBar.add(mnNewMenu_1);
JMenuItem mntmMenuItem = new JMenuItem("Menu item3");
mnNewMenu_1.add(mntmMenuItem);
}
}
//2
package top;
import java.awt.BorderLayout;
public class Form1 extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 frame = new Form1();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Form1() {
// 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);
JLabel lblNewLabel = new JLabel("this Form1");
contentPane.add(lblNewLabel, BorderLayout.WEST);
textField = new JTextField();
contentPane.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
contentPane.add(btnNewButton, BorderLayout.EAST);
}
}
//3
package top;
import java.awt.BorderLayout;
public class Form2 extends JDialog {
private final JPanel contentPanel = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Form2 dialog = new Form2();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Form2() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JLabel lblThisForm = new JLabel("This Form2");
contentPanel.add(lblThisForm);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
}
Thanks again
You better use JDesktopPane + JInternalFrame for that purpose instead. Here's a quick sample.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class JInternalFrameSample {
private JPanel pnlMain;
private JDesktopPane desk;
public JInternalFrameSample(){
pnlMain = new JPanel(new BorderLayout()){
#Override public Dimension getPreferredSize(){
return new Dimension(600,600);
}
};
desk = new JDesktopPane();
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Internal Frame");
JMenuItem item = new JMenuItem();
item.setAction(new AbstractAction("Create New") {
#Override
public void actionPerformed(ActionEvent arg0) {
JInternalFrame iFrame = new JInternalFrame("Created from Menu");
iFrame.setResizable(true);
iFrame.setClosable(true);
iFrame.setIconifiable(true);
iFrame.setSize(new Dimension(300, 300));
iFrame.setLocation(0, 0);
//iFrame.getContentPane().setLayout(new BorderLayout());
//iFrame.getContentPane().add( new YourCustomUI().getUI() );
iFrame.setVisible(true);
desk.add(iFrame);
}
});
menu.add(item);
bar.add(menu);
pnlMain.add(bar, BorderLayout.PAGE_START);
pnlMain.add(desk, BorderLayout.CENTER);
}
private JPanel getUI(){
return pnlMain;
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Demo");
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JInternalFrameSample().getUI());
frame.pack();
frame.setVisible(true);
}
});
}
}
See also : How to Use Internal Frames
If you do not like the JDesktopPane and JInternalFrame solution, just use your AppWin JFrame as is, and open modal JDialogs for the rest of the forms, instead of JFrames. Modal dialogs can float around the desktop and do not allow you to click your AppWin, until they are closed.
It is usually better to use just one main JFrame for an application, unless you have some wizard application that moves progressively from one JFrame to the other and back. Even with a wizard app, you can stick with one JFrame and update progressively just the ContentPane with JPanels.
Here is the AppWin JFrame:
public class AppWin extends javax.swing.JFrame {
private Form1 form1;
private Form1 form2;
...
private FormN formN;
public AppWin() {
initComponents();
form1 = new Form1(this, true);
form2 = new Form2(this, true);
...
formN = new FormN(this, true);
}
...
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
form1.setVisible(true);
}
And here is your Form1 JDialog:
public class Form1 extends javax.swing.JDialog {
public Form1(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
...
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
setVisible(false);
}
I only use NetBeans for GUI building because that's more convenient. In the following I can tell you how to achieve what you want to do but I can't tell you how to layout all the components because NetBeans do that for me.
So basically you want to 1. show secondFrame by clicking a menuitem and then close mainFrame, 2. show mainFrame after closing secondFrame, yes? Then, the key is to pass the reference of mainFrame to secondFrame, and write your own method of formClosing event of secondFrame. Something like this:
In the menuItem method in your mainframe:
private void menuItemActionPerformed(java.awt.event.ActionEvent evt) {
//pass 'this' frame's (mainFrame) reference to the secondFrame
SecondFrame newFrame = new SecondFrame(this);
newFrame.setVisible(true); //show the secondFrame
this.setVisible(false); //hide this frame (mainFrame)
}
In your secondFrame:
public class SecondFrame extends javax.swing.JFrame {
private MainFrame mainFrame;
//define your own constructor that can use mainFrame's reference
public SecondFrame(MainFrame mainFrame) {
initComponents();
this.mainFrame = mainFrame;
}
private void initComponents(){
//bind your own event for closing second frame
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
/***********your stuff***************/
}
//show mainFrame when closing this frame and then dispose this frame
private void formWindowClosing(java.awt.event.WindowEvent evt) {
mainFrame.setVisible(true);
this.dispose();
}
}
The codes above is for disposing the secondFrame when closing it. If you just want to hide the secondFrame when closing for future use, then the codes will be slightly different. Let me know what you up to.
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
form1.setVisible(true);
dispose();
}
I'm creating a very simple program.
I have created this classes :
MainJframeClass, JDesktopPaneClass, JinternalFrameClass1 and JinternalFrameClass2.
what ive done is that i instantiated my jdesktoppaneclass and named it desktoppane1 and i added it to the MainJframeclass. i have also instantiated the 2 jinternalframes and named it internal1 and internal2. Now, i have button in mainjframeclass that when i press, i add the internal1 to desktoppane1. what my problem now is how to add the internal2 to desktoppane1 using a button placed somewhere in internal1. i know that why could i just add another button to desktoppane1 and add the internal2. but i have done it already, i just want to solve this problem. if you can help me please. sorry for my english by the way.
It's simply a matter of references. The code that adds something to the JDesktopPane must have a reference to it, and so you will need to pass that reference into the class that needs it say via either a constructor parameter or a method parameter.
Edit 1
For example:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class ReferenceExample extends JPanel {
private JDesktopPane desktop = new JDesktopPane();
private Random random = new Random();
public ReferenceExample() {
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addInternalFrame();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(addInternalFrameBtn);
setPreferredSize(new Dimension(600, 450));
setLayout(new BorderLayout());
add(new JScrollPane(desktop), BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
}
public void addInternalFrame() {
MyInternalFrame intFrame = new MyInternalFrame(ReferenceExample.this);
int x = random.nextInt(getWidth() - intFrame.getPreferredSize().width);
int y = random.nextInt(getHeight() - intFrame.getPreferredSize().height);
intFrame.setLocation(x, y);
desktop.add(intFrame);
intFrame.setVisible(true);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Reference Eg");
frame.getContentPane().add(new ReferenceExample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyInternalFrame extends JInternalFrame {
// pass in the reference in the constructor
public MyInternalFrame(final ReferenceExample refEg) {
setPreferredSize(new Dimension(200, 200));
setClosable(true);
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// use the reference here
refEg.addInternalFrame();
}
});
JPanel panel = new JPanel();
panel.add(addInternalFrameBtn);
getContentPane().add(panel);
pack();
}
}
how to add the internal2 to desktoppane1 using a button placed somewhere in internal1.
In the ActionListener added to your button you can use code like the following to get a reference to the desktop pane:
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)event.getSource());
if (container != null)
{
JDesktopPane desktop = (JDesktopPane)container;
JInternalFrame frame = new JInternalFrame(...);
desktop.add( frame );
}
Let's say there is a button and if you will click that, a new frame will appear and so on...
The setVisible(true); function is used to display a frame. Create an object of the desired frame and call this function. Something like this
//The applications first or the main frame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame extends JFrame {
private JButton myFirstButton;
private JButton mySecondButton;
// Constructor for a new frame
public MainFrame {
super("My First Button Program");
myFirstButton = new JButton("First Frame");
myFirstButton.setFont(new Font( "Arial", Font.BOLD, 18));
myFirstButton.setBackground(Color.red);
mySecondButton = new JButton("New Frame");
mySecondButton.setFont(new Font( "Arial", Font.BOLD, 18));
mySecondButton.setBackground(Color.green);
Container c = getContentPane();
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
c.setLayout(fl);
c.add (myFirstButton);
c.add (mySecondButton);
ButtonHandler handler = new ButtonHandler(); //creation of a new Object
myFirstButton.addActionListener(handler); // Attach/register handler to myFirstButton
mySecondButton.addActionListener(handler); //Attach/register handler to mySecondButton
setSize(400, 300);
show();
}
public static void main(String [] args) {
// Make frame
MainFrame f = new MainFrame();
f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// This closes the window and terminates the
// Java Virtual Machine in the event that the
// Frame is closed by clicking on X.
System.out.println("Exit via windowClosing.");
System.exit(0);
}
}
);
} // end of main
// inner class for button event handling
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myFirstButton) {
new NewFrame1();
}
if (e.getSource() == mySecondButton) {
new NewFrame2();
}
}
} // end of inner class
} // end of outer class
The frame to be opened for first button
//import statements here
public class NewFrame1 extends JFrame implements ActionListener
{
//initialises the frame and opens it
public NewFrame1()
{
JButton open = new JButton("New Window");
open.addActionListener(this);
add(open);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
//code for the new frame
}
}
The frame to be opened for second button
//import statements here
public class NewFrame2 extends JFrame implements ActionListener
{
//initialises the frame and opens it
public NewFrame2()
{
JButton open = new JButton("New Window");
open.addActionListener(this);
add(open);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
//code for the new frame
}
}
Make one JFrame class, call it MainFrame for example, and from here open JPanels, that way you have a centralized place to commuincate data between different frames,popups,options dialogs ...etc
Sidenote: i recommend using an MVC design pattern
Your usage context is unclear. Maybe what you need is a JTabbedPane (tutorial)?