我制作了一个绘制Polygon的程序,但Polygon没有显示出来。我正在尝试修复我的代码。
public static class Polygon extends JPanel {
public Polygon() {
setBackground(Color.black);
}
public void paintComponent(Graphics p)
{
super.paintComponent(p);
int[] list1 = {100,50,150,200};
int[] list2 = {50,100,200,150};
int n = 3;
drawAPolygon(list1,list2,n);
}
public void drawAPolygon(int[] xPoints, int[] yPoints, int numPoints){
Graphics p = getGraphics();
p.setColor(Color.yellow);
p.drawPolygon(xPoints, yPoints, numPoints);
}
}
答案 0 :(得分:2)
getGraphics()
方法不适合您。但您可以将Graphics
作为参数传递。
public static class Polygon extends JPanel {
public Polygon() {
setBackground(Color.black);
}
public void paintComponent(Graphics p)
{
super.paintComponent(p);
int[] list1 = {100,50,150,200};
int[] list2 = {50,100,200,150};
int n = 3;
drawAPolygon(p,list1,list2,n);
}
public void drawAPolygon(Graphics p, int[] xPoints, int[] yPoints, int numPoints){
p.setColor(Color.yellow);
p.drawPolygon(xPoints, yPoints, numPoints);
}
}
答案 1 :(得分:1)
我不确定为什么你有一个静态类,先改变它,然后尝试下面的建议。
我会在paintComponent方法中做所有事情。这段代码对我很好:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Polygon extends JPanel {
public void paintComponent(Graphics p)
{
super.paintComponent(p);
int[] list1 = {100,50,150,200};
int[] list2 = {50,100,200,150};
int n = 3;
p.setColor(Color.yellow);
p.drawPolygon(list1, list2, n);
}
}
这是一个带有main方法的跑步者类,所以你可以测试它:
import javax.swing.JFrame;
public class DrawPolygon {
public static void main(String[] args) {
Polygon panel = new Polygon();
JFrame frame = new JFrame();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
那种颜色不能很好地显示,也许有一种方法可以让它变厚?