ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JAVA로 원형 차트 그리기 (자바 에센셜 11장 Open Challenge)
    Study/JAVA 2021. 1. 24. 12:35

    문제

     

     - 파이 차트를 그려보자. 다음 그름과 같이 apple, cherry, strawberry, prune 4종류의 과일 판매량을 입력하면 전체 판매량에서 백분율(%)을 계산하여 문자열과 파이 차트로 동시에 출력되도록 하라. 텍스트필드 컴포넌트에 수를 입력하고 Enter 키를 누르면 Action 이벤트가 발생한다. Action 이벤트 리스너에서 백분율을 계산하고 파이 차트를 그린다.

     

     

     

    코드

     

    import javax.swing.*;

    import java.awt.event.*;

    import java.awt.*;

     

    public class PieChartFrame extends JFrame {

        Container contentPane;
        int [] data = {0,0,0,0};
        int [] arcAngle = new int [4];

        Color [] color = {Color.RED, Color.BLUE, Color.MAGENTA, Color.ORANGE};

        String [] itemName = {"apple", "cherry", "strawberry", "prune"};
        JTextField [] tf = new JTextField [4];
        ChartPanel chartPanel = new ChartPanel();

     

        PieChartFrame() {
            setTitle("Open Challenge 11");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            contentPane.add(new InputPanel(), BorderLayout.NORTH);

            contentPane.add(chartPanel, BorderLayout.CENTER);

            setSize(500,350);
            setVisible(true);
            drawChart();
        }

     

        void drawChart() {
            int sum=0;
            for(int i=0; i<data.length; i++) {

                data[i] = Integer.parseInt(tf[i].getText());

                sum+=data[i];
            }

     

            if(sum == 0) return;

            for(int i=0; i<data.length; i++) 
                arcAngle[i]=(int)Math.round((double)data[i]/(double)sum*360);

     

            chartPanel.repaint();

        }

     

        class InputPanel extends JPanel {
            InputPanel() {
                this.setBackground(Color.LIGHT_GRAY);
                for(int i=0; i<tf.length; i++) {
                    tf[i] = new JTextField("0", 5);
                    tf[i].addActionListener(new MyActionListener());
                    add(new JLabel(itemName[i]));
                    add(tf[i]);

                }

            }

     

            class MyActionListener implements ActionListener {
                public void actionPerformed(ActionEvent e) {
                    JTextField t = (JTextField)e.getSource();
                    int n;
                    try {
                        n = Integer.parseInt(t.getText());
                    }catch(NumberFormatException ex) {
                        t.setText("0");
                        return;
                    }
                    drawChart();
                }
            }
        }

     

        class ChartPanel extends JPanel {
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                int startAngle = 0;
                for(int i=0; i<data.length; i++) {
                    g.setColor(color[i]);
                    g.drawString(itemName[i]+" "+Math.round(arcAngle[i]*100./360.)+"%", 50+i*100, 20);
                }
                for(int i=0; i<data.length; i++) {
                    g.setColor(color[i]);
                    g.fillArc(150,50,200,200,startAngle, arcAngle[i]);
                    startAngle = startAngle + arcAngle[i];
                }
            }
        }

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

Designed by Tistory.