setLocation in actionPerformed只在没有整数增量的情况下改变按钮位置


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()方法时,按钮的文本也会更改。

当按钮的属性发生变化时,Swing将自动调用组件上的revalidate()repaint()

revalidate()将调用布局管理器,布局管理器将根据布局管理器的规则将按钮的位置重置回(0,0),这是框架内容窗格的默认BorderLayout。

底线是不要试图管理组件的位置或大小。这是布局管理器的工作。

还要学习和使用Java命名约定。类名应该以大写字符开头。

阅读Swing基础教程

相关内容

最新更新