Results 1 to 2 of 2
- 01-07-2012, 04:20 AM #1
Member
- Join Date
- Jan 2012
- Posts
- 3
- Rep Power
- 0
Why won't this rectangle display in my JFrame?
Why won't this rectangle appear on the content pane when I run the file?
Main Class:
package drawing;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args){
JFrame frame = new JFrame();
MyDrawPanel rect = new MyDrawPanel();
frame.getContentPane().add(rect);
frame.setVisible(true);
frame.setSize(300, 300);
}
}
MyDrawPanel class:
package drawing;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
class MyDrawPanel extends JPanel{
public void paintComponents(Graphics g){
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
- 01-07-2012, 07:14 AM #2
Senior Member
- Join Date
- Jul 2009
- Posts
- 1,143
- Rep Power
- 5
Re: Why won't this rectangle display in my JFrame?
The method to override should be paintComponent() (without the "s").
When overriding a method your code should be:
This way you will get a compile error if you have a typing mistake like this.Java Code:@Override public void paintComponent(Graphics g)
Also, your code works because you are adding the panel to the center of the frame, but it will not work if you add it to the NORTH of the BorderLayout. When doing custom painting you need to:
a) invoke super.paintComponent(...) at the start of the method
b) override the getPreferredSize() method to return the preferred size of the panel so the layout manager can do its job.
Similar Threads
-
Second JFrame won't display as I intend
By elnbado in forum AWT / SwingReplies: 0Last Post: 03-08-2011, 12:45 PM -
Display output in Jframe or JPanel
By rammurugesan in forum AWT / SwingReplies: 12Last Post: 04-14-2009, 01:45 PM -
can display image in JFrame?
By xCLARAx in forum AWT / SwingReplies: 14Last Post: 04-03-2009, 07:02 PM -
Right-clicking a rectangle on a JFrame to remove it
By busdude in forum New To JavaReplies: 4Last Post: 02-20-2009, 02:44 AM -
Unable to display JDialog from JFrame
By jv5 in forum NetBeansReplies: 2Last Post: 02-04-2009, 04:33 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks