Reputation: 3026
I would like the following lay out...
The JTextArea should also have a scrollbar.
...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);
Upvotes: 1
Views: 334
Reputation: 168825
The FlowLayout
in a JPanel
for the JButton
instances is one way to go. You might also use a JToolBar
for the buttons.
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();
}
});
}
}
Upvotes: 2
Reputation: 205785
Use a nested layout: To a JPanel
having BorderLayout
,
JPanel
having FlowLayout
for the buttons to the NORTH
JScrollPane
for the JTextArea
to the CENTER
.Upvotes: 3
Reputation: 12092
Use a GridBagLayout
See this for more help : How to Use GridBagLayout
Now note that the JTextarea
to have a scrollbar have nothing to do with layouts.
See this for more help in that context : How to Use Scroll Panes
Upvotes: 2
Reputation: 678
You can either use a GridBagLayout as suggested, or nest multiple layout managers such as:
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);
Upvotes: 1