我想在java中按下一个按钮来画一个圆圈。我将 System.out.println() 放在 action 方法中,以确保我的代码正常工作。println 出现,但在任何地方都没有画圆。有什么建议么?谢谢
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class CircleViewer {
public static void main(String[] args)
{
CircleComponent circle = new CircleComponent();
JButton button = new JButton("Draw");
final JPanel panel = new JPanel();
panel.add(button);
JFrame frame = new JFrame();
class addActionListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
CircleComponent component = new CircleComponent();
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);
component.setLocation(xCoord,yCoord);
component.getWidth(radius);
panel.add(component);
System.out.println("CLICKED!");
}
}
frame.add(panel);
ActionListener action = new addActionListener();
button.addActionListener(action);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
/**
This component lets the user draw a circle by clicking
a button.
*/
public class CircleComponent extends JPanel
{
private int x;
private int y;
private int width;
Ellipse2D.Double circle;
public CircleComponent()
{
circle = new Ellipse2D.Double(x, y, width, width);
}
public Dimension getPreferredSize()
{
return new Dimension(500,500);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(circle);
}
public int getWidth(int aWidth)
{
width = aWidth;
return width;
}
}