February 4, 2011

Simple sample to replace the contents of a content pane in Swing


package swingTest;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main
{
static JFrame frame;

static JPanel firstPanel;
static JPanel secondPanel;

static JLabel firstPanelLabel;
static JButton firstPanelButton;

static JLabel secondPanelLabel;

/**
* @param args
*/
public static void main(String[] args)
{
createObjects();

firstPanel.add(firstPanelLabel);
firstPanel.add(firstPanelButton);

firstPanelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
Container contentPane = frame.getContentPane();
contentPane.remove(firstPanel); // Required for new stuff to appear
contentPane.add(secondPanel); // Required for new stuff to appear; this _is_ the new stuff, after all
((JPanel) contentPane).revalidate(); // Required for new stuff to appear
contentPane.repaint(); // Without this, old stuff isn't removed before new stuff is painted and is still visible underneath
}
});

secondPanel.add(secondPanelLabel);

frame.addWindowListener(new ExitListener());
frame.getContentPane().add(firstPanel);
frame.setVisible(true);
}

public static void createObjects()
{
frame = new JFrame();
frame.setSize(500, 500);

firstPanel = new JPanel();
firstPanel.setLayout(new FlowLayout());
firstPanelLabel = new JLabel("first label");
firstPanelButton = new JButton("first button");

secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout());
secondPanelLabel = new JLabel("second label");
}
}

class ExitListener extends WindowAdapter
{
public void windowClosing(WindowEvent event)
{
System.exit(0);
}
}

No comments:

Post a Comment