I've run the following code in eclipse as an application and it works perfectly, however when I try to run it as an applet I get the window that says "Button to text" but none of the buttons appear. Also, an empty "applet viewer" windows pops up. Here is the code.
/**This program completes the requirements described
* in Option 3 which is to create a frame that contains 3 buttons.
* These buttons then will update the text shown on the frame.
* The program uses AWT and Swing to accomplish this task.
* For more information on the particular methods of this program, look below.
* Press a button to change the text on the bottom to the text displayed on the button
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingOption3 extends Applet {
private JFrame mainFrame;
private JLabel header;
private JLabel status;
private JPanel control;
//initialize the variables by creating them
public SwingOption3(){
prepareGUI();
//this constructor runs the prepareGUI method
}
public static void main(String[] args){
SwingOption3 swingOption3 = new SwingOption3();
swingOption3.showEvent();
//creates an object from the main class and runs the showEvent method
}
/** The following method performs these actions
* 1. Adds a title to the frame ("Button to Text")
* 2. Sets the size to 400 by 400
* 3. Uses the GridLayout to proportion the frame
* 4. Initializes the header and status variables
* 5. Adds a listener to the main frame
* 6. Adds the header, status, and control to the main frame
* 7. Sets the main frame to visible
* 8. Sets the control layout to flow
*/
private void prepareGUI(){
mainFrame = new JFrame("Button to Text");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
header = new JLabel("",JLabel.CENTER );
status = new JLabel("", JLabel.CENTER);
status.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
//this method allows the program window to be closed
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
control = new JPanel();
control.setLayout(new FlowLayout());
mainFrame.add(header);
mainFrame.add(control);
mainFrame.add(status);
mainFrame.setVisible(true);
}
/**The following method completes these tasks:
* 1. Sets the text of the header to inform the user what they should do
* 2. Adds the buttons to the JPanel "control"
* 3. Creates the listener methods and describes the ActionEvent
* that will be sent for each button press
**/
private void showEvent(){
header.setText("Press a button to change the text at the bottom");
//informs the user to press a button in order to change the text
JButton appleButton = new JButton("Apple");
JButton pearButton = new JButton("Pear");
JButton bananaButton = new JButton("Banana");
//creates the buttons and titles them
appleButton.setActionCommand("Apple");
pearButton.setActionCommand("Pear");
bananaButton.setActionCommand("Banana");
//sets the command that will be received and interpreted by the program
appleButton.addActionListener(new ButtonClickListener());
pearButton.addActionListener(new ButtonClickListener());
bananaButton.addActionListener(new ButtonClickListener());
//creates listeners for the button clicks
control.add(appleButton);
control.add(pearButton);
control.add(bananaButton);
//adds the buttons to the JPanel "control"
mainFrame.setVisible(true);
//makes the frame visible
}
private class ButtonClickListener implements ActionListener {
/**
* This method performs the following actions
* 1.Receives the command/ActionEvent from the previous method
* 2. Displays the appropriate text based on the ActionEvent
*/
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Apple")) {
status.setText("Display: Apple");
} //sets the display to "Display: Apple"
else if( command.equals("Pear")) {
status.setText("Display: Pear");
} //sets the display to "Display: Pear"
else {
status.setText("Display: Banana");
} //sets the display to "Display: Banana"
}
}
}
`
I'm not quite sure where I'm going wrong so I posted the whole thing. I appreciate your help.
You don't create new JFrames in applets, you use the applet itself as the container for your controls. And your contructor doesn't call showEvent()--the other controls never got instantiated.
Related
I wrote this after seeing videos of thenewboston and then, when I ran, only the last item added was visible and all other textFields [textField1, textField2 and textField3] are not visible. It worked perfectly in his videos but when I tried, only the passwordField was visible. I'm a beginner and I was unable to find what's the problem. Please help me out what is the problem and what should I do to mitigate this error. One small request, please explain a bit detail because I a newbie to Java and GUI.
package learningPackage;
import java.awt.FlowLayout;
//gives the layout
import java.awt.event.ActionListener;
//this makes the field wait for an event.
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JTextField;
//creates a field where we can type text.
import javax.swing.JPasswordField;
//creates a text field where the text typed is hidden with asterics.
class tuna extends JFrame
{
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JPasswordField passwordField;
public tuna()
{
super("Title Text");
textField1 = new JTextField(10);
//sets a the default value of 10.
add(textField1);
textField2 = new JTextField("Enter a Text");
//sets default text of "Enter a Text" without the quotes
add(textField2);
textField3 = new JTextField("Uneditable", 20);
//Displays Uneditable with a default value of 20.
//To make this Uneditable, you must do this...
textField3.setEditable(false);
//this makes the textField uneditable.
add(textField3);
passwordField = new JPasswordField("myPassword");
add(passwordField);
thehandler Handler = new thehandler();
textField1.addActionListener(Handler);
textField2.addActionListener(Handler);
textField3.addActionListener(Handler);
passwordField.addActionListener(Handler);
/*
* The addActionListener method takes an object of Event Handler class.
*
* Therefore, we must create an object of Event Handler Class.
*
*
* The addActionListener method takes an object because, sometimes, we might
* have different classes with different code to execute. So, we pass the object to
* identify which class code is to be executed.
*/
}
class thehandler implements ActionListener
{
/*
* In order to handle events in Java, you need Event handler Class.
* and, that Event Handler Class must implement ActionListener.
*
* What the ActionListener does is that
*
* It will wait for some Event to happen and after that particular event happens,
* it will implement some piece of code.
*/
public void actionPerformed(ActionEvent event)
{
String string = "";
if(event.getSource()==textField1)
string = String.format("Text Field 1 : %s", event.getActionCommand());
else if(event.getSource()==textField2)
string = String.format("Text Field 2 : %s", event.getActionCommand());
else if(event.getSource()==textField3)
string = String.format("Text Field 3 : %s", event.getActionCommand());
else if(event.getSource()==passwordField)
string = String.format("Password Field : %s", event.getActionCommand());
//when the user presses enter key after entering text, this actually stores the
//thing entered into the String.
JOptionPane.showConfirmDialog(null, string);
}
}
}
public class Apples {
public static void main(String[] args)
{
tuna Srivathsan = new tuna();
Srivathsan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this would close the window when X button is pressed.
Srivathsan.setSize(500, 500);
Srivathsan.setVisible(true);
Srivathsan.setLocationRelativeTo(null);
}
}
Here is the image of the window :
import java.awt.FlowLayout;
//gives the layout
That statement imports the layout & makes it available to the code, but does not set the layout on any container.
While a JPanel has a default layout of FlowLayout, the default layout of the (content pane of the) JFrame is BorderLayout. A BorderLayout accepts up to 5 components or containers (like JPanel) in each of 5 constraints. If no constraint is given, it defaults to the CENTER. If more than one component is added to the CENTER (or any other area of a BorderLayout), all but one of those components will fail to appear. I cannot recall if it is the first or last that appears, but it's a moot point, because the code should not do that.
My advice would be as follows:
Don't extend JFrame (or JPanel).
Add one JPanel to the JFrame.
Add the components (and/or containers) to that JPanel.
Here is an example implementing points 2 & 3. Point 1 is not implemented (batteries not included).
import javax.swing.*;
public class SingleComponentLayoutProblem extends JFrame {
private final JTextField textField1;
private final JTextField textField2;
private final JTextField textField3;
private final JPasswordField passwordField;
public SingleComponentLayoutProblem() {
super("Title Text");
JPanel panel = new JPanel(); // uses FlowLayout be DEFAULT
add(panel);
textField1 = new JTextField(10);
//sets a the default value of 10.
panel.add(textField1);
textField2 = new JTextField("Enter a Text");
//sets default text of "Enter a Text" without the quotes
panel.add(textField2);
textField3 = new JTextField("Uneditable", 20);
//Displays Uneditable with a default value of 20.
//To make this Uneditable, you must do this...
textField3.setEditable(false);
//this makes the textField uneditable.
panel.add(textField3);
passwordField = new JPasswordField("myPassword");
panel.add(passwordField);
}
public static void main(String[] args) {
Runnable r = () -> {
SingleComponentLayoutProblem sclp =
new SingleComponentLayoutProblem();
sclp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this would close the window when X button is pressed.
// don't guess sizes! ..
//sclp.setSize(500, 500);
// .. instead ..
sclp.pack();
sclp.setVisible(true);
sclp.setLocationRelativeTo(null);
};
SwingUtilities.invokeLater(r);
}
}
I want to be able to pass user input from my GUI to one of my classes. However, the input is not passed over and immediately checks the if statement.
How do I get program to wait for the input and only checks after the button is clicked?
Main class
public class MainTest {
public static void main(String[] args) {
String weaponCategory;
//Create Java GUI
GUITest window = new GUITest();
if(window.getCategory() != "")
{
System.out.println("test");
}
}
}
GUITest class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest implements ActionListener{
private JFrame frmInventorysystem;
private JPanel frameBottom;
private JComboBox equipList;
private String category = "";
private JButton confirmBtn, cancelBtn;
/**
* Create the application.
*/
public GUITest()
{
frmInventorysystem = new JFrame();
frmInventorysystem.setTitle("InventorySystem");
frmInventorysystem.setBounds(100, 100, 450, 300);
frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));
frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*JFrame inside another JFrame is not recommended. JPanels are used instead.
* Creating a flow layout for the bottom frame
*/
frameBottom = new JPanel();
frameBottom.setLayout(new FlowLayout());
//creates comboBox to find out which of the three items player is looking to insert
String[] weaponCategories = {"Weapon", "Armor", "Mod"};
equipList = new JComboBox(weaponCategories);
frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);
//Converting BorderLayout.south into a flow layout
frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);
confirmBtn = new JButton("Confirm");
confirmBtn.addActionListener(this);
frameBottom.add(confirmBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(this);
frameBottom.add(cancelBtn);
frmInventorysystem.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
//creates new windows to sort equipment when confirmBtn is clicked
if(e.getSource() == confirmBtn)
{
if(equipList.getSelectedItem().equals("Weapon"))
{
//GUIWeaponCategory weapon = new GUIWeaponCategory();
category = equipList.getSelectedItem().toString();
}
}
//Exits when cancelBtn is clicked
if(e.getSource() == cancelBtn)
{
System.exit(0);
}
}
public String getCategory()
{
return category;
}
public void setCategory(String a)
{
category = a;
}
}
GUITest launches as expected.
However, the first println is missing.
How would I go about doing this?
What concepts or pieces of code am I missing?
EDIT1: Added a couple more details to make the program reproducible and complete.
EDIT2: Making the code more readable for easy understanding.
There are some changes to make on your program
Remove extends JFrame as stated in my comments above, see Extends JFrame vs. creating it inside the program
Place your program on the EDT, see point #3 on this answer and the main method for an example on how to do that.
You're confused about how the ActionListeners work, they wait until you perform certain action in your program (i.e. you press Confirm button) and then do something. "Something" in your program means: Print the selected item and check if it's a weapon then, do something else.
So, in this case, you don't need to return back to main to continue with your program, main only serves to initialize your application and nothing else. You need to think in the events and not in a sequential way. That's the tricky and most important part.
You need to change your programming paradigm from console applications and do-while that everything happens in a sequential manner rather than events that are triggered when the user does something with your application.
For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest implements ActionListener {
private JFrame frmInventorysystem;
private JPanel frameBottom;
private JComboBox equipList;
private JButton confirmBtn, cancelBtn;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GUITest()); //Java 8+ if using an earlier version check the point #2 in this answer and modify the code accordingly.
}
/**
* Create the application.
*/
public GUITest() {
frmInventorysystem = new JFrame();
frmInventorysystem.setTitle("InventorySystem");
frmInventorysystem.setBounds(100, 100, 450, 300);
frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));
/*
* JFrame inside another JFrame is not recommended. JPanels are used instead
* Creating a flow layout for the bottom frame
*/
frameBottom = new JPanel();
frameBottom.setLayout(new FlowLayout());
// creates comboBox to find out which of the three items player is looking to
// insert
String[] weaponCategories = { "Weapon", "Armor", "Mod" };
equipList = new JComboBox(weaponCategories);
frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);
// Converting BorderLayout.south into a flow layout
frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);
confirmBtn = new JButton("Confirm");
confirmBtn.addActionListener(this);
frameBottom.add(confirmBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(this);
frameBottom.add(cancelBtn);
frmInventorysystem.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// creates new windows to sort equipment when confirmBtn is clicked
if (e.getSource() == confirmBtn) {
String category = equipList.getSelectedItem().toString(); //Get the selected category
doSomething(category); //Pass it as a parameter
}
// Exits when cancelBtn is clicked
if (e.getSource() == cancelBtn) {
frmInventorysystem.dispose();
}
}
// Do something with the category
private void doSomething(String selectedEquipment) {
System.out.println(selectedEquipment);
if (selectedEquipment.equals("Weapon")) {
System.out.println("It's a weapon!"); //You can open dialogs or do whatever you need here, not necessarily a print.
} else {
System.out.println("Not a weapon");
}
}
}
Notice that I removed inheritance, I'm not returning back to main and still printing the selected item and checking if it's a weapon or not.
I also exit the application in a safer way.
This is a sample output:
Weapon
It's a weapon!
Armor
Not a weapon
I'm wondering how I can run a piece of code after a user presses a button. In this case I'm asking the user to enter their name in a textField (Shown below)
TextField textField = new TextField();
textField.setBounds(104, 271, 517, 48);
contentPane.add(textField);
Then after the user has clicked Next I'd like the GUI to move to another line of code that changes the layout of the GUI.
I'm assuming I'd need to put something in here that would then run another line of code elsewhere,
JButton Next = new JButton("Next");
Next.addMouseListener(new MouseAdapter() {
#Override
//Would I need to put something here?
public void mouseClicked(MouseEvent e) {
}
});
Details
What I'm trying to do is create a game. I want the user to be able to input their name, then I want the user to be able to click a button that says 'next', and then once that button is pressed I would like things in the Java Program to change. I.E, text to change to something else.
After the user would input their details for the game (Name, preferred Class, Gender, etc), I'd have the Components be removed and then have a image and at some point, their Health.
You could use a CardLayout to change the GUI appearance. Each "screen" of your GUI is represented by a card. Certain events (like pressing a button) can trigger a new card to be shown, hence showing a new screen of your GUI.
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
class Game{
/* This JPanel will manage all the cards we create */
JPanel cards = new JPanel(new CardLayout());
JTextField jtfName;
JButton jbtName;
String name;
Game(){
JFrame jfrm = new JFrame("Game");
jfrm.setSize(200, 220);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* Setup card 1: This card asks for a username
* and then changes to the next screen when the
* user clicks the "next" button.
*/
JPanel card1 = new JPanel(new FlowLayout());
jtfName = new JTextField(15);
jbtName = new JButton("Next");
jbtName.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
/* Make sure a username was entered */
if (!jtfName.getText().equals("")){
name = jtfName.getText();
swapCards("card2");
}
}
});
card1.add(new JLabel("Name:"));
card1.add(jtfName);
card1.add(jbtName);
/* Setup card 2 */
JPanel card2 = new JPanel(new FlowLayout());
card2.add(new JLabel("Game stuff here ... "));
/* Add cards to the controlling card. */
cards.add(card1, "card1");
cards.add(card2, "card2");
/* Add the cards panel to the Frame and display */
jfrm.add(cards);
jfrm.setVisible(true);
}
/* Method to swap cards based on their name.
* This is what actually changes the screen.
*/
private void swapCards(String card){
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, card);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Game();
}
});
}
}
If you are using netbeans , right click on your button under design tab and choose the event Mouse -> MouseClicked .
It will create a void that handles this event.
Enter your code that you want to ruen once the button is pressed .
I'm a beginner and doing my homework. My button is filling up the whole cell in the gridLayout. I've read about GridBagLayout but my book doesn't mention anything about it so I think there's just an error with my current code. The teacher has been trying to help me but we can't figure it out so I thought I would try here. Any help would be appreciated! Here is what I have:
package riddle;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Riddle implements ActionListener {
private final String LABEL_TEXT = "Why did the chicken cross the road?";
JFrame frame;
JPanel contentPane;
JLabel label, label1;
JButton button;
JButton button1;
private static int i;
public Riddle() {
/* Create and set up the frame */
frame = new JFrame(LABEL_TEXT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* Create a content pane with a GridLayout and empty borders */
contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 2, 10, 5));
/* Create and add label that is centered and has empty borders */
label = new JLabel("Why did the chicken cross the road?");
label.setAlignmentX(JButton.LEFT_ALIGNMENT);
label.setBorder(BorderFactory.createEmptyBorder(20, 50, 20, 50));
contentPane.add(label);
label1 = new JLabel(" ");
label1.setAlignmentX(JButton.LEFT_ALIGNMENT);
label1.setBorder(BorderFactory.createEmptyBorder(20, 50, 20, 50));
contentPane.add(label1);
/* Create and add button that is centered */
button = new JButton("Answer");
button.setAlignmentX(JButton.RIGHT_ALIGNMENT);
button.setActionCommand("Show Answer");
button.addActionListener(this);
contentPane.add(button);
/* Add content pane to frame */
frame.setContentPane(contentPane);
/* Size and then display the frame */
frame.pack();
frame.setVisible(true);
}
/** Handle button click action event
* pre:
* post: clicked button shows answer
*/
public void actionPerformed(ActionEvent event) {
String eventName = event.getActionCommand();
if (eventName.equals("Show Answer")) {
label1.setText("To get to the other side. ");
button.setText("Answer");
button.setActionCommand("Answer");
}
}
/**
* Create and show the GUI
*/
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
Riddle greeting = new Riddle();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
runGUI();
}
});
}
}
Here's a quote from the Swing tutorial about GridLayout:
A GridLayout object places components in a grid of cells. Each
component takes all the available space within its cell, and each cell
is exactly the same size.
If your book doesn't tell such an important thing, it's a bad book, and I would advise using the Swing tutorial instead. I'm astonished your teacher hasn't been able to tell you that.
If this behavior is not the one you want, choose another layout manager. The Swing tutorial has a guide for all standard ones.
I'm learning Java and GUI. I have some questions, and the first is if there are any major difference between creating a subclass of JFrame and an instance of JFrame. It seems like like a subclass is more powerful? I also wonder if it's necessary to use this code when creating a GUI:
Container contentPane = getContentPane();
contentPane.setLayot(new Flowlayout());
I add my GUI class, it's a simple test so far, to a task that I have to hand in. When a user has entered some text in the textfield and press the button to continue to the next step, how do I do to clear the frame and show a new content or is there a special way to do this is in Java? I guess there must be better to use the same window instead of creating a new!? Help id preciated! Thanks
// Gui class
import java.awt.FlowLayout; // layout
import java.awt.event.ActionListener; // listener
import java.awt.event.ActionEvent; // event
import javax.swing.JFrame; // windows properties
import javax.swing.JLabel; // row of text
import javax.swing.JTextField; // enter text
import javax.swing.JOptionPane; // pop up dialog
import javax.swing.JButton; // buttons
// import.javax.swing.*;
public class Gui extends JFrame {
private JLabel text1;
private JTextField textInput1;
private JTextField textInput2;
private JButton nextButton;
// constructor creates the window and it's components
public Gui() {
super("Bank"); // title
setLayout(new FlowLayout()); // set default layout
text1 = new JLabel("New customer");
add(text1);
textInput1 = new JTextField(10);
add(textInput1);
nextButton = new JButton("Continue");
add(nextButton);
// create object to handle the components (action listener object)
frameHandler handler = new frameHandler();
textInput1.addActionListener(handler);
nextButton.addActionListener(handler);
}
// handle the events (class inside another class inherits contents from class outside)
private class frameHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
String input1 = "";
// check if someone hits enter at first textfield
if(event.getSource() == textInput1){
input1 = String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, input1);
}
else if(event.getSource() == nextButton){
// ??
}
}
}
}
This small code might help you explain things :
import java.awt.event.*;
import javax.swing.*;
public class FrameDisplayTest implements ActionListener
{
/*
* Creating an object of JFrame instead of extending it
* has no side effects.
*/
private JFrame frame;
private JPanel panel, panel1;
private JTextField tfield;
private JButton nextButton, backButton;
public FrameDisplayTest()
{
frame = new JFrame("Frame Display Test");
// If you running your program from cmd, this line lets it comes
// out of cmd when you click the top-right RED Button.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel1 = new JPanel();
tfield = new JTextField(10);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
nextButton.addActionListener(this);
backButton.addActionListener(this);
panel.add(tfield);
panel.add(nextButton);
panel1.add(backButton);
frame.setContentPane(panel);
frame.setSize(220, 220);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (tfield.getText().length() > 0)
{
if (button == nextButton)
{
/*
* this will remove the first panel
* and add the new panel to the frame.
*/
frame.remove(panel);
frame.setContentPane(panel1);
}
else if (button == backButton)
{
frame.remove(panel1);
frame.setContentPane(panel);
}
frame.validate();
frame.repaint(); // prefer to write this always.
}
}
public static void main(String[] args)
{
/*
* This is the most important part ofyour GUI app, never forget
* to schedule a job for your event dispatcher thread :
* by calling the function, method or constructor, responsible
* for creating and displaying your GUI.
*/
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new FrameDisplayTest();
}
});
}
}
if you want to switch (add then remove) JComponents, then you have to
1) add/remove JComponents and then call
revalidate();
repaint()// sometimes required
2) better and easiest choice would be implements CardLayout
If your requirement is to make a wizard, a panel with next and prev buttons, and on clicking next/prev button showing some component. You could try using CardLayout.
The CardLayout manages two or more components (usually JPanel instances) that share the same display space. CardLayout let the user choose between the components.
How to Use CardLayout
If your class extends JFrame, you can do:
getContentPane().removeAll();