从不调用PaintComponents()

时间:2013-12-12 05:50:21

标签: java swing paintcomponent

这应该是一个抽象类,可以扩展为绘制连接JPanel上某些坐标点的线。

但是,从不调用专门的PaintComponents()方法。我已经看到了其他答案并尝试使用他们的解决方案,例如检查我是否添加了JPanel或者我是否有布局。但是,PaintComponent()仍然从未被调用过,屏幕上也没有任何内容。

import java.awt.*;
import java.util.*;
import javax.swing.*;

public abstract class XYGrapher
{
private ArrayList<Coordinate> coordinates;
int xStart;
int yStart;
int width;
int height;

public class GraphPanel extends JPanel
{
    @Override
    public void paintComponents(Graphics g)
    {
        super.paintComponents(g);
        g.setColor(Color.green);
        g.drawLine(xStart, yStart + height / 2, xStart + width, yStart + height / 2);
        g.drawLine(xStart + width / 2, yStart, xStart + width / 2, yStart + height);

        g.setColor(Color.black);
        for(int i = 0; i < coordinates.size() - 1; i++)
        {
            Coordinate prev = coordinates.get(i);
            Coordinate next = coordinates.get(i + 1);

            if(prev.drawFrom() && next.drawTo())
            {
                g.drawLine((int) prev.getX(), (int) prev.getY(), (int) next.getX(), (int) next.getY());
            }
        }
    }
}

public abstract Coordinate xyStart();

public abstract double xRange();

public abstract double yRange();

public abstract Coordinate getPoint(int pointNum);

public void drawGraph(int xPixelStart, int yPixelStart, int pixelsWide, int pixelsHigh)
{
    int i = 0;

    xStart = xPixelStart;
    yStart = yPixelStart;
    width = pixelsWide;
    height = pixelsHigh;

    double X0 = xyStart().getX();
    double Y0 = xyStart().getX();

    ArrayList<Coordinate> points = new ArrayList(0);
    ArrayList<Coordinate> mapped = new ArrayList(0);

    while(getPoint(i) != null)
    {
        points.add(getPoint(i));
        i++;
    }

    for(int j = 0; j < points.size(); j++)
    {
        double X1 = points.get(j).getX();
        double Y1 = points.get(j).getY();

        boolean df = points.get(j).drawFrom();
        boolean dt = points.get(j).drawTo();

        int X = (int) (xPixelStart + (X1 - X0) * (pixelsWide / xRange()));
        int Y = (int) (yPixelStart + (Y0 + yRange() -Y1) * (pixelsHigh / yRange()));
        mapped.add(new Coordinate(X, Y, df, dt));
    }

    coordinates = mapped;

    for(int k = 0; k < coordinates.size(); k++)
    {
        Coordinate test = coordinates.get(k);
        Coordinate or = points.get(k);
        System.out.println(test.getX() + " " + test.getY());
        System.out.println(or.getX() + " " + or.getY());
    }

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(0,1)

    JPanel graph = new GraphPanel();
    graph.setLayout(new GridLayout(0, 1));

    frame.setContentPane(graph);
    frame.pack();
    frame.setVisible(true);
}
}

1 个答案:

答案 0 :(得分:2)

我认为“paintComponenents()”方法应该是“paintComponent()。”