I always have trouble with Java layouts, but the main thing bugging me now is that when the content changes, in particular changes it sizes, it's not laid out again properly. Take the example below:
package layouttest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class LayoutTestStart extends JFrame implements ActionListener
{
static JButton button= new JButton("Expand");
static JTextArea f = new JTextArea("A medium sized text");
static LayoutTestStart lst;
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
lst = new LayoutTestStart();
lst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel all = new JPanel();
button.addActionListener(lst);
all.add(button);
all.add(f);
lst.getContentPane().add(all);
lst.setVisible(true);
lst.pack();
}
@Override
public void actionPerformed(ActionEvent e)
{
f.setText(f.getText()+"\n"+f.getText());
// this doesn't work
f.invalidate();
// this does but it's cheating
// lst.pack();
}
}
The only way I get this to work is to call lst.pack(), but that's cheating since then each component should have a reference to it's JFrame, which gets messy when a component is a seperate class. What's the preferred way to let this example work?