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();
}
}
}