我遇到了在主方法中调用我的图形方法的挑战,以便它可以使用数组中的点绘制三角形。当我不使用数组并只使用常规数字时,绘画效果很好,但程序的想法是用户将值输入到要使用的数组中。关于如何制作三角形涂料的任何建议?这里是代码:(我有所有正确的导入)
public class Summative extends JFrame{
static int[] inpoot() {
Scanner input = new Scanner(System.in);
int[] numbers = new int[6];
System.out.println("Please enter 3 sets of coordinates:");
for (int i = 0; i < 6; i++) {
numbers[i] = input.nextInt();
}
return numbers;
}
static void outpoot(int [] numbers) {
double A = Math.sqrt (Math.pow ((numbers[4] - numbers[2]), 2) + Math.pow ((numbers[5] - numbers[3]), 2));
double B = Math.sqrt (Math.pow ((numbers[4] - numbers[0]), 2) + Math.pow ((numbers[5] - numbers[1]), 2));
double C = Math.sqrt (Math.pow ((numbers[2] - numbers[0]), 2) + Math.pow ((numbers[3] - numbers[1]), 2));
double s = (A + B + C) / 2;
double area = (Math.sqrt (s * (s - A) * (s - B) * (s - C)));
System.out.println ("The area of the triangle entered is : " + area + " units squared.");
}
public static void main(String[] args) {
int[] numbers = inpoot();
outpoot(numbers);
JFrame frame = new JFrame("Triangle");
frame.setVisible(true);
frame.setSize(new Dimension(500, 500));
JPanel panel = new myPanel();
frame.add(panel);
frame.validate();
frame.repaint();
}
}
这是图形类:
public class myPanel extends JPanel{
public void paint (int [] numbers, Graphics g) {
super.paint (g);
g.setColor (Color.BLACK);
int[] xTri = {numbers[0], numbers[2], numbers[4]};
int[] yTri = {500 - numbers[1], 500 - numbers[3], 500 - numbers[5]};
g.fillPolygon (xTri, yTri, 3);
}
}
答案 0 :(得分:0)
您需要提供一些方法将信息从main
方法传递到myPanel
课程。在您的情况下,您可以简单地提供自定义构造函数,例如......
public class myPanel extends JPanel{
private int[] xTri;
private int[] yTri;
public myPanel(int[] xTri, int[] yTri) {
this.xTri = xTri;
this.yTri = yTri;
}
public void paint (int [] numbers, Graphics g) {
super.paint (g);
g.setColor (Color.BLACK);
g.fillPolygon (xTri, yTri, xTri.length);
}
}
不要从JFrame
延伸,无论如何都要创建一个新实例,这只会让问题混乱
由于Swing的工作方式,您需要确保在Event Dispatching Thread的上下文中启动UI。所以,在你的主要方法中,你应该使用......
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// Your UI code here
}
});
并在run
方法