java - 将JPanels依次垂直添加到JFrame中,每个水平接触边框

标签 java swing layout jframe

我想在垂直方向上一个接一个地把JPanels添加到JFrame中。每个面板应覆盖 jframe 的整个宽度。即使调整了框架的大小,这些面板也应该覆盖整个宽度。我想使用任何布局来使用它。不应使用线程。从附带的图像中捕获我想要的东西。 提前致谢。任何帮助尝试将不胜感激...

这是您请求的代码,但我投了反对票...

public class AttachToWalls extends JFrame implements ActionListener {

    JLabel m1;
    JLabel m2;
    JPanel pane;
    JPanel bottom = new JPanel();
    JScrollPane jsp;
    JButton sender = new JButton("Sender");
    JButton receiver = new JButton("Receiver");

    AttachToWalls() {
        setLayout(new FlowLayout());
        jsp = new JScrollPane(pane);
        add(jsp, BorderLayout.CENTER);
        sender.addActionListener(this);
        receiver.addActionListener(this);
        bottom.add(sender);
        bottom.add(receiver);
        add(bottom);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == sender) {
            m1 = new JLabel("Message from Sender...");
            remove(sender);
            remove(receiver);
            Component comp = Box.createHorizontalStrut(this.getWidth() - m1.getWidth());
            comp.setBackground(Color.red);
            JPanel pane1 = new JPanel();
            pane1.setBackground(Color.gray);
            pane1.add(m1);
            pane1.add(comp);
            add(pane1);
            this.validate();
        } else if (e.getSource() == receiver) {
            m2 = new JLabel("Messsage from Receiver...");
            Component comp = Box.createHorizontalStrut((int) this.getWidth() - m2.getWidth());
            comp.setBackground(Color.red);
            JPanel pane2 = new JPanel();
            pane2.setBackground(Color.gray);
            pane2.add(m2);
            pane2.add(comp);
            add(pane2);
            this.validate();
        }
    }

    public static void main(String[] args) {
        new AttachToWalls();
    }
}

enter image description here enter image description here

最佳答案

您可以使用GridBagLayout。它支持“填充”约束,允许您在网格中填充组件。阅读 How to Use GridLayout 上的 Swing 教程部分有关您可以使用的约束的更多信息。

或者,如果您想跳出框框,可以使用 Relative Layout .它可以像 BoxLayout 一样工作。它可以在首选高度垂直显示组件,但它有一个自动填充宽度的参数。它不是 JDK 的一部分,但您不必担心构建约束。

关于java - 将JPanels依次垂直添加到JFrame中,每个水平接触边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26033789/

相关文章:

c++ - Qt : Qlabel and QPushButton in a QVBoxLayout

java - 在这种特定情况下,Java 数据类型真的很困惑

Java:帮我解析或理解这一行?

java - 刷新 GUI 时线程中出现异常

java - 在 JTextPane 中设置字体宽度

jquery - 让 CSS 类选择器覆盖 CSS id 选择器

java - Tomcat 设置在 Mac 上失败并显示 'Cannot find jni_md.h in/usr/bin/java/'

java - ArrayBlockingQueue : should use to create Pool?

java - 每次单击按钮时如何将值写入不同的文本字段?

java - 从 Android 中的应用程序添加布局 View