我应该使用什么layoutManager?

时间:2016-03-13 16:33:56

标签: java swing layout-manager

我正在创建一个测试系统托盘的应用程序,但我不知道应该使用什么layoutmanager来使它看起来像这样:

enter image description here

我遇到的问题是我无法垂直对齐textField中的文本,因此我想到了这样的事情:“为什么不使用layoutmanagers并使其与消息一起扩展。”你怎么看待这个?

3 个答案:

答案 0 :(得分:4)

简单:使用布局组合。 BorderLayout为整体,JLabel位于PAGE_START位置,JScrollPane / JTextArea位于CENTER位置。还有一个FlowLayout.RIGHT,在PAGE_END位置使用JPanel保存JButton。

如,

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;

@SuppressWarnings("serial")
public class FooPanel extends JPanel {
    private static final String PROMPT = "This is prompt text:";
    private static final int TA_ROWS = 10;
    private static final int TA_COLS = 30;
    private static final int GAP = 5; 

    private JTextArea textArea = new JTextArea(TA_ROWS, TA_COLS);

    public FooPanel() {
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        bottomPanel.add(new JButton("Submit"));

        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new BorderLayout(GAP, GAP));
        add(new JLabel(PROMPT), BorderLayout.PAGE_START);
        add(new JScrollPane(textArea), BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private static void createAndShowGui() {
        FooPanel mainPanel = new FooPanel();

        JFrame frame = new JFrame("FooPanel");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}

或者,底部JPanel可以使用BoxLayout和水平胶水按下按钮:

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
        bottomPanel.add(Box.createHorizontalGlue());
        bottomPanel.add(new JButton("Submit"));

在模态对话框中使用上述示例,并展示如何在JTextArea中包装行:

import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class FooPanel extends JPanel {
    private static final int TA_ROWS = 10;
    private static final int TA_COLS = 30;
    private static final int GAP = 5;

    private JTextArea textArea = new JTextArea(TA_ROWS, TA_COLS);

    public FooPanel(String prompt) {
        textArea.setWrapStyleWord(true);
        textArea.setLineWrap(true);

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
        bottomPanel.add(Box.createHorizontalGlue());
        bottomPanel.add(new JButton(new SendAction("Send", KeyEvent.VK_S)));

        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new BorderLayout(GAP, GAP));
        add(new JLabel(prompt), BorderLayout.PAGE_START);
        add(new JScrollPane(textArea), BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    public String getText() {
        return textArea.getText();
    }

    private class SendAction extends AbstractAction {
        public SendAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic); // alt-key shortcut mnemonic
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // simply dispose of this window
            Window win = SwingUtilities.getWindowAncestor(FooPanel.this);
            win.dispose();
        }
    }

    private static void createAndShowGui() {
        String prompt = "Enter the text that is to be displayed in the tray:";
        final FooPanel mainPanel = new FooPanel(prompt);

        final JFrame frame = new JFrame("FooPanel");
        final JTextArea displayArea = new JTextArea(TA_ROWS, TA_COLS);
        displayArea.setFocusable(false);
        displayArea.setEditable(false);
        displayArea.setWrapStyleWord(true);
        displayArea.setLineWrap(true);

        final JDialog dialog = new JDialog(frame, "Enter Text", ModalityType.APPLICATION_MODAL);
        dialog.add(mainPanel);
        dialog.pack();

        JPanel framePanel = new JPanel(new BorderLayout());
        framePanel.add(new JScrollPane(displayArea), BorderLayout.CENTER);
        framePanel.add(new JPanel() {
            {
                add(new JButton(new AbstractAction("Show Dialog") {
                    {
                        putValue(MNEMONIC_KEY, KeyEvent.VK_S);
                    }

                    public void actionPerformed(ActionEvent e) {
                        dialog.setLocationRelativeTo(frame);
                        dialog.setVisible(true);

                        String text = mainPanel.getText();
                        displayArea.setText(text);
                    };
                }));
            }
        }, BorderLayout.PAGE_END);

        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(framePanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}

答案 1 :(得分:3)

您可以使用BorderLayout

我能想出的最简单的程序是满足您所需的定位要求:

public class PutText extends JFrame {

    public PutText() {
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        initGUI();
        pack();

        setLocationRelativeTo(null);
    }

    private void initGUI() {
        Container cp = getContentPane();
        cp.setLayout(new BorderLayout(0, 10));

        JPanel upper = new JPanel(new BorderLayout());
        JPanel lower = new JPanel(new BorderLayout());

        cp.add(upper, BorderLayout.PAGE_START);
        cp.add(lower, BorderLayout.PAGE_END);

        JLabel lbl = new JLabel("Put the text you want the tray to show.");
        JTextArea ta = new JTextArea();
        ta.setLineWrap(true);
        JButton btn = new JButton("Send");

        upper.add(lbl, BorderLayout.LINE_START);
        cp.add(ta, BorderLayout.CENTER);
        lower.add(btn, BorderLayout.LINE_END);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new PutText().setVisible(true);
        });
    }

}

请注意,您需要添加空边框以类似于您要创建的程序。

答案 2 :(得分:0)

我使用第一个GridBagLayout的最好的布局管理器之一,它更灵活地设置调色板的位置(Swing容器,控件)

public class GridBagLayoutSample {
JFrame frame = new JFrame("GridBagSample");
JPanel panel = new JPanel();
JButton btn1 = new JButton("One");
JButton btn2 = new JButton("Two");
JButton btn3 = new JButton("Three");
JButton btn4 = new JButton("Four");
JButton btn5 = new JButton("Five");
public GridBagLayoutSample(){
panel.setLayout(new GridBagLayout());
GridBagConstraints a = new GridBagConstraints();
a.fill = GridBagConstraints.HORIZONTAL;
a.insets = new Insets(3,3,3,3);

a.gridx = 0;
a.gridy = 0;
panel.add(btn1, a);

a.gridx = 1;
a.gridy = 0;
panel.add(btn2, a);

a.gridx = 0;
a.gridy = 1;
panel.add(btn3, a);


a.gridx = 1;
a.gridy = 1;
panel.add(btn4, a);


frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setPreferredSize(new Dimension(500,500));

panel.setSize(300,300);
}
public static void main(String[] args) {
GridBagLayoutSample a = new GridBagLayoutSample();
}

查看此文档。它在这里解释了GridBagLayout是如何使用的。这是我使用的最佳布局,因为您可以找到您想要的任何位置。使用象限作为指导,因此不会混淆定位您的组件希望这会有所帮助。

https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html