我的想法是: 按一下按钮就达到重绘(添加组件),不知道为什么就是不可以添加 出不出来效果import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Label;import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class JPanel1 extends JPanel{ /**
 * @param args
 */
private boolean show=false;
private Test1 t;

protected void paintComponent(Graphics g){
super.paintComponent(g);
JButton jb1=new JButton("1111");
JButton jb2=new JButton("1222");
JButton jb3=new JButton("1333");
if(show==true){
jb1.setVisible(true);
jb2.setVisible(true);
jb3.setVisible(true);
this.setLayout(new FlowLayout());
Dimension ds=new Dimension(50,50); jb1.setPreferredSize(ds);
jb2.setPreferredSize(ds);
jb3.setPreferredSize(ds);
this.add(jb1);
this.add(jb2);
this.add(jb3);
t.add(this);
System.out.println(show);
}else{
Label lb=new Label("Test"); this.add(lb);
}
}
public JPanel1(Test1 t){
this.t=t;
}
public void setShow(boolean v){
show=v;
repaint();
}
}
import java.awt.Dimension;
import java.awt.FlowLayout;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test1 extends JFrame{ /**
 * @param args
 * @return 
 */

private JPanel1 jp;
public  Test1(){
init();
setSize(400,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true); }

public void init(){
 jp=new JPanel1(this);
 jp.setLayout(new FlowLayout());
JButton jb=new JButton("确定");
Dimension ds=new Dimension(50,50);
jb.setPreferredSize(ds);
jb.addActionListener(new Al(this));
jp.add(jb);
this.getContentPane().add(jp); }

public JPanel1 getJPanel(){
return jp;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 t=new Test1();
}}import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Al implements ActionListener {
private Test1 t; private JPanel1 jp1;

public Al(Test1 t){
this.t=t;
}
public void actionPerformed(ActionEvent e) {
String name=e.getActionCommand();
if(name.equals("确定")){
System.out.println(name);
t.getJPanel().setShow(true);
} }}
JavaSwing重绘paintComponent

解决方案 »

  1.   

    在要添加组件时,都是这个做? 没有其他的方法?
    protected  void paintComponent(Graphics g){
    super.paintComponent(g);
    if(show==true){
    jb=new JButton("确定1");
    t.getJPanel().add(jb);
    System.out.println(t);
    t.add(t.getJPanel());
    }
    }
    监听中
    public void actionPerformed(ActionEvent e) {
    String name=e.getActionCommand();
    if(name.equals("确定")){
    System.out.println(name);
    t.getJPanel().setShow(true);
    }
    }
    这样也不可以?