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?
Well, generally, users don’t like the size of the frame changing every time they hit enter. The frame should be designed to accomodate growth. So you would define the text area to have a given number of row and columns. Then you add the text area to a scroll pane and add the scrollpane to the frame. Then as data is changes scrollbars will appear or disappear as required.
If however you truly need to have a dynamically changing frame then you should use pack(). You can use:
where the Component is the source component of the ActionEvent, to find the Window to pack().