0

Hello forum, Vaironl here.

I believe this questions has been answered before, but I cannot find the answer.. weird.

I have a class which is called panel and extends a JPanel and a paint method.
For some reason my Jlabel is not appearing, I read common painting problems, and tried setting the JLabel to opaque... with no luck. any suggestions?

4
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by mKorbel
1

suggestion nr 1: show your code.
we can't really tell anything without having a look at it, now can we?

0

suggestion nr 1: show your code.
we can't really tell anything without having a look at it, now can we?

Sorry for that... I assumed it was just a straightforward problem.. but pardon me.

Here is the class that extends the Jpanel

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Panel extends JPanel{
	/* all drawing methods, fields, labels, and GUI components will
	Placed inside of this panel	
	 */
	public Panel()
	{
		setLayout(null);
		JLabel label = new JLabel("Hello");
		label.setOpaque(true);
		label.setSize(40,40); label.setLocation(40, 20);
		add(label);
		addMouseListener(new MouseAdapter() { 
	          public void mousePressed(MouseEvent me) { 
	            System.out.println(me); 
	          } 
	        }); 	
	    
	}
	public void paint(Graphics g)
	{
		g.setColor(Color.ORANGE);
		g.fillRect(0, 0, getWidth(), getHeight());
		g.setColor(Color.red);
		g.drawRect(0, 500, 250, 20);// Recipe's Name
		g.drawRect(0, 530, 250, 20);// Author's Name
		g.drawRect(0, 560, 250, 20);// Rating Value
		g.drawRect(0, 590, 250, 20);// Serving Size
		g.setColor(Color.BLACK);
		Graphics2D g2 = (Graphics2D) g;
		g2.setStroke(new BasicStroke(3));
		g2.drawRect(0, 40, 250, getHeight());  
		g2.drawRect(250, 700, getWidth(), getHeight());

	}
	

}
1

You've made the common mistake of overriding paint rather then paintComponent.
JPanel's paint method calls paint for all its child objects as well as calling its own paintComponent, but you have overridden it thus bypassing the calls to paint the label. Just override paintComponent instead of paint and let Swing do its work.

http://docs.oracle.com/javase/tutorial/uiswing/painting/problems.html

Edited by JamesCherrill: Added link to problem solver

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.