Java Swing尝试迭代列表并绘制每条线

时间:2017-04-15 14:21:39

标签: java swing repaint

我试图找出如何迭代传入的数据点并在数据点进入时在JPanel上绘制图形。开始我只是尝试迭代DataPoints列表并绘制每一行(调用重绘)。我尝试了几种方法来做到这一点,但没有运气......

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class MyPanel extends JPanel{
    protected int x1 = 0;
    protected int x2 = 0;
    protected int y1 = 0;
    protected int y2 = 0;


    public MyPanel(){
        iteratePoints();
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            JFrame frame = new JFrame();
            frame.setSize(500, 500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            frame.add(new MyPanel());

         }
      });

    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GREEN);
        System.out.println("In print");
        g.drawLine(x1, y1, x2, y2);
    };

    private void iteratePoints(){
        System.out.println("iteratepoints");
        ArrayList<DataGrid> dataList = new ArrayList<DataGrid>();
        dataList.add(new DataGrid(0,4));
        dataList.add(new DataGrid(5,14));
        dataList.add(new DataGrid(10,1));
        dataList.add(new DataGrid(15,10));
        dataList.add(new DataGrid(20,14));
        dataList.add(new DataGrid(25,1));

        for(int i = 0; i<dataList.size(); i++)
        {

            x2 = dataList.get(i).x;
            y2 = dataList.get(i).y;

            this.repaint();  
            x1 = x2;
            y1 = y2;
        }

    }

    private class DataGrid
    {
        public int x, y;
        DataGrid(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您需要遍历paintComponent()方法中的Points列表,而不是“iteratePoints()”方法。

使用您当前的方法,每个重绘都只会清除上一个绘画,只绘制一条代表您上一个x / y值的线。

另一种选择是直接绘制到BufferedImage

查看Custom Painting Approaches了解这两种方法的工作示例。