简体   繁体   中英

JButton: Changing the location of a button

How can I change the location of a button every time I click it? It works but only for the first time I click it.

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

public class Viewer {
    private static JButton b1 = new JButton("Action Listener");
    private static JFrame f = new JFrame();
    private static JPanel p = new JPanel();
    public static void main(String[]args){
        f.setVisible(true);
        f.setSize(400,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           
        p.add(b1);
        f.add(p);       
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {        
                b1.setLocation(100,100);
            }
        });
    }
}

By default, JPanel uses a FlowLayout . This means any changes to a components position will only be temporary and will be "reset" by the layout manager the next time the container is laid out. Try resizing the frame after you have moved the button

As @JoshM has already being pointed out, you are simply moving the button to the same location on each click.

The question is, why do you want to move the button?

DISCLAIMER

This is NOT how you would want to do this! As MadProgrammer has pointed out, this result will not last once the panel is invalidated. This is just an example of why you weren't getting the result you wanted.

Your actionPerformed() method is being called each time, it's just that every time it executes it is placing the button in the same place. If you want it to, lets say, move right 10 each time you click, try something like this.

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

public class Viewer {
    private static JButton b1 = new JButton("Action Listener");
    private static JFrame f = new JFrame();
    private static JPanel p = new JPanel();
    private static int location = 100; //Make a variable for location
    public static void main(String[]args){
        f.setVisible(true);
        f.setSize(400,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           
        p.add(b1);
        f.add(p);       
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {        
                b1.setLocation(location,100);
                location += 10; //This will change where it draws next time
            }
        });
    }
}

Also, your use of static is quite wrong. You are using it so you can perform all of this in main(), but what you need is Swing's EDT here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM