public static void main(String[] args) {
      JTextField text = new JTextField();
      JFrame frame = new JFrame();
      frame.setLayout(new BorderLayout());
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(5, 4));
      JPanel panel2 = new JPanel();
      panel2.setLayout(new FlowLayout());



      JLabel imgLabel1 = new JLabel(new ImageIcon("C:\\Users\\Arthur\\Downloads\\abs.jpg"));
      JLabel imgLabel2 = new JLabel(new ImageIcon("C:\\Users\\Arthur\\Downloads\\abss.jpg"));


      imgLabel1.setPreferredSize(new Dimension(100,100));
      imgLabel2.setPreferredSize(new Dimension(100,100));

      panel2.add(imgLabel1);
      panel2.add(imgLabel2);


      for(int i=0; i<20; i++){
          panel.add(panel2);
      }


      frame.add(text, BorderLayout.NORTH);
      frame.add(panel, BorderLayout.CENTER);
      frame.setPreferredSize(new Dimension(1280,700));
      frame.pack();
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

我想做一个记忆游戏,我需要在4x5的JPanel的每个单元中放置两个图像。为此,我创建了一个内部包含两个图像的JPanel 1x2,并将其放入4x5的JPanel中。但是结果是:

结果:

java - JAVA中的JPanel中的JPanel-LMLPHP

最佳答案

因此,如果正确理解,您遇到的问题是,您看不到20个新面板,只有一个。

问题是,一个组件只能在一个容器中驻留一次,因此执行类似...

for (int i = 0; i < 20; i++) {
    panel.add(panel2);
}

等价于...
panel.add(panel2);

您实际上需要在循环的每次迭代中创建组件的新实例

我建议您做的是创建一个可以包含两个图像的“包装器”或“卡片”面板。在我的测试中,我只使用了彩色面板,但是您知道了...
public class WrapperPane extends JPanel {

    public WrapperPane() {
        setLayout(new FlowLayout());
        add(makePanel(Color.RED));
        add(makePanel(Color.GREEN));
        // This is just for demonstration purposes
        setBorder(new LineBorder(Color.DARK_GRAY));
    }

    protected JPanel makePanel(Color background) {
        JPanel panel = new JPanel();
        panel.setBackground(background);
        panel.setPreferredSize(new Dimension(100, 100));
        return panel;
    }

}

您只需要执行类似...
JTextField text = new JTextField();
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4));

for (int i = 0; i < 20; i++) {
    panel.add(new WrapperPane());
}

frame.add(text, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
// Don't do this, just let the content make it's own
// calculations
//frame.setPreferredSize(new Dimension(1280, 700));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

你最终会得到类似...

java - JAVA中的JPanel中的JPanel-LMLPHP

09-08 03:44