在面板中使用两个不同的类进行绘制可以通过以下步骤实现:
以下是一个示例代码,演示如何在面板中使用两个不同的类进行绘制:
import javax.swing.*;
import java.awt.*;
class Rectangle {
public void draw(Graphics g) {
g.drawRect(50, 50, 100, 50);
}
}
class Circle {
public void draw(Graphics g) {
g.drawOval(150, 150, 50, 50);
}
}
class DrawingPanel extends JPanel {
private Rectangle rectangle;
private Circle circle;
public DrawingPanel() {
rectangle = new Rectangle();
circle = new Circle();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
rectangle.draw(g);
circle.draw(g);
}
}
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Drawing Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawingPanel panel = new DrawingPanel();
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
在这个示例中,我们创建了一个Rectangle
类和一个Circle
类,分别用于绘制矩形和圆形。然后,在DrawingPanel
类中,我们实例化了这两个类的对象,并在paintComponent
方法中调用它们的绘制方法来绘制图形。最后,我们将DrawingPanel
添加到一个JFrame
中,并显示出来。
这样,当程序运行时,就会在面板中同时显示一个矩形和一个圆形。你可以根据实际需求,修改绘制的图形和元素,以及它们的位置和大小。
领取专属 10元无门槛券
手把手带您无忧上云