Hi,

I have a problem repainting Jpanel. I wrote a simple code just to check whether it works, but notnihg is happening. Function initPanelAnswer should initialize answer panel with some image, but I wanted to make it more simply. So, according to my logic, this should print out "Paint Component", after I create instance of this class somewhere else. Where am I wrong?

Thanks,
Vuchko

public class PanelAnswer extends JPanel {
	
	private JPanel answer;
	
	public PanelAnswer(){
		answer = new JPanel();
		initPanelAnswer();
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		System.out.println("Paint Component");		
	}

	private void initPanelAnswer(){
		repaint();
	}
	
	public JPanel getPanel(){
		return answer;
	}
	
}

Maybe its smart enough to realise that repainting an uninitialised unpopulated invisible panel is unnecessary?
ps: What's the point of answer = new JPanel... don't you want an instance of PanelAnswer?

I wanted to add this panel (answer) on JFrame, and then depending on user's action, I'll repaint this answer panel. So I did it like this. Maybe, this is not a best solution, I'll try something different, but why this isn't working, I'm confused where I did it wrong.

You have a class PanelAnswer with overrides for paintComponent, but you don't do much to create one. I still don't see why you create an unrelated JPanel when you call the constructor for PanelAnswer unless you intend to use it as a container, in which something more like this should work:

public PanelAnswer(){
    JFrame jf = new JFrame("Hello");
    jf.add(this);
    this.add(new JLabel("Hello"));
    jf.pack();
    jf.setVisible(true);
    // initPanelAnswer();
}

Yes, that solved problem. I didn't realize that I dont need private member answer at all. Thank you very much, and thanks for your quick replies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.