1
import javax.swing.*;
import java.awt.event.*;

public class SimpleGUI3 implements ActionListener  {
    JButton button;
    private int numClick;

    public static void main(String[] args) {
        SimpleGUI3 gui = new SimpleGUI3();
        gui.go();
    }

    public void go() {
        JFrame frame = new JFrame();
        button = new JButton("Click me.");
        button.addActionListener(this);
        frame.getContentPane().add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        button.setLocation(100, 100); //This code do not change the button location if numClick++ (next row) used.   
        numClick++;                   //If comment numClick++ the button changes location on click. Why location doesn't changes if this row uncomment?
        button.setText("Has been clicked " + numClick + " times.");
    }
}

The question is: Why location changes on click without numClick++ in code and why the button ocation doesn't changes if numClick++ work in code?

jakarjakar
  • 33
  • 6
  • 1
    `button.setLocation(100, 100);` Don't do that. It is effectively fighting the layout manager. What is the purpose of moving the button? – Andrew Thompson Sep 21 '16 at 11:57
  • The purpose is just understanding how it works. With commented nubClick++ the button moves on click, once. – jakarjakar Sep 21 '16 at 13:11
  • *"The purpose is just understanding how it works."* So.. you want to understand how something that shouldn't be done, works? Utterly pointless. **If** there were an actual reason to move components on button click, it would best be done by changing the parameters of an `EmptyBorder` that wraps a panel containing the component. But instead turn your attention to things that are actually useful & maintain best practices.. – Andrew Thompson Sep 21 '16 at 13:32

1 Answers1

2

When you change the value of numClick the text of the button also changes when you use the setText() method.

When a property of the button changes then Swing will automatically invoked revalidate() and repaint() on the component.

The revalidate() will invoke the layout manager and the layout manager will reset the location of the button back to (0, 0) based on the rules of the layout manager, which is a BorderLayout by default for the content pane of the frame.

Bottom line is don't try to manage the location or size of a component. That is the job of the layout manager.

Also, learn and use Java naming conventions. Class names should start with an upper case character.

Read the Swing tutorial for Swing basics.

camickr
  • 321,443
  • 19
  • 166
  • 288