简体   繁体   English

如何在摇摆中绘制到JPanel

[英]How do I paint to a JPanel in swing

I'm writing a program in swing that uses linked nodes to store a value and then paint the value contained to a JPanel in the form of a yellow bar. 我正在编写一个使用链接节点存储值的程序,然后以黄色条的形式将包含的值绘制到JPanel中。 The painting was originally done using the AWT. 这幅画最初是使用AWT完成的。 I've read a little bit of this tutorial on painting in swing, but I still don't understand how to paint to the JPanel. 我读过一点点在秋千绘画教程,但我还是不明白怎么画到JPanel中。 The program is supposed to draw the bars when the "Random" button is pressed,but currently paints nothing. 该程序应该在按下“随机”按钮时绘制条形图,但是当前没有任何颜色。

I've included code that I believe is relevant, but let me know if you require any other parts. 我已经包含了我认为相关的代码,但如果您需要任何其他部分,请告诉我。 Thanks in advance for any help you can give me or for any tutorials you can point me to. 提前感谢您提供给我的任何帮助或任何可以指导我的教程。

public class DataOrganizer extends JPanel 
    {

        private JFrame  frame;

        protected static final Color DEFAULT_COLOR = Color.YELLOW;

        protected static final Color    HIGHLIGHT_COLOR = Color.YELLOW.darker();

        protected DataCollection<Item> collection; // To hold our items

        protected DataCollection<Item> sortedCollection;

        protected Item selected;

        private final int COLLECTION_SIZE = 10, // Maximum number of items
                MAXIMUM_ITEM_VALUE = 16; // Maximum value of an item

        private int firstItemXCoord;

        protected int   firstItemYCoord;

        /**
         * Launch the application.
         */
        public static void main(String[] args) 
        {
            EventQueue.invokeLater(new Runnable() {
                public void run()
                {
                    try
                    {
                        DataOrganizer window = new DataOrganizer();
                        window.frame.setVisible(true);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the application.
         */
        public DataOrganizer()
        {
            initialize();

        }

        /**
         * Initialize the contents of the frame.
         */
        private void initialize()
        {
            /*
             * Create and set-up the JFrame.
             */
            frame = new JFrame();
            frame.setPreferredSize(new Dimension(550, 450));
            frame.setBounds(100, 100, 600, 400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);
            frame.setVisible(true);

            /*
             * Create btnRandom and add an action listener
             * that calls randomAction().
             */
            JButton btnRandom = new JButton("Random");
            btnRandom.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    randomAction();
                }
            });
            btnRandom.setBounds(6, 18, 117, 29);
            frame.getContentPane().add(btnRandom);

            /*
             * Create btnMaximum and add an action listener
             * that calls maximumAction().
             */
            JButton btnMaximum = new JButton("Maximum");
            btnMaximum.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    maximumAction();
                }
            });
            btnMaximum.setBounds(6, 59, 117, 29);
            frame.getContentPane().add(btnMaximum);

            /*
             * Create btnMinimum and add an action listener
             * that calls minimumAction().
             */
            JButton btnMinimum = new JButton("Minimum");
            btnMinimum.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    minimumAction();
                }
            });
            btnMinimum.setBounds(6, 100, 117, 29);
            frame.getContentPane().add(btnMinimum);

            /*
             * Create btnRemove and add an action listener
             * that calls removeAction().
             */
            JButton btnRemove = new JButton("Remove");
            btnRemove.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    removeAction();
                }
            });
            btnRemove.setBounds(6, 141, 117, 29);
            frame.getContentPane().add(btnRemove);

            /*
             * Create btnSort and add an action listener
             * that calls sort().
             */
            JButton btnSort = new JButton("Sort");
            btnSort.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    sort();
                }
            });
            btnSort.setBounds(6, 182, 117, 29);
            frame.getContentPane().add(btnSort);

            /*
             * Create the JPanel, set the bounds,
             * and add it to the frame.
             */
            JPanel panel = new JPanel();
            panel.setBounds(135, 0, 465, 378);
            frame.getContentPane().add(panel);

            //Initialize the unsorted collection
            collection = new DataCollection<Item>(COLLECTION_SIZE);

            //Initialize the sorted collection
            sortedCollection = new DataCollection<Item>(COLLECTION_SIZE);

            repaint();
        }


        public void paintComponent(Graphics panel) {

            super.paintComponent(panel);

            panel.drawString("Hello World", 140 , 10);

            /*
             *  Display the Items when instantiated.
             */

            if (collection != null) 
            { 

                Item item;              
                int xCoord = firstItemXCoord;

                /*
                 * Reset the selected item to the start of the collection,
                 * ensuring it always starts at the first node
                 */
                collection.reset();

                        //While there is another node in the collection, loop through.
                while (collection.hasNext()) 
                {
                    /*
                     * Set the item to the selected node. 
                     * Which since reset() was called on the 
                     * collection, it should be the first node 
                     * in the collection. Then set the next node in the
                     * collection a the selected one.
                     */
                    item = collection.next(); 

                    /*
                     * Call the paint method in the item class
                     */
                    item.paint(panel, xCoord, firstItemXCoord);
                    xCoord += Item.OVERALL_WIDTH;
                }

            }

            /*
             *  Display the Items when instantiated.
             */

            if (sortedCollection != null) 
            { 
                Item item; 
                int xCoord = firstItemXCoord + 200;

                /*
                 * Reset the selected item to the start of the collection,
                 * ensuring it always starts at the first node
                 */
                sortedCollection.reset();

                        //While there is another node in the collection, loop through.
                while (sortedCollection.hasNext()) 
                {
                    /*
                     * Set the item to the selected node. 
                     * Which since reset() was called on the 
                     * sortedCollection, it should be the first node 
                     * in the collection. Then set the next node in the
                     * collection a the selected one.
                     */
                    item = sortedCollection.next(); 

                    /*
                     * Call the paint method in the item class
                     */
                    item.paint(panel, xCoord, firstItemXCoord);
                    xCoord += Item.OVERALL_WIDTH;
                }

            }
        }

        //
        // Random
        //
        public void randomAction() 
        {
            collection.clear(); // We restart with nothing,
            // then we add random items,
            for (int i = 1; i <= COLLECTION_SIZE; i++) 
            {
                collection.add(new Item((int) (1 + MAXIMUM_ITEM_VALUE
                        * Math.random()), DEFAULT_COLOR));
            }
            selected = null; // We make sure nothing is selected
        }

Check out Custom Painting Approaches for a couple of ways to do custom painting. 查看自定义绘画方法,了解几种自定义绘画方法

The program is supposed to draw the bars when the "Random" button is pressed,but currently paints nothing 该程序应该在按下“随机”按钮时绘制条形图,但是当前没有任何颜色

You would probably want to use the first approach of adding an object to an ArrayList so that you have a List of object to paint. 您可能希望使用第一种方法将对象添加到ArrayList,以便您有一个要绘制的对象List。 So the button would add the object to paint, then you invoke the repaint() method on the panel. 因此按钮会将对象添加到绘制中,然后在面板上调用repaint()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM