[英]Java Swing Layout
I would like the following lay out... 我希望以下布局...
The JTextArea should also have a scrollbar . JTextArea还应该具有一个滚动条 。
...for the code below. ...下面的代码。
JPanel jp = new JPanel(); One = new JButton("One"); Two = new JButton("Two"); TestOutput = new JTextArea(); jp.add(One); jp.add(Two); jp.add(TestOutput);
Use a nested layout: To a JPanel
having BorderLayout
, 使用嵌套布局:对于具有
BorderLayout
的JPanel
,
JPanel
having FlowLayout
for the buttons to the NORTH
JPanel
具有FlowLayout
为按钮在NORTH
JScrollPane
for the JTextArea
to the CENTER
. JTextArea
的JScrollPane
到CENTER
。 Use a GridBagLayout 使用GridBagLayout
See this for more help : How to Use GridBagLayout 请参阅此以获得更多帮助: 如何使用GridBagLayout
Now note that the JTextarea
to have a scrollbar have nothing to do with layouts. 现在请注意,具有滚动条的
JTextarea
与布局无关。
See this for more help in that context : How to Use Scroll Panes 在这种情况下,请参阅此处以获取更多帮助: 如何使用滚动窗格
关键字是分层的-在JPanel上具有JPanel。
The FlowLayout
in a JPanel
for the JButton
instances is one way to go. JPanel
用于JButton
实例的FlowLayout
是一种解决方法。 You might also use a JToolBar
for the buttons. 您可能还对按钮使用了
JToolBar
。
import java.awt.*;
import javax.swing.*;
class ButtonsAndTextAreaLayout {
ButtonsAndTextAreaLayout() {
JPanel gui = new JPanel(new BorderLayout(5,5));
// use a toolbar for the buttons
JToolBar tools = new JToolBar();
// use firstWordLowerCase for attribute/method names.
JButton one = new JButton("One");
JButton two = new JButton("Two");
tools.add(one);
tools.add(two);
// provide hints as to how large the text area should be
JTextArea testOutput = new JTextArea(5,20);
gui.add(tools, BorderLayout.NORTH);
gui.add(new JScrollPane(testOutput), BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonsAndTextAreaLayout();
}
});
}
}
You can either use a GridBagLayout as suggested, or nest multiple layout managers such as: 您可以按照建议使用GridBagLayout,也可以嵌套多个布局管理器,例如:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
JButton oneButton = new JButton("One");
JButton twoButton = new JButton("Two");
buttonPanel.add(oneButton);
buttonPanel.add(twoButton);
JTextArea output = new JTextArea();
JScrollPane scrollPane = new JScrollPane(output);
frame.add(buttonPanel, BorderLayout.NORTH);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.