当前位置: 技术问答>java相关
如何动态添加组件?
来源: 互联网 发布时间:2017-04-13
本文导语: 请问如何在组件中动态地添加组件? 如按下按钮则在原容器中生成一个新组件并显示新组件的信息。 | import javax.swing.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.util.*; ...
请问如何在组件中动态地添加组件?
如按下按钮则在原容器中生成一个新组件并显示新组件的信息。
如按下按钮则在原容器中生成一个新组件并显示新组件的信息。
|
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.*;
public class test extends JFrame implements ActionListener {
JPanel contentPanel=(JPanel)this.getContentPane();
JButton jb=new JButton("add");
JPanel jp1=new JPanel(new FlowLayout());
JPanel jp2=new JPanel(new FlowLayout());
public test() {
super("myJFrame");
this.setSize(400,300);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPanel.setLayout(new BorderLayout());
contentPanel.add("North",jp1);
contentPanel.add("Center",jp2);
jp1.add(jb);
jb.addActionListener(this);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb) {
JButton jb2=new JButton("JButton"+(jp2.getComponentCount()+1));
jb2.addActionListener(this);
jp2.add(jb2);
this.validate();
} else {
jp2.remove((JButton)e.getSource());
this.validate();
this.repaint();
}
}
public static void main(String args[]) {
new test();
}
}
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.*;
public class test extends JFrame implements ActionListener {
JPanel contentPanel=(JPanel)this.getContentPane();
JButton jb=new JButton("add");
JPanel jp1=new JPanel(new FlowLayout());
JPanel jp2=new JPanel(new FlowLayout());
public test() {
super("myJFrame");
this.setSize(400,300);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPanel.setLayout(new BorderLayout());
contentPanel.add("North",jp1);
contentPanel.add("Center",jp2);
jp1.add(jb);
jb.addActionListener(this);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb) {
JButton jb2=new JButton("JButton"+(jp2.getComponentCount()+1));
jb2.addActionListener(this);
jp2.add(jb2);
this.validate();
} else {
jp2.remove((JButton)e.getSource());
this.validate();
this.repaint();
}
}
public static void main(String args[]) {
new test();
}
}
|
先invalidate(),在update(),记得是这么做....