Search code examples
javainterfacejbuttonjlabel

How do you convert a JLabel to a Button in Java?


I have a JLabel with ImageIcons of t-shirts. I want to make each t-shirt have the ability to be clicked and then it will lead to another window. How can I make each t-shirt a button while maintaining the pictures? This is just part of one of my methods and I want the shirts to become JButtons. Here is my code:

final JFrame shirts = new JFrame("T-shirts");

        JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));

        for (int i = 1; i < 13; i++) {
           l = new JLabel(new ImageIcon("T-shirts/"+i+".jpg"), JLabel.CENTER);
            l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
            l.setFont(l.getFont().deriveFont(20f));
            panel.add(l);
        }//end of for loop


        shirts.setContentPane(panel);
        shirts.setSize(1000, 1000);
        shirts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        shirts.setVisible(true);

Solution

  • There is no need to change to a JButton. The simplest option here is to implement a MouseListener.

    This will allow you to test for mouse clicked events:


    yourLabelName.addMouseListener(new MouseAdapter()  
    {  
        public void mouseClicked(MouseEvent e)  
        {  
           //point to the frame you want it to go to from here
           yourFrame = new JFrame("Next JFrame");
           frame.setVisible(true);
    
        }  
    }); 
    

    UPDATE

    shirts.this.add(l);
    

    That will add the label to the next JFrame


    Hope this helps.

    Let me know of the outcome :)