Bubble sort animation

后端 未结 2 931
Happy的楠姐
Happy的楠姐 2021-01-16 21:27

Lately I\'ve noticed questions asking about animation of code that uses a looping algorithm. For example:

  1. Java: How to use swing timer for delaying actions
2条回答
  •  孤城傲影
    2021-01-16 22:07

    A Swing Timer works on event driven code. Therefore the iterative code must be refactored to event driven code.

    Some things to consider during this process:

    1. state must be added to the algorithm. This means that all local variables used to control the looping algorithm must be converted to instance variables of the class.

    2. the looping algorithm must be split into two methods, the first to set the initial state of the algorithm and start the timer, and the second method to update the state and stop the Timer.

    Using the above suggestion the refactoring of your code might be something like:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class BubbleSortTimer extends JPanel
    {
        private final static int BAR_WIDTH = 30;
        private final static int BAR_HEIGHT_MAX = 400;
    
        private int[]items;
        private int i, j, n;
        private Timer timer;
    
        public BubbleSortTimer(int[] items)
        {
            this.items = items;
    
            timer = new Timer(100, (e) -> nextIteration());
        }
    
        public void setItems(int[] items)
        {
            this.items = items;
            repaint();
        }
    
        public void sort()
        {
            i = 0;
            j = 1;
            n = items.length;
    
            timer.start();
        }
    
        public void nextIteration()
        {
            if (items[j - 1] > items[j])
            {
                int temp = items[j - 1];
                items[j - 1] = items[j];
                items[j] = temp;
    
                repaint();
            }
    
            j++;
    
            if (j >= n - i)
            {
                j = 1;
                i++;
            }
    
            if (i == n)
                timer.stop();
        }
    
        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
    
            for (int i = 0; i < items.length; i++)
            {
                int x = i * BAR_WIDTH;
                int y = getHeight() - items[i];
    
                g.setColor( Color.RED );
                g.fillRect(x, y, BAR_WIDTH, items[i]);
    
                g.setColor( Color.BLUE );
                g.drawString("" + items[i], x, y);
            }
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return new Dimension(items.length * BAR_WIDTH, BAR_HEIGHT_MAX + 20);
        }
    
        public static int[]generateRandomNumbers()
        {
            int[] items = new int[10];
    
            for(int i = 0; i < items.length; i++)
            {
                items[i] = (int)(Math.random() * BubbleSortTimer.BAR_HEIGHT_MAX);
            }
    
            return items;
        }
    
        private static void createAndShowGUI()
        {
            BubbleSortTimer bubbleSort = new BubbleSortTimer( BubbleSortTimer.generateRandomNumbers() );
    
            JButton generate = new JButton("Generate Data");
            generate.addActionListener((e) -> bubbleSort.setItems( BubbleSortTimer.generateRandomNumbers() ) );
    
            JButton sort = new JButton("Sort Data");
            sort.addActionListener((e) -> bubbleSort.sort());
    
            JPanel bottom = new JPanel();
            bottom.add( generate );
            bottom.add( sort );
    
            JFrame frame = new JFrame("SSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(bubbleSort, BorderLayout.CENTER);
            frame.add(bottom, BorderLayout.PAGE_END);
            frame.pack();
            frame.setLocationByPlatform( true );
            frame.setVisible( true );
        }
    
        public static void main(String[] args) throws Exception
        {
            EventQueue.invokeLater( () -> createAndShowGUI() );
        }
    }
    

提交回复
热议问题