你好,我正在尝试学习Java中的图形学,同时学习类和对象。我现在的目标是制作一个包含带有矩形或圆形的不同类的程序,然后我想在其他类中使用这些矩形和圆形,并更改其大小,颜色和位置等参数来绘制某种图案。
我现在的问题是我可以制作一个矩形,甚至可以再制作一个矩形,但是我无法更改其参数(颜色,大小和位置),因此我尝试将变量添加到这部分代码中Rect rect = new Rect(int variables);
,但是没有用。
通常我可以解决类似这样的简单问题,但是如果有人可以帮助我,我真的不理解类和对象在Java中的工作原理。
这是我的代码
public class Main{
public static void main(String[] args ) {
Pattern.drawPattern();
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Rect extends JPanel{
public static Color myColor = Color.RED;
public static int myX = 10;
public static int myY = 10;
public static int myWidth = 200;
public static int myHeight = 200;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(myColor);
g.fillRect(myX, myY, myWidth, myHeight);
}
}
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
public class Pattern {
public static void drawPattern() {
JFrame window = new JFrame("test");
window.setSize(1000, 800);
window.setVisible(true);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Rect rect = new Rect();
Rect rect1 = new Rect();
window.add(rect);
window.add(rect1);
Rect.myColor = Color.lightGray;
}
}
答案 0 :(得分:1)
这里有很多问题,但我能看到的主要问题是:
ArrayList<Rect>
。小测验:
例如,Rect(或在这里命名为Rect2,以表明它与您的课程有所不同)可能类似于:
// imports here
public class Rect2 {
private Color myColor = Color.RED;
private int x = 10;
private int y = x;
private int width = 200;
private int height = width;
public Rect2() {
// default constructor
}
public Rect2(Color myColor, int x, int y, int width, int height) {
this.myColor = myColor;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
// method used to allow the rectangle to be drawn
public void draw(Graphics g) {
g.setColor(myColor);
g.fillRect(x, y, width, height);
}
public void setMyColor(Color myColor) {
this.myColor = myColor;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
// more setters and some getters if need be
}
和绘图JPanel类似:
// imports here
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private List<Rect2> rectList = new ArrayList<>();
// ..... more code
public void addRect2(Rect2 rect) {
rectList.add(rect);
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// iterate through the rectList and draw all the Rectangles
for (Rect2 rect : rectList) {
rect.draw(g);
}
}
// ...... more code
}
它可以像这样放入JFrame中。...
Rect2 rectA = new Rect2();
Rect2 rectB = new Rect2();
rectB.setMyColor(Color.BLUE);
rectB.setX(300);
rectB.setY(300);
// assuming that the class's constructor allows sizing parameters
DrawingPanel drawingPanel = new DrawingPanel(1000, 800);
drawingPanel.addRect2(rectA);
drawingPanel.addRect2(rectB);
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(drawingPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);