有很多事情可能会出错,如果没有更多代码,很难找出确切的问题......
有几件事突然想到...
- 使用适当的布局管理器,甚至是复合布局管理器
- 向 提供附加信息以
JTextArea
允许其定义可用空间,例如行和列
- 添加
JTextArea
到 aJScrollPane
以确保它不会突然占用更多空间然后实际可用
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout21 {
public static void main(String[] args) {
new TestLayout21();
}
public TestLayout21() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JPanel actions = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill= GridBagConstraints.HORIZONTAL;
actions.add(new JButton("Walk"), gbc);
actions.add(new JButton("Run"), gbc);
actions.add(new JButton("Jump"), gbc);
actions.add(new JButton("Eat"), gbc);
actions.add(new JButton("Drink"), gbc);
add(actions, BorderLayout.WEST);
add(new JProgressBar(), BorderLayout.SOUTH);
JTextArea textArea = new JTextArea(20, 40);
add(new JScrollPane(textArea));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}