重新粉刷另一个JPanel里面的JPanel

时间:2012-08-09 05:23:20

标签: java swing jpanel

事情就是这样:

public class ParentPanel extends JPanel{
    private ChildPanel childPanel;
    public ParentPanel() {
        super();
        initComponents();
    }
    public void pushData(int data){
        childPanel.pushData(data);
    }
    private void initComponents() {
        childPanel= new ChildPanel();
}

我有另一个班级:

public class ChildPanel extends JPanel{
    public ChildPanel(){
        super();
    }
    public void paintComponent(Graphics g){
        //I draw some lines in this JPanel according to data
    }
    public void pushData(int data){
        repaint();
    }
}

我想要的是在调用ChildPanel中的pushData()方法时绘制一些行。但现在ChildPanel内部没有响应。我该怎么办?

1 个答案:

答案 0 :(得分:5)

childPanel不是任何容器的一部分,它的paintComponent不会被调用。尝试将其作为孩子添加到ParentPanel,即在initComponents调用add(childPanel)内。

编辑:基于已发布代码的示例

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestChild {
    public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final ParentPanel parent = new ParentPanel();
        JButton button = new JButton("Push");
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                parent.pushData(7);
            }
        });

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        panel.add(parent, BorderLayout.CENTER);
        panel.add(button, BorderLayout.SOUTH);

        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    public static class ParentPanel extends JPanel {
        private ChildPanel childPanel;

        public ParentPanel() {
            super();
            initComponents();
        }

        public void pushData(int data) {
            childPanel.pushData(data);
        }

        private void initComponents() {
            childPanel = new ChildPanel();
            add(childPanel);
        }
    }

    public static class ChildPanel extends JPanel {
        private Random random = new Random();

        public ChildPanel() {
            super();
            setPreferredSize(new Dimension(200, 200));
        }

        @Override
        public void paintComponent(Graphics g) {
            System.out.println(getWidth());
            g.setColor(getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(Color.getHSBColor(random.nextFloat(), 0.9f, 1.0f));
            g.fillOval(0, 0, getWidth(), getHeight());
        }

        public void pushData(int data) {
            repaint();
        }
    }
}