我想在垂直方向上一个接一个地把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();
}
}
最佳答案
您可以使用GridBagLayout
。它支持“填充”约束,允许您在网格中填充组件。阅读 How to Use GridLayout 上的 Swing 教程部分有关您可以使用的约束的更多信息。
或者,如果您想跳出框框,可以使用 Relative Layout .它可以像 BoxLayout 一样工作。它可以在首选高度垂直显示组件,但它有一个自动填充宽度的参数。它不是 JDK 的一部分,但您不必担心构建约束。
关于java - 将JPanels依次垂直添加到JFrame中,每个水平接触边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26033789/