我想生成多个面板(带有title,desc和detail按钮),这是一般结构:
但是当我将此代码放在for
循环中时,它总是添加最后一项。
Panel panel_1 = new Panel();
panel_1.setBounds(23, 134, 378, 208);
JLabel lblNewLabel_2 = new JLabel("desc");
lblNewLabel_2.setBounds(0, 69, 189, 69);
JButton btnNewButton_2 = new JButton("Details");
btnNewButton_2.setBounds(104, 139, 189, 69);
panel_1.setLayout(null);
JLabel lblPrv = new JLabel("title");
lblPrv.setBounds(104, 0, 189, 69);
panel_1.add(lblPrv);
panel_1.add(lblNewLabel_2);
JLabel label_1 = new JLabel("");
label_1.setBounds(0, 69, 189, 69);
panel_1.add(label_1);
panel_1.add(btnNewButton_2);
有什么建议吗?
答案 0 :(得分:1)
以下是如何将多个面板彼此相邻放置的示例:
public class Example extends JFrame {
Example() {
setLayout(new FlowLayout());
for (int i = 0; i < 4; i++)
add(new MyPanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
class MyPanel extends JPanel {
MyPanel() {
setLayout(new BorderLayout());
add(new JLabel("title", SwingConstants.CENTER), BorderLayout.PAGE_START);
add(new JLabel("<html>WWWWWW WWWWWWW<p>WWWWWWWWW<p>RRRRRRR RRRRR RRRRRRR"));
add(new JButton("Details"), BorderLayout.PAGE_END);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Example());
}
}
您应该选择最适合您情况的布局管理器。