I just want to move a button when clicked on it and also I want to change the label text.
I wrote code for moving the button and it’s working fine for me. But when I want to change the label text to different name it’s not happening.
Either the button is moving from its place or the labels text is changed. But I want to perform both actions at once i.e. on button click event. I tried so many things as I could. Can some body help me?
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JavaGUI extends JPanel {
private Control control = new Control();
private Keys keys = new Keys("Original starting value.");
public JavaGUI() {
this.add(keys);
this.add(control);
}
private class Control extends JPanel {
public Control() {
this.add(new JButton(new AbstractAction("Update") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Command: " + e.getActionCommand());
keys.string = String.valueOf(System.nanoTime());
//keys.label.setText(keys.string);
// If I remove these comments button will not move. bt I want both...
JButton j = (JButton) e.getSource();
j.setLocation(j.getX()+10,j.getY()+10);
}
}));
}
}
private class Keys extends JPanel {
private String string;
private JLabel label = new JLabel();
public Keys(String s) {
this.string = s;
label.setText(s);
this.add(label);
}
}
private void display() {
JFrame f = new JFrame("JavaGUI");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new JavaGUI().display();
}
});
}
}
You cannot move a button just like that, the layout manager tells it where it should be. Calling setText triggers the effect of layout manager for the whole component hierarchy. If you really want to do this, you should set a null layout manager, and manage all the sizes and locations of all components manually.
Even if your button was moving in your original code, it was not painted correctly as soon as it left its original place – you could accidentally abuse Swing, but not completely.
Working solution: