简体   繁体   English

如何将JPanels逐个添加到JPanel类型的数组中

[英]How to add JPanels one by one to an array of type JPanel

Currently, I'm facing a problem with this code, I want every time that I add a point to the map to add a JPanel to the array Panels (which is an array of JPanel). 目前,我正面临着这个代码的问题,我希望每次我向地图添加一个点以将JPanel添加到数组Panels(这是一个JPanel数组)。

I can't use for statement because I want to add 1 Jpanel per call (addPanel()), and also I'm facing a problem with the action listener,it only recognizes the first element in the array which is normal because the JPanel is not added to the array. 我不能使用for语句,因为我想每次调用添加1个Jpanel(addPanel()),而且我还面临动作监听器的问题,它只识别数组中的第一个元素,因为JPanel是正常的未添加到数组中。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;

public class TestGrid02 extends JPanel  {

   private static final long serialVersionUID = 1L;

   protected static final Color SELECTION_COLOR = Color.pink;
   private Color originalColor = new Color(238,238,238) ;
   private static final Dimension PREF_SIZE = new Dimension(50, 50);
   public JPanel panel_2;
   public JPanel panel_3;
   public JFrame frame;
   public JTextField textField;
   public int maxX =10;
   public int maxY =10;
   public String name;
   JPanel[] panels = new JPanel[100];


   public TestGrid02() {
       initUI();
       createMap(panel_2,maxX ,maxY );

   }

   public final void initUI() {

       setLayout(new BorderLayout(0, 0));

        panel_2 = new JPanel();
        add(panel_2, BorderLayout.WEST);
        panel_2.setLayout(new GridLayout(10, 10, 1, 1));
        panel_2.setBackground(Color.GRAY);

        panel_3 = new JPanel(new BorderLayout(4, 4));
        add(panel_3, BorderLayout.LINE_END);
        panel_3.setBackground(Color.GREEN);

        JPanel controls = new JPanel(new GridLayout(0, 1, 0, 25));
        panel_3.add(controls, BorderLayout.PAGE_START);
        controls.setBackground(Color.CYAN);
        controls.setBorder(new EmptyBorder(40, 20, 20, 20));
        controls.add(new JTextField(10));
        controls.add(new JTextField(10));
        controls.add(new JButton("OK"));
   }


   public void createMap(JPanel a,int maxX,int maxY)  {    

       String [ ][ ] map = new String [maxX][maxY];

      for (int x = maxX-1; x>=0 ; x--) {

          for (int y = 0; y<maxY  ; y++) { 
               int i=x-1;
               int j=y-1;

              map [x][y] =  i + ","+  j ;
              System.out.println( map [x][y]); 
              addPanel(a,i,j);

}}}

   public void addPanel(JPanel a,int c, int d) {
              int i =0;
              panels[i] = new JPanel();        
              a.add(panels[i]);
              panels[i].setPreferredSize(PREF_SIZE);
              name = String.format("[%d, %d]", c,d);
              panels[i].setBackground(originalColor);
              panels[i].setName(name); 
              System.out.println(  "PanelName:"+panels[i].getName());
              //panels[i] =panels[i]; 
              //I need this statement to add the panel to the array panels

              panels[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseEntered(MouseEvent e) {
                    panels[i].setBackground(Color.pink);
                    panels[i].add(new JLabel(panels[i].getName()));

                    panels[i].repaint();
                    panels[i].revalidate();

                }

                @Override
                public void mouseExited(MouseEvent e) {
                    panels[i].setBackground(originalColor);
                    panels[i].repaint();
                    panels[i].removeAll();

                }
            });

   }   


   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
             JFrame frame = new JFrame("Astar");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.getContentPane().add(new TestGrid02());
             frame.setLocationRelativeTo(null);
             frame.pack();
             frame.setVisible(true);     

         }
      });
   }
}

it only recognizes the first element in the array which 它只识别数组中的第一个元素

That is because all you code references the variable "i" which never seems to change. 那是因为你所有的代码都引用了似乎永远不会改变的变量“i”。

When adding (or removing) components from a visible GUI the basic code is: 从可见GUI添加(或删除)组件时,基本代码为:

panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint();

Don't use an Array to hold the panels. 不要使用阵列来固定面板。 You are restricting yourself to some hardcoded size. 你正在限制自己的硬编码大小。 Instead use an ArrayList . 而是使用ArrayList Or the real question is do you even need an Array to hold the panels for future processing? 或者真正的问题是你甚至需要一个数组来保存面板以供将来处理吗?

Your MouseListener code is wrong. 您的MouseListener代码错误。 To reference the component that generated the event your code should be: 要引用生成事件的组件,您的代码应该是:

JPanel panel = (JPanel)e.getSource();
panel.setBackground(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM