我想在工作项目中开始构建自己定制的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()
方法?
MyBall
上调用 repaint() 即可。 - matt forsytheBorderLayout
可以解决这个问题,因为BorderLayout的默认值是CENTER,这将允许组件显示。 - matt forsytheget*Size()
方法,以便布局管理器可以完成它们的工作。许多布局管理器使用最大、最小和首选大小来确定如何在容器中分配空间给其中的各个组件。如果你不实现这些方法,那么你的组件将无法与其他组件(甚至是自己)一起使用这些布局。如果你不在这些容器中使用你的组件,这可能会起作用,但这并不是真正的“正确做法”。这就是为什么你的组件不能与GridBagLayout一起使用的原因。 - matt forsythe