您需要覆盖getPreferredSize()
您自定义组件的方法。默认情况下,大小为 (0, 0),因此无需绘制任何内容。
revalidate() 应该在面板上完成,而不是在组件上完成。
您的 getX() 和 getY() 方法没有任何意义。如果您想在面板上定位组件,您应该使用组件的 setLocation(...) 方法。
Edit:
还有很多问题。我将尝试解释它们,然后给出一个更好(仍然不是很好)的示例来说明如何做到这一点。
circle = new Ellipse2D.Double(x, y, width, width);
创建圆形时,所有参数的值为 0,因此无需绘制任何内容。您不能仅稍后更改变量 x、y 和 width 的值并期望圆反映这些值。
组件的尺寸错误。您不能只制作 500 x 500 的任意尺寸。首选尺寸应该是圆的尺寸。
您不能只将组件添加到面板中,因为面板默认使用 FlowLayout。这意味着 setLocation() 方法将被忽略。我更改了您的代码以使用空布局。这意味着现在将使用您指定的位置,并且您还必须指定组件的大小。
我更改了您的代码以对 ActionListener 使用“匿名内部类”。这比在另一个类的中间定义一个类更常见。
这是一个简单的例子:
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
public class CircleComponent extends JPanel
{
Ellipse2D.Double circle;
public CircleComponent(int radius)
{
circle = new Ellipse2D.Double(0, 0, radius, radius);
setOpaque(false);
}
public Dimension getPreferredSize()
{
Rectangle bounds = circle.getBounds();
return new Dimension(bounds.width, bounds.height);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor( getForeground() );
g2.fill(circle);
}
/*
public int getWidth(int aWidth)
{
width = aWidth;
return width;
}
*/
public static void main(String[] args)
{
// Create a panel using a null layout so we can add components at random positions
final JPanel center = new JPanel();
center.setLayout(null);
JButton button = new JButton("Draw");
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String x = JOptionPane.showInputDialog("X Coordinate", "Enter an x coordinate");
int xCoord = Integer.parseInt(x);
String y = JOptionPane.showInputDialog("Y Coordinate", "Enter a y coordinate");
int yCoord = Integer.parseInt(y);
String width = JOptionPane.showInputDialog("Radius", "Enter the length of the radius");
int radius = Integer.parseInt(width);
CircleComponent component = new CircleComponent(radius);
component.setLocation(xCoord,yCoord);
component.setSize(component.getPreferredSize());
center.add(component);
center.repaint();
}
});
JFrame frame = new JFrame();
frame.add(center, BorderLayout.CENTER);
frame.add(button, BorderLayout.NORTH);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}