有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将JPanel垂直地一个接一个地添加到JFrame中,每个JPanel水平地接触到边框

我想把JPanel一个接一个地垂直添加到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


共 (1) 个答案

  1. # 1 楼答案

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

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