- Java code
public class AAA extends JFrame{ public AAA(){ JButton j1=new JButton("12"); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300,300); add(j1); j1.setLocation(this.getSize().width-150,100); j1.setSize(100,20);// j1.addActionListener(new ActionListener() {// // @Override// public void actionPerformed(ActionEvent e) {// AAA.this.repaint();// }// }); setVisible(true); } public static void main(String[] args) { new AAA(); }}
这是个测试代码。我的想法是,控件位置写成相对的,然后改变窗口大小时,窗口不会出现空白或者控件消失。但是系统就是不调用repaint方法。注释的代码是我写的强制调用,都不行。这该怎么办呢?
------解决方案--------------------
执行了重绘的方法,你可以看看最大最小化已经改变大小的时候控制台的输出,参考下面代码
- Java code
import javax.swing.*;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.*;public class AAA extends JFrame { public AAA(){ JButton j1=new JButton("12"); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300,300); add(j1); j1.setLocation(this.getSize().width-150,100); j1.setSize(100,20); j1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AAA.this.repaint(); } }); setVisible(true); } @Override public void paint(Graphics g) { super.paint(g); //To change body of overridden methods use File | Settings | File Templates. System.out.println("repaint"); } public static void main(String[] args) { new AAA(); }}