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.");
}
}
问题是:为什么在代码中没有numClick ++的点击位置会发生变化,如果numClick ++在代码中起作用,为什么按钮的位置不会改变?
当您更改numClick的值时,使用该setText()
方法时按钮的文本也会更改。
当按钮的属性然后改变摆动会自动调用revalidate()
并repaint()
在组件上。
在revalidate()
将调用布局管理器和布局管理器将按钮背面的位置重置为基于所述布局管理器,这是一种通过BorderLayout的默认为所述帧的所述内容窗格中的规则(0,0)。
最重要的是不要尝试管理组件的位置或大小。那是布局管理器的工作。
另外,学习和使用Java命名约定。类名应以大写字母开头。
阅读有关Swing基础知识的Swing教程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句