John R
John R

Reputation: 3026

Java Swing Layout

I would like the following lay out...

Upvotes: 1

Views: 334

Answers (5)

勿绮语
勿绮语

Reputation: 9320

The keyword is layering - having JPanel on JPanel.

Upvotes: 2

Andrew Thompson
Andrew Thompson

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.

Buttons and TextArea Layout Buttons and TextArea Layout w. toolbar on RHS

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

trashgod
trashgod

Reputation: 205785

Use a nested layout: To a JPanel having BorderLayout,

  • add a JPanel having FlowLayout for the buttons to the NORTH
  • and a JScrollPane for the JTextArea to the CENTER.

Upvotes: 3

COD3BOY
COD3BOY

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

Jon
Jon

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

Related Questions