Search code examples
javaswingjlabel

Replicate the same JLabel with diferent variable names


I'm needing to make the same JLabel appear multiple times on the same grid layout, but I'm having trouble implementing a method to produce label00, label01, label02, ..., label10. These labels must have the same content. Can someone give me a code example to do this?

public class Grid {
    private JFrame f;

    public Grid(String fname, int row, int column, int d) {
        f = new JFrame(fname);
        f.setLayout(new GridLayout(row,column));
        f.setSize(row*d,column*d);
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        addContent(row,column,d);
    }

    public void open() {
        f.setVisible(true);
    }

    private void addContent(int r, int c, int d) {
        JLabel label=new JLabel(" ");
        Border border = BorderFactory.createLineBorder(Color.black, 2);
        label.setBorder(border);
        label.setPreferredSize(new Dimension(d,d));
        f.add(label);
        JLabel label1= new JLabel("1 ");
        f.add(label1);
    }


    public static void main(String[] args) {
         Grid grid = new Grid("Test", 5, 4, 50);
         grid.open();
    }
}

Instead of creating each label manually I want to implement a method to generate label1, label2, ... labeli automatically with the text of the original label.


Solution

  • You have a grid which is a two dimensionnal array. To fill it with JLabel, iterate over the two dimensions and add your custom JLabel like this. If you have specific properties, like computation on values or styling, I suggest you create a custom JLabel.

    private JFrame f;
    public Grid(String fname, int row, int column, int d) {
        f = new JFrame(fname);
        f.setLayout(new GridLayout(row,column));
        f.setSize(row*d,column*d);
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        addContent(row,column,d);
    }
    
    public void open() {
        f.setVisible(true);
    }
    
    private void addContent(int r, int c, int d) {
        Border border = BorderFactory.createLineBorder(Color.black, 2);
        for (int i = 0 ; i < r ; i++) {
            for (int j = 0 ; j < c ; j++) {
                f.add(new JLabel(i+","+j) {{
                     setBorder(border);
                     setPreferredSize(new Dimension(d,d));
                }});
            }
        }
    }
    public static void main(String[] args) { 
        Grid grid = new Grid("Test", 5, 4, 50);
        grid.open();
    }
    

    Result :

    result

    EDIT :

    Since it is a tic tac toe game and I suggested to you, create a custom JLabel which can implements mouselistener on click (for example), you will be able to modify colors and so on depending on events.

    public class TicTacToeCell extends JLabel {
        private static final long serialVersionUID = 1L;
        public TicTacToeCell(Border border, int height, int width) {
            setText("");
            setBorder(border);
            setPreferredSize(new Dimension(height, width));
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (getText().isEmpty()) {
                        setText(getClickedValue());
                    }
                }
            });
        }
    } 
    

    You need to know what was the last click so put a static method to return O or X each time a cell has been clicked.

    public static int clickValue = 0;
    public static String getClickedValue() {
        clickValue = clickValue == 0 ? 1 : 0;
        return clickValue == 0 ? "X" : "O";
    }
    

    Add it to your grid when you build your GUI

    private void addContent(int r, int c, int d) {
        Border border = BorderFactory.createLineBorder(Color.black, 2);
        for (int i = 0 ; i < r ; i++) {
            for (int j = 0 ; j < c ; j++) {
                f.add(new TicTacToeCell(border, d, d));
            }
        }
    }
    

    Result (changed grid to 3,3) :

    result2

    Full example :

    public class Grid {
        private JFrame f;
        public Grid(String fname, int row, int column, int d) {
            f = new JFrame(fname);
            f.setLayout(new GridLayout(row,column));
            f.setSize(row*d,column*d);
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            addContent(row,column,d);
        }
        public void open() {
            f.setVisible(true);
        }
        private void addContent(int r, int c, int d) {
            Border border = BorderFactory.createLineBorder(Color.black, 2);
            for (int i = 0 ; i < r ; i++) {
                for (int j = 0 ; j < c ; j++) {
                    f.add(new TicTacToeCell(border, d, d));
                }
            }
        }
        public static void main(String[] args) {
             Grid grid = new Grid("Test", 3, 3, 50);
             grid.open();
        }
        public static int clickValue = 0;
        public static String getClickedValue() {
            clickValue = clickValue == 0 ? 1 : 0;
            return clickValue == 0 ? "X" : "O";
        }
        public class TicTacToeCell extends JLabel {
            private static final long serialVersionUID = 1L;
            public TicTacToeCell(Border border, int height, int width) {
                setText("");
                setBorder(border);
                setPreferredSize(new Dimension(height, width));
                addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (getText().isEmpty()) {
                            setText(getClickedValue());
                        }
                    }
                });
            }
        }
    }