This blog post intends to answer the following questions.
- How to update a JPanel?
- How to dynamically change the contents of a JPanel based on user interaction?
Here is what I have :-
- A File called MainFrame.java that has a button labeled 'Click Me', and a panel called displayPanel.
- A file called Panel1.java that has a button labeled as 'Button1'.
- A file called Panel2.java that has a button labeled as 'Button2'.
- The constructor of my MainFrame class initializez the button 'Click Me' and initializes the displayPanel to Panel1.
- So now when i run the application i get 2 buttons on my screen - 'Click Me' and 'Button 1'.
- When the user clicks on the 'Click Me' Button, i intend to make the displayPanel refer to the Panel 2 and hence display the 'Button 2 on my MainFrame.
Panel1.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
JButton button1;
public Panel1()
{
this.setSize(250,250);
button1=new JButton("Button 1");
this.add(button1);
}
}
//------End Of Source Code------
Panel2.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.*;
public class Panel2 extends JPanel
{
JButton button2;
public Panel2()
{
this.setSize(250,250);
button2=new JButton("Button 2");
this.add(button2);
}
}
//------End Of Source Code------
MainFrame.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MainFrame extends JFrame
{
JPanel displayPanel;
JButton myButton;
public MainFrame()
{
super("MainFrame");
myButton=new JButton("Click Me");
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
updateMainUI();
}
});
this.setSize(400,400);
this.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e )
{
System.exit( 0 );
}
}
);
displayPanel=new Panel1();
Container c=getContentPane();
c.setLayout(new BorderLayout());
c.add(myButton,BorderLayout.NORTH);
c.add(displayPanel,BorderLayout.SOUTH);
this.setVisible(true);
}
public void updateMainUI()
{
this.getContentPane().remove(displayPanel);
displayPanel=new Panel2();
this.getContentPane().add(displayPanel,BorderLayout.SOUTH);
this.getContentPane().validate();
}
public static void main(String [] args)
{
MainFrame mf=new MainFrame();
}
}
//------End Of Source Code------
I wrote this piece of code after toiling for about 3 hours on the internet. At all the places where I searched, the people who had solved a similar problem, just explained the procedure of how they had done it. Nobody had posted any code for the solution(at least in the forums where i searched). For those of you who feel that I am bad at 'googling', I already know that i am bad at it (lolz).I sincerely hope that this piece of code comes in handy to anyone and everyone who stumbles upon it.
Happy Programming ;)
Signing off.
Ryan
No comments:
Post a Comment