JFrame 中 JPanel 中的组件
我制作了自己的组件,将其命名为“hi”并将其放入 JPanel 中,然后将该 JPanel 放入 JFrame 中,但没有显示任何内容。我在 JPanel 周围做了一个边框,看看 JPanel 是否在 JFrame 上,果然,它在那里,但我的组件(顺便说一下,它绘制弧线)不在 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);
这就是我的主要内容,这基本上是我的测试类中唯一的东西。 testComponent() 只有一个 PaintComponent() 可以绘制。
和组件
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));
}
需要注意的是,像 JButton、JTextField 等这样的东西。这些在 JPanel 中工作得很好
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个代码:
================================================ ==================================
Try this code:
==============================================================================
您的组件可能没有设置首选尺寸。因此,显示的宽度和高度为零。您至少必须实现方法 getPreferredSize 返回适当的首选尺寸。
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.