Component in JPanel in JFrame
I made my own Component, named it 'hi' and put it in a JPanel and then put that JPanel into a JFrame, but nothing shows up. I made a border around JPanel to see if JPanel is even on the JFrame and sure enough, it is there, but my Component ( which by the way draws arcs) isn't on the JPanel.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
testComponent hi = new testComponent();
panel.add(hi);
frame.add(panel);
panel.setBorder(BorderFactory.createLineBorder(Color.red));
开发者_开发百科 frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Thats what i have in the main, which is the basically the only thing in my test class. The testComponent() just has a paintComponent() that draws.
and the Component
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.draw(new Arc2D.Double(100,100,100,100,0,30,Arc2D.PIE));
g2.fill(new Arc2D.Double(100,100,100,100,30,330,Arc2D.PIE));
}
Like to note that, things like JButton, JTextField, etc. These work dandy in the JPanel
Try this code:
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
public class PaintComponent extends JPanel
{
public PaintComponent()
{
setPreferredSize(new Dimension(400,400));
}
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
g2d.draw(new Arc2D.Double(100,100,100,100,0,30,Arc2D.PIE));
g2d.fill(new Arc2D.Double(100,100,100,100,30,330,Arc2D.PIE));
}
}
==============================================================================
import javax.swing.*;
import java.awt.*;
public class MainClass
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
PaintComponent hi = new PaintComponent();
panel.add(hi);
frame.add(panel);
panel.setBorder(BorderFactory.createLineBorder(Color.red));
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
Your component probably does not have preferred size set. Because of that is shows up with zero width and height. You have to at least implement the method getPreferredSize to return appropriate preferred size.
精彩评论