如何从JList选择中绘制矩形

时间:2016-04-25 05:46:27

标签: java jpanel drawing jlist

我正在寻找关于我正在编写的Java程序的一些帮助。我需要显示一个简单的条形图,该条形图由基于保存在由JList选择事件生成的数组中的数据的矩形组成。但是,JPanel中没有绘制任何内容,我无法弄清楚如何修复它。

  1. 列表选择事件(供参考)

    try
    {
    BufferedReader in = new BufferedReader((new FileReader("scores.txt")));
    
    String sLine;
    
    while ((sLine = in.readLine()) != null)
    {
        vecAthlete.addElement(new Stage3_DataFile(sLine));
    }
    
    String[] saAthlete = new String[vecAthlete.size()];
    for (int iI = 0; iI < vecAthlete.size(); iI++)
        saAthlete[iI] = vecAthlete.get(iI).sName;
    jList_Athlete.setListData(saAthlete);
    jList_Athlete.setSelectedIndex(0);
    
    // Reading input line by line
    // Close file
        in.close();
    }
    catch (IOException e)
    {
        System.out.println("ERROR: Could not read text file!");
    }
    jList_Athlete.addListSelectionListener(new javax.swing.event.ListSelectionListener()
    {
        public void valueChanged(javax.swing.event.ListSelectionEvent e)
        {
            double[][] daRun = new double[2][7];
    
            final double dScoreUsed = 5;
            double dMinScoreRun1 = 10, dMaxScoreRun1 = 0;
            double dMinScoreRun2 = 10, dMaxScoreRun2 = 0;
    
            double dTotalRun1 = 0, dTotalRun2 = 0;
    
            jLabel_Athlete.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sName);
            jLabel_Country.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sCountry);
    
            jLabel_Run1_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[0]);
        jLabel_Run1_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[1]);
        jLabel_Run1_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[2]);
        jLabel_Run1_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[3]);
        jLabel_Run1_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[4]);
        jLabel_Run1_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[5]);
        jLabel_Run1_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[6]);
    
        jLabel_Run2_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[0]);
        jLabel_Run2_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[1]);
        jLabel_Run2_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[2]);
        jLabel_Run2_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[3]);
        jLabel_Run2_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[4]);
        jLabel_Run2_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[5]);
        jLabel_Run2_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[6]);
    
    
        daRun[0][0] = Double.parseDouble(jLabel_Run1_Score_1.getText());
        daRun[0][1] = Double.parseDouble(jLabel_Run1_Score_2.getText());
        daRun[0][2] = Double.parseDouble(jLabel_Run1_Score_3.getText());
        daRun[0][3] = Double.parseDouble(jLabel_Run1_Score_4.getText());
        daRun[0][4] = Double.parseDouble(jLabel_Run1_Score_5.getText());
        daRun[0][5] = Double.parseDouble(jLabel_Run1_Score_6.getText());
        daRun[0][6] = Double.parseDouble(jLabel_Run1_Score_7.getText());
    
        daRun[1][0] = Double.parseDouble(jLabel_Run2_Score_1.getText());
        daRun[1][1] = Double.parseDouble(jLabel_Run2_Score_2.getText());
        daRun[1][2] = Double.parseDouble(jLabel_Run2_Score_3.getText());
        daRun[1][3] = Double.parseDouble(jLabel_Run2_Score_4.getText());
        daRun[1][4] = Double.parseDouble(jLabel_Run2_Score_5.getText());
        daRun[1][5] = Double.parseDouble(jLabel_Run2_Score_6.getText());
        daRun[1][6] = Double.parseDouble(jLabel_Run2_Score_7.getText());
    
        for(int i = 0; i < 7; i++)
        {   
            if(daRun[0][i] <= dMinScoreRun1)
            {
                dMinScoreRun1 = daRun[0][i];
            }
            if(daRun[0][i] >= dMaxScoreRun1)
            {
                dMaxScoreRun1 = daRun[0][i];
            }
    
            dTotalRun1 += daRun[0][i];
        }
    
        dTotalRun1 = (dTotalRun1 - dMinScoreRun1 - dMaxScoreRun1) / dScoreUsed;
        jLabel_TotalRun1.setText(String.valueOf(dTotalRun1));
        jLabel_Run1AddInfo.setText("Min Score: " + (dMinScoreRun1) + ", Max Score: " + (dMaxScoreRun1));
    
        for(int i = 0; i < 7; i++)
        {
            if(daRun[1][i] <= dMinScoreRun2)
            {
                dMinScoreRun2 = daRun[1][i];
            }
            if(daRun[1][i] >= dMaxScoreRun2)
            {
                dMaxScoreRun2 = daRun[1][i];
            }
    
            dTotalRun2 += daRun[1][i];
        }
    
        dTotalRun2 = (dTotalRun2 - dMinScoreRun2 - dMaxScoreRun2) / dScoreUsed;
        jLabel_TotalRun2.setText(String.valueOf(dTotalRun2));
        jLabel_Run2AddInfo.setText("Min Score: " + (dMinScoreRun2) + ", Max Score: " + (dMaxScoreRun2));
    
        if(dTotalRun1 >= dTotalRun2)
            jLabel_FinalScore.setText(String.valueOf(dTotalRun1));  
        else
            jLabel_FinalScore.setText(String.valueOf(dTotalRun2));  
    
    
        jPanel_Graph.repaint();
    }
    });
    
  2. JPanel Definitions

        JPanel jPanel_Graph = new JPanel();
    jPanel_Graph.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
    jPanel_Graph.setBounds(729, 159, 700, 200);
    frame.getContentPane().add(jPanel_Graph);
    
    img = new BufferedImage(jPanel_Graph.getWidth(),
                            jPanel_Graph.getHeight(),
                            BufferedImage.TYPE_INT_RGB);
    
    g2dimg = (Graphics2D)img.getGraphics();
    
    // Draw a filled white coloured rectangle on the entire area to clear it.
    g2dimg.setPaint(Color.WHITE);
    g2dimg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
    
  3. JPanel绘图活动

    class myJPanel extends JPanel
    {
    private Rectangle2D.Double rectangle;
    
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
    
        for(int i = 0; i < 7; i++)
        {
            dHeight = daRun[0][i];
    
            rectangle = new Rectangle2D.Double(dX, dY, dWidth, dHeight);
            g2dimg.setPaint(Color.red);
            g2dimg.draw(rectangle);
            g2dimg.fill(rectangle);
    
            dX += dXIncrement;
            g2dimg.drawImage(img, 0, 0, null);
            }
        }
    }
    
  4. 提前致谢!

1 个答案:

答案 0 :(得分:1)

所以,从我所知道的,你的“图表”无法知道它应该画什么。基本的想法是,你的“图形”应该专注于绘制数据/模型,所以你需要一些方法来告诉它何时数据发生变化。

有很多方法可以做到这一点,例如,你可以设计一个模型,你可以添加/删除数据,这可以触发图形窗格监听器的更新,然后用新数据更新自己。 / p>

或者您只需将要更新的数据直接传递到图表窗格,在这种情况下,您可以使用最简单的解决方案

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private GraphPane graphPane;

        public TestPane() {
            setLayout(new BorderLayout());
            DefaultListModel<Double> listmodel = new DefaultListModel<>();
            for (int index = 0; index < 100; index++) {
                listmodel.addElement(Math.random());
            }

            graphPane = new GraphPane();
            add(graphPane);

            JList<Double> listData = new JList<>(listmodel);
            add(new JScrollPane(listData), BorderLayout.WEST);

            listData.addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    graphPane.setData(listData.getSelectedValuesList().toArray(new Double[0]));
                }
            });
        }

    }

    public class GraphPane extends JPanel {

        private Double[] data;

        public void setData(Double[] data) {
            this.data = data;
            repaint();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (data != null && data.length > 0) {
                Graphics2D g2d = (Graphics2D) g.create();
                double barWidth = getWidth() / (double)data.length;
                int xPos = 0;
                for (Double value : data) {
                    double height = (getHeight() - 1) * value;
                    Rectangle2D bar = new Rectangle2D.Double(xPos, getHeight() - height, barWidth, height);
                    g2d.setColor(Color.GREEN);
                    g2d.fill(bar);
                    g2d.setColor(Color.BLACK);
                    g2d.draw(bar);
                    xPos += barWidth;
                }
                g2d.dispose();
            }
        }

    }

}