【发布时间】:2014-06-22 04:18:24
【问题描述】:
我想开始为工作中的项目构建我自己的定制 JComponent。我在下面有一个简单的示例,它应该只在屏幕上创建一个球。 (我在互联网上找到了大部分内容)但它确实提供了一个不错的起点。我的问题是为什么这段代码没有在我的表格中显示球?我做错了什么?
此外,应该为自定义 JComponent 提供哪些基本方法?
代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class testBall {
public static void main(String[] args) {
new testBall();
}
public testBall() {
JPanel testPane = new JPanel();
testPane.setBackground(Color.white);
testPane.setLayout(new GridBagLayout());
testPane.add(new MyBall(30,30,10));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(testPane);
frame.pack();
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyBall extends JComponent
{
private static final long serialVersionUID = 1L;
public MyBall() { }
public MyBall(int x, int y, int diameter)
{
super();
this.setLocation(x, y);
this.setSize(diameter, diameter);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(0, 0, 100, 100);
}
}
在哪里可以找到 JComponent 类中应覆盖的所有方法的列表? (我知道有些组件应该始终包含在 JComponent 中。)
如果我在一个类中创建这个组件的一个实例,并且需要更改圆圈的颜色,我会直接从该类调用repaint() 方法吗?
【问题讨论】:
标签: java swing paintcomponent jcomponent preferredsize