如何在swing中动态增加组件呢??
下面是MainBorad的代码,
千成要记住要加repaint()方法
java 代码
这是CPUPanel的组件的代码
这是CPUPanel的组件的代码
- package example;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import com.swtdesigner.SwingResourceManager;
- public class CPUPanel extends JPanel {
- /**
- * Create the panel
- */
- public CPUPanel() {
- super();
- setLayout(null);
- final JLabel label = new JLabel();
- label.setIcon(SwingResourceManager.getIcon(CPUPanel.class, "/com/esri/arcgis/beans/TOC/TOCControlIconColor16x16.gif"));
- label.setForeground(new Color(128, 0, 0));
- label.setFont(new Font("宋体", Font.ITALIC, 18));
- label.setBounds(0, 0, 294, 52);
- add(label);
- label.setText("这是谁的哪个牌子的CPU??");
- final JButton button = new JButton();
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- setVisible(false);
- }
- });
- button.setText("退出");
- button.setBounds(24, 91, 99, 23);
- add(button);
- //
- }
- }
java 代码
- package example;
- import java.awt.event.ActionEvent;
- import example.CPUPanel;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- public class MainBoard extends JFrame {
- /**
- * Launch the application
- * @param args
- */
- public static void main(String args[]) {
- try {
- MainBoard frame = new MainBoard();
- frame.setVisible(true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * Create the frame
- */
- public MainBoard() {
- super();
- getContentPane().setLayout(null);
- setBounds(100, 100, 500, 375);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- final JButton button = new JButton();
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- final CPUPanel panel = new CPUPanel();
- panel.setBounds(142, 45, 230, 200);
- getContentPane().add(panel);
- ///
- repaint();
- }
- });
- button.setText("CPU的情况");
- button.setBounds(10, 10, 124, 23);
- getContentPane().add(button);
- final JButton button_1 = new JButton();
- button_1.setText("内存的情况");
- button_1.setBounds(179, 10, 99, 23);
- getContentPane().add(button_1);
- //
- }
- }