我只想在单击按钮时移动一个按钮,并且我想更改标签文本。
我编写了移动按钮的代码,它对我来说工作正常。但是当我想将标签文本更改为不同的名称时,它不会发生。
按钮正在从其位置移动或标签文本已更改。但我想同时执行这两个操作,即按钮单击事件。我尝试了很多东西。一些身体可以帮助我吗?
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();
}
});
}
}