Re: JFrame help please?
A Watcher wrote:
Knute Johnson wrote:
A Watcher wrote:
My problem was that I couldn't change the contents. Filling it
initially worked fine.
So do you have it working now?
Just for my curiosity why do you change the content pane rather than
adding or removing components or containers?
I'm not an expert at Java yet. Can you point me to some examples of
doing that?
Here is a very simple example of adding and removing components and also
making a component visible or not. Different layout managers will
respond differently to having components added or removed but if you
call validate, the layout manager will layout the components again.
Often one will set components as enabled or disabled to indicate to a
user that a particular feature is or is not available. This is often
done with menus.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test3 extends JPanel {
JLabel north,center;
public test3() {
setLayout(new BorderLayout());
center = new JLabel("Center",JLabel.CENTER);
add(center,BorderLayout.CENTER);
north = new JLabel("North",JLabel.CENTER);
add(north,BorderLayout.NORTH);
JButton south = new JButton("Toggle Center");
south.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (center.isShowing())
center.setVisible(false);
else
center.setVisible(true);
}
});
add(south,BorderLayout.SOUTH);
JButton west = new JButton("Remove North");
west.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (north.isShowing()) {
remove(north);
validate();
}
}
});
add(west,BorderLayout.WEST);
JButton east = new JButton("Add North");
east.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (!north.isShowing()) {
add(north,BorderLayout.NORTH);
validate();
}
}
});
add(east,BorderLayout.EAST);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test3 t3 = new test3();
f.add(t3);
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
--
Knute Johnson
email s/nospam/knute/