import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class TestPaint
{
public static void main(String[] args)
{
TestPaintFrame frame = new TestPaintFrame();
frame.show();
}
}
class TestPaintFrame extends JFrame
{
public TestPaintFrame()
{
JButton button = new JButton("paint");
ExitWindow exit = new ExitWindow();
setSize(600,400);
TestPaintPanel panel = new TestPaintPanel();
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(button);
cp.add(panel);
this.addWindowListener(exit);
}
}
class TestPaintPanel extends JPanel
{
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawString("STRING SHOW",10,10);
setSize(200,200);
System.out.println("call");
}
}class ExitWindow extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
import java.awt.*;
import java.awt.event.*;public class TestPaint
{
public static void main(String[] args)
{
TestPaintFrame frame = new TestPaintFrame();
frame.show();
}
}
class TestPaintFrame extends JFrame
{
public TestPaintFrame()
{
JButton button = new JButton("paint");
ExitWindow exit = new ExitWindow();
setSize(600,400);
TestPaintPanel panel = new TestPaintPanel();
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(button);
cp.add(panel);
this.addWindowListener(exit);
}
}
class TestPaintPanel extends JPanel
{
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawString("STRING SHOW",10,10);
setSize(200,200);
System.out.println("call");
}
}class ExitWindow extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
因此你要在每次paint的时候强制设定大小setSize(200,200);
初始化设置行不通。