codice:
import java.awt.*;
import javax.swing.*;
public class TestFrame extends JFrame {
public TestFrame() {
super("Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 200);
JTextArea textArea = new MyTextArea();
textArea.setText("Prima riga del testo\nSeconda riga\nTerza riga");
Box box = new Box(BoxLayout.Y_AXIS);
box.add(Box.createVerticalGlue());
box.add(textArea);
box.add(Box.createVerticalGlue());
JScrollPane scrollPane = new JScrollPane(box);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestFrame().setVisible(true);
}
});
}
}
class MyTextArea extends JTextArea {
public Dimension getMaximumSize() {
return getPreferredSize();
}
}
Prova a scrivere del testo, vedrai che la text area si espande (ma resta centrata) e se si espande troppo compaiono le scrollbar.