我想沿着側頂部以下鋪陳......的Java Swing佈局
- Jbutton將海誓山盟。
- JTextArea應該是下的的按鈕。
JTextArea還應該有一個滾動條。
...代碼如下。JPanel jp = new JPanel(); One = new JButton("One"); Two = new JButton("Two"); TestOutput = new JTextArea(); jp.add(One); jp.add(Two); jp.add(TestOutput);
我想沿着側頂部以下鋪陳......的Java Swing佈局
JTextArea還應該有一個滾動條。
...代碼如下。
JPanel jp = new JPanel();
One = new JButton("One");
Two = new JButton("Two");
TestOutput = new JTextArea();
jp.add(One);
jp.add(Two);
jp.add(TestOutput);
關鍵字是分層 - 在JPanel上有JPanel。
這對我有效。謝謝彼得! –
這個例子有一些方面非常好,而其他方面則不太好。例如。 +1'new JTextArea(4,35);',-1'setMinimumSize' /'setSize'。 (第一個使第二個冗餘。)整體+1。請考慮以後再編譯一個可編譯/可運行的示例 - 它通常只需要一些額外的LOC。 –
如需更多幫助,請參閱本:How to Use GridBagLayout
現在注意,JTextarea
有一個滾動條都無關佈局。 How to Use Scroll Panes
我儘快轉而反對這個答案,因爲我看到'GridBagLayout'。雖然GBL功能強大,但編寫和使用和調試的難度要比嵌套佈局要長(對於這種簡單的GUI佈局)。 OTOH包括J7文檔的鏈接和2個指向教程的鏈接,其中一個關於我們似乎都同意的問題(滾動窗格)。 +1 –
使用嵌套佈局:
在這方面更多的幫助,請參閱本要爲BorderLayout
一個JPanel
,
JPanel
有FlowLayout
到NORTH
JScrollPane
爲JTextArea
至CENTER
。您可以使用的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);
的FlowLayout
在JPanel
的JButton
實例是一條路可走。您也可以使用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();
}
});
}
}
請學習Java命名約定並嚴格遵守 – kleopatra