将JTextArea放在特定位置

时间:2016-06-24 13:03:25

标签: java swing layout layout-manager jtextarea

我想知道,我怎么能把我的JTextArea放在我的程序中的一些按钮上...为了告诉你我如何订购这个,我在GUI中做了一个例子。 / p>

图片示例:

enter image description here

基本上,我想把它们放在按钮上,就像在例子中一样。 我尝试将JPanel作为flowlayout,并添加JTextArea,但不起作用。

3 个答案:

答案 0 :(得分:3)

您可以使用BorderLayout并将JTextArea添加到Center并将按钮面板的布局设置为FlowLayout并将其添加到North。如果你需要代码,请告诉我。

答案 1 :(得分:2)

以下是一个示例,建议BorderLayout适用于主面板。

为了更接近您的示例,我在北面板上添加了一个边距(空边框),以及按钮之间的水平支柱(在北面板中使用BoxLayout )。

JFrame frame = new JFrame();

JPanel contentPanel = new JPanel();

contentPanel.setLayout(new BorderLayout());

JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

JButton b1 = new JButton("B1");
JButton b2 = new JButton("B2");

buttonsPanel.add(b1);
buttonsPanel.add(Box.createHorizontalStrut(5));
buttonsPanel.add(b2);

contentPanel.add(buttonsPanel, BorderLayout.NORTH);
contentPanel.add(new JTextArea(), BorderLayout.CENTER);

frame.setContentPane(contentPanel);
frame.setSize(400, 300);
frame.setVisible(true);

答案 2 :(得分:1)

BorderLayout和大多数其他布局管理器(例如BoxLayoutGridBagLayout)的问题在于它们以像素为单位设置组件之间的间隙。这是不可移植的,因为在不同的屏幕上布局会 看起来不同。如果您在19英寸显示器上创建UI,它将无法显示 32英寸显示器上很好。现在我们谈论Java应用程序,其中可移植性至关重要。

幸运的是,通过GroupLayoutMigLayout,我们可以创建真正的便携式UI。

package com.zetcode;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;

public class MigLayoutTwoButtonsEx extends JFrame {

    public MigLayoutTwoButtonsEx() {

        initUI();
    }

    private void initUI() {

        JButton btn1 = new JButton("B1");
        JButton btn2 = new JButton("B2");
        JTextArea area = new JTextArea(15, 28);
        area.setBorder(BorderFactory.createEtchedBorder());

        createLayout(btn1, btn2, area);

        setTitle("MigLayout example");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {

        setLayout(new MigLayout("gap 5lp 7lp"));

        add(arg[0], "split 2");
        add(arg[1], "wrap");
        add(arg[2], "push, grow, span");
        pack();
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            MigLayoutTwoButtonsEx ex = new MigLayoutTwoButtonsEx();
            ex.setVisible(true);
        });
    }
}

以下是MigLayout经理的示例。

setLayout(new MigLayout("gap 5lp 7lp"));

我们使用逻辑像素来定义我们的差距。

截图:

Screenshot of the example

相关问题