我想开始为工作中的项目构建自己的自定义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()方法吗?