请教各位大侠:如何实现在panel中显示不同颜色的圆
发布网友
发布时间:2023-10-10 04:10
我来回答
共1个回答
热心网友
时间:2023-09-18 03:15
简单的说就是重新Jpanel的paint方法,然后用参数Graphics对象的fillOval方法画圆,修改数组后调用repaint即可。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final PaintingPanel panel = new PaintingPanel();
frame.add(panel, BorderLayout.CENTER);
JPanel control = new JPanel(new FlowLayout(FlowLayout.CENTER));
final JTextField xField = new JTextField(5), yField = new JTextField(5);
final JTextField sizeField = new JTextField(5);
final JComboBox combo = new JComboBox(
new Color[] { Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN, }
);
JButton button = new JButton("Add");
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
panel.addCircle(new Circle(
Integer.parseInt(xField.getText()),
Integer.parseInt(yField.getText()),
Integer.parseInt(sizeField.getText()),
(Color) combo.getSelectedItem()
));
panel.repaint();
} catch (Exception ex) {}
}
});
control.add(xField);
control.add(yField);
control.add(sizeField);
control.add(combo);
control.add(button);
frame.add(control, BorderLayout.SOUTH);
frame.setBounds(100, 100, 600, 400);
frame.setVisible(true);
}
static class PaintingPanel extends JPanel {
ArrayList<Circle> circles = new ArrayList<Circle>();
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Circle circle : circles) {
g.setColor(circle.color);
g.fillOval(circle.x - circle.radius,
circle.y - circle.radius,
circle.radius * 2,
circle.radius * 2);
}
}
public void addCircle(Circle c) {
circles.add(c);
}
}
static class Circle {
int x, y, radius;
Color color;
Circle(int x, int y, int r, Color c) {
this.x = x;
this.y = y;
radius = r;
color = c;
}
}
}