Search code examples
javaswinganimationjbuttonjlabel

how to make JButton changes the location of the text inside JLabel


how can i set JButton that changes the JLabel location on the JPanel when it pressed? how to implement the actionlistener for this on the JButton?


Solution

  • You want to add the action listener to the button first

    button.addActionListener(new ButtonListener());
    

    Next you want to create the custom class

    class ButtonListener implements ActionListener {
         public void actionPerformed(ActionEvent e) {
                if(e.getSource() == button) {
                     label.setLocation(xValue, yValue);
                }
         }
    }
    

    Change the xValue/yValue to the x and y values that you want the label to change to.

    I hope this helps!