0

I create a JLabels array which is [9][9] on java. and i want to set visible these JLabels when i clicked with mouse on these labels. Anyone can help me?

I tried this:
    //labels[c][d].addMouseListener(null);
    public void mouseClicked(MouseEvent me){
    //        for(Integer i=1;i<10;i++)
    //        {
    //            for(Integer j=1;j<10;j++)
    //            {
    //               
    //                if (me.getSource()==labels[i][j]);
    //                {
    //                  
    //                    labels[1][1].setVisible(true);
    //                }
    //            }
    //       
    //    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
ademcu
  • 131
  • 1
  • 2
  • 6

4 Answers4

3

Use a JToggleButton as shown in Swing JToolbarButton pressing.

In your use-case, the green unselected image will simply be either a fully transparent image, or an image that is the desired BG color.

More specific example:

Toggle Image

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

class ToggleImage {

    public static JToggleButton getButton(
        Image selected,
        Image unselected) {

        JToggleButton b = new JToggleButton();
        b.setSelectedIcon(new ImageIcon(selected));
        b.setIcon(new ImageIcon(unselected));
        b.setBorderPainted(false);
        b.setContentAreaFilled(false);
        b.setFocusPainted(false);
        b.setMargin(new Insets(0,0,0,0));

        return b;
    }

    public static Image getImage(boolean hasSquare) {
        int size = 60;
        BufferedImage bi = new BufferedImage(
            size,size,BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();

        if (hasSquare) {
            g.setColor(Color.RED);
            g.fillRect(1,1,size-2,size-2);
        }

        g.dispose();
        return bi;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                Image selected = getImage(true);
                Image unselected = getImage(false);

                int row = 2;
                int col = 5;
                JPanel p = new JPanel(new GridLayout(row,col));

                for (int ii=0; ii<row*col; ii++) {
                    p.add( getButton(selected, unselected) );
                }

                JOptionPane.showMessageDialog(null, p);
            }
        });
    }
}

Note that a button will react to both mouse and keyboard input, whereas (by default) a label won't.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

If all those JLabels are invisible at the beginning - they won't be able to catch mouse/key events. If you want to show labels content only after click on them - just don't set their text before they recieve a click, like this:

public static void main ( String[] args )
{
    JFrame frame = new JFrame ();
    frame.setLayout ( new GridLayout ( 9, 9 ) );
    frame.getContentPane ().setPreferredSize ( new Dimension ( 300, 300 ) );

    final Random random = new Random ();
    for ( int i = 0; i < 9; i++ )
    {
        for ( int j = 0; j < 9; j++ )
        {
            final JLabel label = new JLabel ( "", JLabel.CENTER );
            label.setBorder ( BorderFactory.createLineBorder ( Color.LIGHT_GRAY ) );
            label.addMouseListener ( new MouseAdapter ()
            {
                public void mousePressed ( MouseEvent e )
                {
                    label.setText ( "" + random.nextInt ( 100 ) );
                }
            } );
            frame.add ( label );
        }
    }

    frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}
Mikle Garin
  • 10,083
  • 37
  • 59
  • i create a Jlabel Array. it means there are 91 labels. What about this one? – ademcu May 02 '12 at 12:21
  • First of all, not 91 but 81 (9*9=81). Second thing - you can easily save all created JLabels from my example into some array. It was just pointless to add some array into the example since the question is not about it but the visibility. – Mikle Garin May 02 '12 at 12:30
2

The code you posted does not seem to bad. But you always set the label at index [1][1] visible instead of using [i][j].

And of course, if your JLabel really is the source of the MouseEvent you can ditch the whole looping mechanism altogher, e.g. if you use

me.getSource()==labels[i][j]

to determine which label you need to set to visible, you can replace the whole double loop by

((JLabel)me.getSource()).setVisible( true );
Robin
  • 36,233
  • 5
  • 47
  • 99
2

I hope this helps.

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Clicker extends JPanel {
    private static final int ROWS = 9; 
    private static final int COLUMNS = 9;

    public Clicker() {
        setLayout(new GridLayout(COLUMNS, ROWS));

        JLabel labels[][] = new JLabel[ROWS][];
        for (int i = 0; i < ROWS; i++) {
            labels[i] = new JLabel[COLUMNS];    
        }

        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLUMNS; j++) {
                labels[i][j] = new JLabel();
                labels[i][j].addMouseListener(createMouseListener());
                add(labels[i][j]);
            }
        }
    }

    public MouseAdapter createMouseListener() {
        return new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JLabel label = (JLabel)e.getSource();

                if (!label.isEnabled()) {
                    label.setText("");
                    label.setEnabled(true);
                } else {
                    label.setText("Clicked");
                    label.setEnabled(false);
                }
            }
        };
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame("Click me demo.");
        frame.setSize(500, 500);
        frame.setLayout(new BorderLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new Clicker(),BorderLayout.CENTER);
        frame.setVisible(true);
    }
}
Reg
  • 10,717
  • 6
  • 37
  • 54