What would be the easiest way for creating a dialog:
in one window I'm giving data for envelope addressing, also set font type from list of sizes
when clicked OK, in the same window or in next window I get preview of how the envelope would look like with the given names, and used selected font size
It should look similarly to:
alt text http://img15.imageshack.us/img15/7355/lab10aa.gif
Should I use Jdialog? Or will JOptionPane will be enough? The next step will be to choose color of font and background so I must keep that in mind.
This should get you going.
class TestDialog extends JDialog {
private JButton okButton = new JButton(new AbstractAction("ok") {
public void actionPerformed(ActionEvent e) {
System.err.println("User clicked ok");
// SHOW THE PREVIEW...
setVisible(false);
}
});
private JButton cancelButton = new JButton(new AbstractAction("cancel") {
public void actionPerformed(ActionEvent e) {
System.err.println("User clicked cancel");
setVisible(false);
}
});
private JTextField nameField = new JTextField(20);
private JTextField surnameField = new JTextField();
private JTextField addr1Field = new JTextField();
private JTextField addr2Field = new JTextField();
private JComboBox sizes = new JComboBox(new String[] { "small", "large" });
public TestDialog(JFrame frame, boolean modal, String myMessage) {
super(frame, "Envelope addressing", modal);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
getContentPane().add(mainPanel);
JPanel addrPanel = new JPanel(new GridLayout(0, 1));
addrPanel.setBorder(BorderFactory.createTitledBorder("Receiver"));
addrPanel.add(new JLabel("Name"));
addrPanel.add(nameField);
addrPanel.add(new JLabel("Surname"));
addrPanel.add(surnameField);
addrPanel.add(new JLabel("Address 1"));
addrPanel.add(addr1Field);
addrPanel.add(new JLabel("Address 2"));
addrPanel.add(addr2Field);
mainPanel.add(addrPanel);
mainPanel.add(new JLabel(" "));
mainPanel.add(sizes);
JPanel buttons = new JPanel(new FlowLayout());
buttons.add(okButton);
buttons.add(cancelButton);
mainPanel.add(buttons);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
public String getAddr1() {
return addr1Field.getText();
}
// ...
}
Result:
If you need to use JOptionPane :
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
private static JTextField nameField = new JTextField(20);
private static JTextField surnameField = new JTextField();
private static JTextField addr1Field = new JTextField();
private static JTextField addr2Field = new JTextField();
private static JComboBox sizes = new JComboBox(new String[] { "small", "medium", "large", "extra-large" });
public Main(){
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
getContentPane().add(mainPanel);
JPanel addrPanel = new JPanel(new GridLayout(0, 1));
addrPanel.setBorder(BorderFactory.createTitledBorder("Receiver"));
addrPanel.add(new JLabel("Name"));
addrPanel.add(nameField);
addrPanel.add(new JLabel("Surname"));
addrPanel.add(surnameField);
addrPanel.add(new JLabel("Address 1"));
addrPanel.add(addr1Field);
addrPanel.add(new JLabel("Address 2"));
addrPanel.add(addr2Field);
mainPanel.add(addrPanel);
mainPanel.add(new JLabel(" "));
mainPanel.add(sizes);
String[] buttons = { "OK", "Cancel"};
int c = JOptionPane.showOptionDialog(
null,
mainPanel,
"My Panel",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
buttons,
buttons[0]
);
if(c ==0){
new Envelope(nameField.getText(), surnameField.getText(), addr1Field.getText()
, addr2Field.getText(), sizes.getSelectedIndex());
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
You will need to use JDialog. No point messing about with JOptoinPane - it's not meant for gathering more than a simple string. Additionally, use either MigLayout, TableLayout, or JGoodies forms - it will help you get a nice layout that's easy to code.
If it is allowed to use a GUI builder I would recommend you IntelliJ IDEA's
You can create something like that in about 5 - 10 mins.
If that's not possible ( maybe you want to practice-learn-or-something-else ) I would use a JFrame instead ) with CardLayout
Shouldn't be that hard to do.
You can use JOptionPane. You can add any Swing component to it.
Create a panel with all the components you need except for the buttons and then add the panel to the option pane. The only problem with this approach is that focus will be on the buttons by default. To solve this problem see the solution presented by Dialog Focus.
Related
So I am designing a chatroom and before I can read up on sockets I need to finish up this GUI. Basically I am mostly using TextDemo as my guide. I like how it displays so I figured it'd be an easy spot to start with my code. In my code it breaks whenever I try to put in:
input.addActionListener(this);
When I comment out that line it goes back to displaying/running perfectly. Due to my errors, it looks like I'm putting it in the wrong location. I've tried moving it around a bit but I don't seem to have the problem solving skills to fix this yet. Can someone help correct me and explain what I am doing wrong here?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JPanel implements ActionListener
{
private final static String newline = "\n";
///// CREATING THE GUI /////
JFrame frame = new JFrame("Chatroom");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JPanel chatpanel = new JPanel();
JPanel inputpanel = new JPanel();
JPanel sendpanel = new JPanel();
JTextArea chat = new JTextArea(19, 49);
JTextArea input = new JTextArea(3, 40);
JScrollPane chatscroll = new JScrollPane(chat,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JScrollPane inputscroll = new JScrollPane(input,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JButton connectbutton = new JButton("Connect");
JButton disconnectbutton = new JButton("Disconnect");
JButton send = new JButton("Send");
JLabel label = new JLabel();
///// GUI CONSTRUCTOR /////
public GUI()
{
chatroomGUI();
}
public void chatroomGUI()
{
///// GUI DISPLAY /////
frame.setVisible(true);
frame.setSize(800, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setBackground(Color.GRAY);
panel2.setBackground(Color.lightGray);
chatpanel.setBackground(Color.lightGray);
inputpanel.setBackground(Color.lightGray);
sendpanel.setBackground(Color.lightGray);
///// ACTION LISTENER /////
//input.addActionListener(this);
chat.setEditable(false);
chat.setFont(new Font("Dialog", Font.PLAIN, 12));
chat.setLineWrap(true);
chat.setWrapStyleWord(true);
input.setFont(new Font("Fialog", Font.PLAIN, 12));
input.setLineWrap(true);
input.setWrapStyleWord(true);
sendpanel.setLayout(new BorderLayout(0, 0));
sendpanel.setPreferredSize(new Dimension(95, 50));
chatpanel.setLayout(new FlowLayout());
chatpanel.setPreferredSize(new Dimension(565, 320));
///// ADD AREA /////
chatpanel.add(chatscroll);
inputpanel.add(inputscroll);
inputpanel.add(sendpanel, BorderLayout.EAST);
sendpanel.add(send, BorderLayout.CENTER);
panel.add(connectbutton);
panel.add(disconnectbutton);
panel.add(label);
panel2.add(chatpanel);
panel2.add(inputpanel);
frame.add(panel, BorderLayout.WEST);
frame.add(panel2);
}
///// ACTION PERFORMED /////
/*The following will take any text that is typed inside of
the "input" area and display it in the "chat" screen area.*/
public void actionPerformed(ActionEvent evt)
{
String text = input.getText();
chat.append(text + newline);
input.selectAll();
chat.setCaretPosition(chat.getDocument().getLength());
}
}
Note: My main is in another class. That code just simply looks like:
public class Chatroom
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GUI();
}
});
}
}
JTextArea does not support the ActionListener API, so it does not have a addActionListener method. You should consult the JavaDocs and tutorials first
Depending on what you are trying to do, you might consider using a DocumentListener or a DocumentFilter or use the key bindings API, for example
I have created a JOptionPane that pulls up a custom JPanel that takes in 2 JTextField's & A JComboBox. Upon hitting Save I would like to have the 3 values stored into global variables but have little experience with JOptionPane and making this work I have the following method that instantiates it:
public void add() {
JOptionPane.showOptionDialog(null,
getPanel(),
"Add A Shipment ",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE, null,
new String[]{"Add Shipment", "Cancel"},"default");
}
and the method that creates the custom popup
#SuppressWarnings("unchecked")
private JPanel getPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout (8,8));
//NORTH PANEL
JPanel name = new JPanel();
name.setLayout(new BorderLayout(8,8));
name.add(new JLabel("Title: "), BorderLayout.WEST);
JTextField titleIn = new JTextField();
titleIn.setPreferredSize(new Dimension(150, 20));
name.add(titleIn, BorderLayout.EAST);
//CENTER PANEL
JPanel trackID = new JPanel();
trackID.setLayout(new BorderLayout(8,8));
trackID.add(new JLabel("Tracking #: "), BorderLayout.WEST);
JTextField trackIn = new JTextField();
trackIn.setPreferredSize(new Dimension(150, 20));
trackID.add(trackIn, BorderLayout.EAST);
//BOTTOM PANEL
JPanel ship = new JPanel();
ship.setLayout(new BorderLayout(8,8));
String[] services = { "USPS", "UPS", "FedEx", "DHL" };
#SuppressWarnings("rawtypes")
JComboBox service = new JComboBox(services);
service.setSelectedIndex(0);
ship.add(service);
panel.add(name, BorderLayout.NORTH);
panel.add(trackID, BorderLayout.CENTER);
panel.add(ship, BorderLayout.SOUTH);
return panel;
}
Any easy way of assigning these as variables with the given code?
Thanks
You need to create a class that extends JPanel, store the controls (the two JTextFields and the JComboBox) as fields of this class, pass an instance of this class to JOptionPane.showOptionDialog() and retrieve the values from the fields after the call.
I am working on a semester project that I have and I was wondering if it was possible to store 3-4 JPanels instead one single "main" JPanel. The reason for me asking this is because I a trying to make a GUI checkbook program and my checkbook has 7 buttons that should open a new window once I click on it. To switch between each window I'm going to have to use the CardLayout, but my understand of the CardLayout is that I can only assign one single JPanel to that card so I can't assign multiple JPanels to a single Card layout so when the user clicks on a different card 3-4 different JPanels appear.
The reason that I am asking this is because I asked for help earlier and received help for creating my first window in this project, it produces the output I want PERFECTLY, but uses more than 1 JPanel in doing so. Since this prevents me from continuing on to the other steps of my 7 GUI Windows, I am stuck.
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class checkbook extends JPanel implements ActionListener {
private static final String title = "Use The Buttons Below To Manage Transactions";
private static final String[] bottomButtons = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
static JButton Button[] = new JButton[8];
static ActionListener AL = new checkbook();
public checkbook() {
JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 18));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JTextField textfield = new JTextField();
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(4));
accountBalancePanel.add(new JLabel("Balance:"));
textfield = new JTextField("0.0", 10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
accountBalancePanel.add(textfield);
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
southBtnPanel.add(Button[i]);
Button[i].addActionListener(AL);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(100, 100))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
checkbook mainPanel = new checkbook();
JFrame frame = new JFrame("Checkbook");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button[7]) {
System.exit(0);
}
}
}
Credit goes to Hovercraft Full Of Eels for showing me the above example
If there is anything that is unclear about my question, please ask and I will do the best I can to fix it.
Here is what the code produces:
http://i.stack.imgur.com/WY0c3.png
this is my first time here.
I was writing a GUI-driven program which would allow me to perform Caesar's cipher on .txt files.
However, before I could add the ActionListeners and ChangeListeners I decided to test the GUI. Here is what I got:
Here is the code:
package implementation;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Frame extends JFrame{
public Frame(){
super("Caesar[E]");
this.setVisible(true);
this.setLocationRelativeTo(null);
/*Adding the options to GUI*/
factor.setPreferredSize(new Dimension(30,30));
JToolBar toolbar = new JToolBar();
radio.add(encrypt);
radio.add(decrypt);
toolbar.add(encrypt);
toolbar.add(decrypt);
toolbar.add(factor);
toolbar.setFloatable(false);
/*Adding the JTextArea for input*/
Box inputBound = Box.createHorizontalBox();
Box inputBound_text = Box.createVerticalBox();
Box inputBound_buttons = Box.createVerticalBox();
inputScroll.add(input);
inputScroll.setEnabled(true);
input.setEditable(true);
inputScroll.setBorder(BorderFactory.createTitledBorder("Text/File for Encryption/" +
"Decryption"));
inputBound_text.add(inputScroll);
inputBound_buttons.add(openFile);
inputBound_buttons.add(cancelFileInput);
inputBound.add(inputBound_text);
inputBound.add(Box.createHorizontalStrut(25));
inputBound.add(inputBound_buttons);
/*Adding JTextArea for output*/
Box outputBound = Box.createHorizontalBox();
Box outputBound_text = Box.createVerticalBox();
Box outputBound_buttons = Box.createVerticalBox();
outputScroll.add(output);
output.setEditable(true);
outputScroll.setBorder(BorderFactory.createTitledBorder("Text After Encryption" +
"/Decryption"));
outputBound_text.add(outputScroll);
outputBound_buttons.add(saveFile);
outputBound_buttons.add(send);
outputBound.add(outputBound_text);
outputBound.add(Box.createHorizontalStrut(25));
outputBound.add(outputBound_buttons);
outputBound.setSize(150, 200);
/*Adding JButton for performing the action*/
this.add(performAction,BorderLayout.SOUTH);
/*Adding the components to the Frame*/
Box outerBox = Box.createVerticalBox();
outerBox.add(toolbar,BorderLayout.NORTH);
outerBox.add(inputBound);
outerBox.add(outputBound);
this.add(outerBox);
this.setSize(500, 700);
}
boolean isFileInput = false;
boolean isEncrypt = true;
JButton performAction = new JButton("Encrypt!");
JButton openFile = new JButton("Open a File");
JButton cancelFileInput = new JButton("Cancel File Input");
JButton saveFile = new JButton("Save File");
JButton send = new JButton("Send");
JTextArea input = new JTextArea();
JTextArea output = new JTextArea();
JFileChooser chooser = new JFileChooser();
JScrollPane inputScroll = new JScrollPane();
JScrollPane outputScroll = new JScrollPane();
ButtonGroup radio = new ButtonGroup();
JRadioButton encrypt = new JRadioButton("Encrypt",true);
JRadioButton decrypt = new JRadioButton("Decrypt",false);
JSpinner factor = new JSpinner(new SpinnerNumberModel(1,1,26,1));
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new Frame();
}
});
}
}
Can you please tell me how I can solve the problems as shown in the image?
I know I can use setPreferredSize() but how do I make sure that I enter the correct dimension without trial-and-error?
I like the SpringLayout, it is very flexible and there is very not a lot that it can't do. Especially you will not need to care about setPreferredSize anymore. Just search for it, there are enough resources out there.
SpringLayout allows you to define the size of elements relative to others - so for example, you can make sure the buttons will look the same.
I would recommend MiGLayout as LayoutManager. Things like that are easy in MiGLayout
Trial-and-error is never a good way to get the layout you want. Instead, use the JTextArea constructor that lets you say how many rows and columns you want.
JTextArea(int rows, int columns)
JTextArea will calculate a good preferred size for when you pack() the window, and you won't need setSize().
Edit: You said, "JTextArea is inactive. I can't enter text in it."
Instead of add(), use setViewportView():
inputScroll.setViewportView(input);
...
outputScroll.setViewportView(output);
...
In situations like these, I like to divide my application into areas of responsibility. This keeps the code clean and self contained, allowing me to replace sections of it if/and when required, without adversely effect the rest of the application.
It also means that you can focus on the individual requirements of each section.
With complex layout, it's always better (IMHO) to use compounding containers with separate layout managers, it reduces the complexity and potential for strange cross over behavior.
public class BadLayout07 {
public static void main(String[] args) {
new BadLayout07();
}
public BadLayout07() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MasterPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MasterPane extends JPanel {
public MasterPane() {
EncryptSettings encryptSettings = new EncryptSettings();
InputPane inputPane = new InputPane();
OutputPane outputPane = new OutputPane();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(encryptSettings, gbc);
gbc.gridy++;
gbc.weighty = 1;
gbc.fill = gbc.BOTH;
add(inputPane, gbc);
gbc.gridy++;
add(outputPane, gbc);
}
}
public class EncryptSettings extends JPanel {
private JRadioButton encrypt;
private JRadioButton decrypt;
private JSpinner factor;
public EncryptSettings() {
encrypt = new JRadioButton("Encrypt");
decrypt = new JRadioButton("Decrypt");
ButtonGroup bg = new ButtonGroup();
bg.add(encrypt);
bg.add(decrypt);
factor = new JSpinner(new SpinnerNumberModel(new Integer(1), new Integer(1), null, new Integer(1)));
setLayout(new FlowLayout(FlowLayout.LEFT));
add(encrypt);
add(decrypt);
add(factor);
}
}
public class InputPane extends JPanel {
private JTextArea input;
private JButton open;
private JButton close;
public InputPane() {
setBorder(new TitledBorder("Source Text"));
input = new JTextArea();
open = new JButton("Open");
close = new JButton("Close");
JPanel tb = new JPanel(new FlowLayout(FlowLayout.LEFT));
tb.add(open);
tb.add(close);
setLayout(new BorderLayout());
add(tb, BorderLayout.NORTH);
add(new JScrollPane(input));
}
}
public class OutputPane extends JPanel {
private JTextArea output;
private JButton save;
private JButton send;
public OutputPane() {
setBorder(new TitledBorder("Encrypted Text"));
output = new JTextArea();
output.setEditable(false);
save = new JButton("Save");
send = new JButton("Send");
JPanel tb = new JPanel(new FlowLayout(FlowLayout.LEFT));
tb.add(save);
tb.add(send);
setLayout(new BorderLayout());
add(tb, BorderLayout.NORTH);
add(new JScrollPane(output));
}
}
}
I've not interconnect any of the functionality, but it is a simple case of providing appropriate setters and getters as required, as well appropriate event listeners.
I just started to learn swing by myself, I'm little bit confused why my event does not work here:
1.I'm trying to delete everything from my panel if the user click menu bar -> load but it force me to change the panel to final because i'm using it inside the event!
2.I have defined new panel in my event and defined two more container to add to that panel and then add it to the main frame but it seems nothing happening!
Please help me if you can find out what is wrong.
Sorry in advance for messy code.
I appreciate any hints.
public class SimpleBorder {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
myFrame frame = new myFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MyFrame extends JFrame {
public MyFrame()
{
setSize(500,500);
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel label = new JLabel("my name is bernard...");
Color myColor = new Color(10, 150, 80);
panel.setBackground(myColor);
label.setFont(new Font("Serif", Font.PLAIN, 25));
Dimension size = label.getPreferredSize();
Insets insets = label.getInsets();
label.setBounds(85+insets.left, 120+insets.top , size.width, size.height);
panel.add(label);
JMenuBar menu = new JMenuBar();
setJMenuBar(menu);
JMenu col = new JMenu("Collection");
menu.add(col);
JMenu help = new JMenu("Help");
menu.add(help);
Action loadAction = new AbstractAction("Load")//menu item exit goes here
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event)
{
JTextArea text = new JTextArea(10, 40);
JScrollPane scrol1 = new JScrollPane(text);
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
JScrollPane scrol2 = new JScrollPane(list);
JPanel panel2 = new JPanel(new BorderLayout());
panel2 = new JPanel(new GridLayout(1, 2 ));
panel2.add(scrol1,BorderLayout.WEST);
panel2.add(scrol2,BorderLayout.EAST);
add(panel2);
}
};
JMenuItem load = new JMenuItem(loadAction);
col.add(load);
add(panel);
}
}
Call revalidate()/repaint() on your JFrame instance after adding the new panel:
JPanel panel2 = new JPanel(new BorderLayout());
// panel2 = new JPanel(new GridLayout(1, 2 ));//why this it will overwrite the above layout
panel2.add(scrol1,BorderLayout.WEST);
panel2.add(scrol2,BorderLayout.EAST);
add(panel2);
revalidate();
repaint();
Also call pack() on you JFrame instance so all components are spaced by the layoutmanager. As said in a comment dont extend the JFrame class, create a variable of the frame and initiate all that you need on the frames instance, and dont set a layout to null, unless you love hard work :P
Alternatively as mentioned by mKorbel, a CardLayout may be more what you want, it will allow you to use a single JPanel and switch between others/new ones:
JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
//add card panel to frame
frame.add(cards);
//swap cards
CardLayout cl = (CardLayout)(cards.getLayout());//get layout of cards from card panel
cl.show(cards, TEXTPANEL);//show another card