我有一个简单的问题,但我没有找到好的解决方案。我有一个JFrame
组件位于 SOUTH
, NORTH
, EAST
,和CENTER
。上CENTER
是我的问题。在中心我有一个JPanel
与 Borderlayout
和 2 JTextAreas
(一个在 NORTH
上,一个在 CENTER
上)。
我希望第一个面板始终从面板顶部开始,并最大程度地拉伸(stretch)(如果需要)到面板中间,而不是更多。第二个区域应从第一个区域的末尾开始。如果两个文本区域之一太大,则应该出现 JScrollPane
。
实现这一点的最佳方法是什么?我应该为面板使用其他布局吗?
这是我的小执行示例:
public class myGUI {
public static void main(String[] args) {
new myGUI();
}
public myGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
//Add Content at South, West and North....
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
centerPanel.add(new JScrollPane(new JTextArea("AREA")), BorderLayout.NORTH);
centerPanel.add(new JScrollPane(new JTextArea("AREA2")), BorderLayout.CENTER);
frame.add(centerPanel);
frame.setVisible(true);
}
}
中心面板的可能场景:
在 @Hovercraft Full Of Eels 的帮助下解决方案
public class MyGUI {
public static void main(String[] args) {
new MyGUI();
}
private static GridBagConstraints constraint = new GridBagConstraints();
public MyGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(new JLabel("NORTH!"), BorderLayout.NORTH);
frame.add(new JLabel("EAST!"), BorderLayout.EAST);
frame.add(new JLabel("SOUTH!"), BorderLayout.SOUTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
changeConstraint(0,0);
JTextArea text1 = createTextArea("11111111111111");
centerPanel.add(text1, constraint);
changeConstraint(0,1);
JTextArea text2 = createTextArea("2222222222222");
centerPanel.add(text2, constraint);
JScrollPane scroll = new JScrollPane(centerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
frame.add(scroll, BorderLayout.CENTER);
frame.setVisible(true);
}
/**
* Create a Gridbag Constraint
* @param text
* @return
*/
private void changeConstraint(int gridx, int gridy){
constraint.anchor = GridBagConstraints.FIRST_LINE_START;
constraint.fill = GridBagConstraints.HORIZONTAL;
constraint.weighty = 0;
constraint.weightx = 1.0;
constraint.gridx = gridx;
constraint.gridy = gridy;
}
/**
* Create a Textarea
* @param text
* @return
*/
private JTextArea createTextArea(String text){
JTextArea textarea = new JTextArea(text);
textarea.setWrapStyleWord(true);
textarea.setLineWrap(true);
return textarea;
}
}
最佳答案
一种可能性:考虑创建一个使用 GridBagLayout 的 JPanel,并将两个 JTextArea 添加到此 JPanel,确保将它们的 Weightx 设置为 0,并将 Weighty 设置为非零值,例如 1.0。然后将该 JPanel 放入 JScrollPane 中,并将 JScrollPane 放入 GUI 中。
关于java - 边框布局中的文本区域最大尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23459624/