HOME       >>       Programming

Custom Jpanel Class Does Not Show When Instantiated


Jeune

Here's a class I made,

import javax.swing.JPanel;import java.awt.Graphics; public class customPanel extends JPanel{ public void paintComponent(Graphics g) { super.paintComponent(g); g.fillOval(50,10,60,60); }}


when I instantiate that here....

import javax.swing.JPanel;import javax.swing.JFrame;import java.awt.BorderLayout;import javax.swing.JButton;import java.awt.FlowLayout; public class draw extends JFrame{ public draw() { super("Draw Demo"); setLayout(new BorderLayout()); customPanel drawPanel= new customPanel(); FlowLayout southFlowLayout = new FlowLayout(); add(drawPanel,BorderLayout.SOUTH); } public static void main(String args[]) { draw app = new draw(); app.setSize(300,300); app.setVisible(true); }}


...I don't see the circle. How come?

However when I do this...

import javax.swing.JPanel;import java.awt.Graphics;import javax.swing.JFrame;import java.awt.GridLayout;public class customPanel extends JPanel{ public void paintComponent(Graphics g) { super.paintComponent(g); g.fillOval(50,10,60,60); } public static void main(String args[]) { JFrame app = new JFrame(); app.setLayout(new GridLayout(3,1)); customPanel drawPanel = new customPanel(); app.add(drawPanel); app.setSize(300,300); app.setVisible(true); }}

The circle shows up!

BhajunSingh

The reason it shows up in the second one is because it has a give height: 300. In your first example, the JPanel doesn't, and for some reason the SOUTH area in BorderLayout does not tend to show components without a specified height.So, you could keep the first example by either adding something like drawPanel.setPreferredSize(new Dimension(300, 100)); or using BorderLayout.CENTER instead.


Jeune

The reason it shows up in the second one is because it has a give height: 300. In your first example, the JPanel doesn't, and for some reason the SOUTH area in BorderLayout does not tend to show components without a specified height.
So, you could keep the first example by either adding something like drawPanel.setPreferredSize(new Dimension(300, 100)); or using BorderLayout.CENTER instead.


Ok, so it does work. But I don't get it. Why? How?


VIEW DESKTOP VERSION REGISTERGET FREE HOSTING

Xisto.com offers Free Web Hosting to its Members for their participation in this Community. We moderate all content posted here but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 2001-2019 by Xisto Corporation. All Rights Reserved.