jakarjakar jakarjakar - 1 year ago 130
Java Question

setLocation in actionPerformed change button location only if there are no integer incrementation

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();

public void go() {
JFrame frame = new JFrame();
button = new JButton("Click me.");
frame.setSize(300, 300);

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download