我是Java 2D图形的初学者,目前正在学习。
我有一个Surface
课程,扩展JPanel
,这是覆盖paintComponent
方法。这是程序应该绘制的东西。 Surface
的一个实例已添加到扩展JFrame
的其他类中。此类称为Main,它还包含main
方法。
我正在尝试将Surface调用DrawRect类中的方法,该方法将在Surface中从外部创建一个矩形。
以下是我的尝试:
// Class Main
package m;
import java.util.*;
import java.awt.*;
import java.awt.Event.*;
import javax.swing.*;
public class Main extends JFrame {
public static void main(String[] args) {
Main m = new Main();
}
public Main(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Bla");
setSize(500,500);
add(new Surface());
setVisible(true);
}
}
// Class Surface
package m;
import java.util.*;
import java.awt.*;
import java.awt.Event.*;
import javax.swing.*;
public class Surface extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// What to do here?
}
}
package m;
import java.util.*;
import java.awt.*;
import java.awt.Event.*;
import javax.swing.*;
// Class DrawRect
public class DrawRect {
String color;
Surface surface;
public DrawRect(String color, Surface surface){
this.color = color;
this.surface = surface;
}
}
换句话说,外部阶级如何在另一个阶级中吸取一些东西?感谢
答案 0 :(得分:2)
一个油漆表面是一个油漆表面。你没有合并。即使你试图重叠它们,你仍然会在一个表面上绘画。
如果您想将数据模型用于其他形状,您可以执行类似这样的操作
public class MyRetangle{
int x = 10;
int y = 10;
int width = 100;
int height = 100;
Color color = Color.RED;
}
public class Surface extends JPanel {
MyRectangle rect = new MyRectangle(); // create an instance of your other class
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(rect.color); // use data from rect
g2.draw(new Rectangle.Double(rect.x, rect.y, rect.width, rect.height));
}
}
这只是一个例子。我不知道为什么你会这样做,但你可以看到如何使用来自另一个类的数据作为绘图数据
修改:以更适合您的代码
public class DrawRect{
int y;
int y;
int height;
int width;
Color color;
public DrawRect(int x, int y, int width, int height, Color color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
}
public class Surface extends JPanel {
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
DrawRect rect = new DrawRect(20, 20, 100, 100, Color.RED);
g2.setColor(rect.color);
g2.draw(new Rectangle.Double(rect.x, rect.y, rect.width, rect.height));
}
}