Java Swing需要40%-70%的CPU

时间:2017-05-26 21:13:07

标签: java performance swing paint cpu-usage

Swing在i7中需要70%的Intel CPU

我有两个组件类覆盖了public void paint(Graphics g)方法 类:

package com.niton.UI.comps.draggrafix;
import com.niton.usagecomps.draglogic.basic.DragItem;

public abstract class DragItemComp extends JPanel {
    private static final long serialVersionUID = -5963637215146534947L;
    private  DragItem item;
    /**
     * Height of the content
     */
    private int dragHeight = 50;
    /**
     * Height of the header
     */
    private int topHeight = 23;
    /**
     * width of the content
     */
    private int contentSize = 300;
    /**
     * the width of the bar
     */
    private int barWidth = 20;
    private int oldX;
    private int oldY;
    private Rectangle blueBtn = new Rectangle(0, 0, barWidth, topHeight);
    private Rectangle redBtn = new Rectangle(contentSize+barWidth, 0, barWidth, topHeight);
    private Rectangle namespace = new Rectangle(barWidth, 0, contentSize, topHeight);
    private ArrayList<ConnectPoint> redPossible = new ArrayList<>();
    private ArrayList<ConnectPoint> bluePossible = new ArrayList<>();
    private ArrayList<ConnectPoint> redVisible = new ArrayList<>();
    private ArrayList<ConnectPoint> blueVisible = new ArrayList<>();
    private ArrayList<ConnectPoint> actual;
    private Font f;
    private Color contentColor = new Color(getMainColor().getRGB()-50);
    public Dimension neededSize = new Dimension(barWidth*2+contentSize, dragHeight+topHeight);
    private MouseAdapter butListener = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if(blueBtn.contains(e.getPoint()))
                actual = bluePossible;
            else if (redBtn.contains(e.getPoint()))
                actual = redPossible;
            else{
                //TODO do something
                return;
            }
            if(possibleList != null && possibleList.isVisible())
                possibleList.dispose();
            possibleList = new JFrame();
            possibleList.setAlwaysOnTop(true);
            possibleList.setType(Type.UTILITY);
            possibleList.getContentPane().setBackground(Color.LIGHT_GRAY);
            int height = 8;
            for (ConnectPoint connectPoint : actual) {
                connectPoint.setLocation(15, height);
                possibleList.getContentPane().add(connectPoint);
                height += connectPoint.getHeight()+8;
                possibleList.getContentPane().add(new JSeparator());
            }
            possibleList.setLocation(e.getLocationOnScreen());
            possibleList.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    possibleList.dispose();
                }
            });
            possibleList.setSize(200, height);
            possibleList.setUndecorated(true);
            possibleList.setVisible(true);
            actual = null;
            setPreferredSize(neededSize);
        }
    };
    public JFrame possibleList;
    public DragItemComp() {
        setBackground(new Color(0, 0, 0, 0));
        createComps();
        addMouseListener(butListener);
        f = new Font(getFont().getFontName(), Font.BOLD, 14);
    }
    public void createComps(){
        removeAll();
        int h = 0;
        for (ConnectPoint connectPoint : blueVisible) {
            connectPoint.setLocation(0, h);
            h += connectPoint.getHeight()+6; 
        }
    }
    public void onMove(){
        if(possibleList == null || !possibleList.isVisible()){
            System.out.println("Frame == null");
            return;
        }
        if(oldX == 0 && oldY== 0 ){
            oldX = getLocationOnScreen().x;
            oldY = getLocationOnScreen().y;
        }
        int tomoveX = getLocationOnScreen().x-oldX;
        int tomoveY = getLocationOnScreen().y-oldY;
        Point newPoint = possibleList.getLocation();
        newPoint.translate(tomoveX, tomoveY);
        possibleList.setLocation(newPoint);
        possibleList.repaint();
        System.gc();
        oldX = getLocationOnScreen().x;
        oldY = getLocationOnScreen().y;
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        /*Blue Button*/
        g.setColor(Color.BLUE);
        g.fillRect(0, 0, barWidth, topHeight);
        /*Blue Button*/

        /*NameBar*/
        g.setColor(getMainColor());
        g.fillRect(barWidth, 0, contentSize, topHeight);
        /*nameBar*/

        /*red Button*/
        g.setColor(Color.RED);
        g.fillRect(contentSize+barWidth, 0, barWidth, topHeight);
        /*Red Button*/

        /*Content*/
        g.setColor(contentColor);
        g.fillRect(barWidth, topHeight, contentSize, dragHeight);
        /*Content*/

        /*Title*/
        g.setColor(Color.BLACK);
        g.setFont(f);
        int textSize = 14*getTitle().length(); 
        g.drawString(getTitle(), ((contentSize+(2*barWidth))/2)-(textSize/3), 15);
        /*Title*/

        /*Blue Sidebar*/
        g.setColor(Color.BLUE.darker().darker());
        g.fillRect(0, topHeight, barWidth, dragHeight);
        /*Blue Sidebar*/

        /*Red Bar*/
        g.setColor(Color.red.darker().darker());
        g.fillRect(barWidth+contentSize, topHeight, barWidth, dragHeight);
        /*Red Sidebar*/
        //SIZE
        neededSize = new Dimension(barWidth*2+contentSize, dragHeight+topHeight);
        setPreferredSize(neededSize);
        System.gc();
    }
    public abstract Color getMainColor();
    public abstract String getTitle();
    public class ConnectPoint extends JPanel{
        private static final long serialVersionUID = -6834760334640389791L;
        boolean out = true;
        String text;
        private Font f; 
        public ConnectPoint(String text,Runnable onClick)
        {
            this.text = text;
            setSize(text.length()*getFont().getSize()+20, 15);
            setBackground(new Color(0, 0, 0, 0));
            addMouseListener(new MouseAdapter(){
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println("Click");
                    new Thread(onClick).start();
                    DragItemComp.this.redPossible.remove(this);
                    DragItemComp.this.redVisible.add(ConnectPoint.this);
                }
            });
            addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
                        getParent().setVisible(false);
                }
            });
            f = new Font(getParent().getFont().getFontName(), getFont().getStyle(), 12);
        }
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            if(out)
                g.setColor(Color.RED);
            else
                g.setColor(Color.BLUE);
            g.fillOval(0, 0, 10, 10);
            g.setColor(Color.BLACK);
            g.setFont(f);
            g.drawString(text, 15, 11);
        }
        @Override
        public boolean isFocusable() {
            return true;
        }
        @Override
        public boolean isFocusTraversable() {
            return true;
        }
    }
}

我知道这是很多代码而且很抱歉 我很长时间以来都试图解决这个问题 在这段时间里,我发现了一些有趣的东西 我认为泄漏是在这个类中:

public class JavaScriptDropFileComponent extends JPanel {
    private static final long serialVersionUID = 3535239632114792374L;
    private DragJavaScriptFile file;
    private String project;
    private DragItem nextPlace;
    private DragItem selected;
    protected JFrame placeFrame;
    public JavaScriptDropFileComponent() {
        setLayout(new GridLayout(0, 1, 0, 0));
        placeFrame = new JFrame();
        placeFrame.getContentPane().setLayout(new FlowLayout());
        placeFrame.setUndecorated(true);
        placeFrame.setOpacity(0.5F);
        placeFrame.getContentPane().setBackground(new Color(0, 0, 0, 0));
        placeFrame.setType(Type.UTILITY);
        placeFrame.setVisible(true);
        placeFrame.setAlwaysOnTop(true);
        JSplitPane splitPane = new JSplitPane();
        add(splitPane);

        JPanel panel = new JPanel();
        panel.setBackground(Color.BLACK);
        splitPane.setLeftComponent(panel);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[]{0, 0};
        gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
        gbl_panel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
        gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
        panel.setLayout(gbl_panel);

        JLabel lblComponents = new JLabel("Components");
        lblComponents.setForeground(Color.LIGHT_GRAY);
        lblComponents.setFont(new Font("Roboto Light", Font.PLAIN, 24));
        GridBagConstraints gbc_lblComponents = new GridBagConstraints();
        gbc_lblComponents.anchor = GridBagConstraints.NORTH;
        gbc_lblComponents.insets = new Insets(0, 0, 5, 0);
        gbc_lblComponents.gridx = 0;
        gbc_lblComponents.gridy = 0;
        panel.add(lblComponents, gbc_lblComponents);

        JPanel panel_2 = new JPanel();
        panel_2.setBorder(new LineBorder(Color.WHITE, 1, true));
        panel_2.setBackground(Color.DARK_GRAY);
        GridBagConstraints gbc_panel_2 = new GridBagConstraints();
        gbc_panel_2.fill = GridBagConstraints.HORIZONTAL;
        gbc_panel_2.anchor = GridBagConstraints.NORTH;
        gbc_panel_2.insets = new Insets(0, 0, 5, 0);
        gbc_panel_2.gridx = 0;
        gbc_panel_2.gridy = 2;
        panel.add(panel_2, gbc_panel_2);
        panel_2.setLayout(new GridLayout(0, 1, 0, 0));

        JLabel lblIfelse = new JLabel("If/Else");
        panel_2.add(lblIfelse);
        lblIfelse.setBorder(new LineBorder(Color.LIGHT_GRAY));
        lblIfelse.setFont(new Font("SansSerif", Font.PLAIN, 23));
        lblIfelse.setForeground(Color.WHITE);

        JButton btnIfCondrtion = new JButton("If Condrtion");
        btnIfCondrtion.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                nextPlace = new BasicIfCondition();
                placeFrame.getContentPane().removeAll();
                DragItemComp c = nextPlace.getComponent();
                c.setLocation(0, 0);
                c.setSize(c.getPreferredSize());
                placeFrame.getContentPane().add(c);
                placeFrame.setSize(0,0);
            }
        });
        btnIfCondrtion.setSelected(true);
        panel_2.add(btnIfCondrtion);

        JButton btnCompareCondition = new JButton("Compare Condition");
        btnCompareCondition.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                nextPlace = new CompairCondition();
                placeFrame.getContentPane().removeAll();
                DragItemComp c = nextPlace.getComponent();
                c.setLocation(0, 0);
                c.setSize(c.getPreferredSize());
                placeFrame.getContentPane().add(c);
                placeFrame.setSize(0,0);
            }
        });
        panel_2.add(btnCompareCondition);

        Button btnFunctionCondition = new Button((String) null);
        btnFunctionCondition.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnFunctionCondition.setText("Function Condition");
        panel_2.add(btnFunctionCondition);

        JButton btnCombinedCondition = new JButton("Combined Condition");
        btnCombinedCondition.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) 
            {
                nextPlace = new CombinorCondition();
                placeFrame.getContentPane().removeAll();
                DragItemComp c = nextPlace.getComponent();
                c.setLocation(0, 0);
                c.setSize(c.getPreferredSize());
                placeFrame.getContentPane().add(c);
                placeFrame.setSize(0,0);
            }
        });
        panel_2.add(btnCombinedCondition);

        JPanel panel_3 = new JPanel();
        panel_3.setBorder(new LineBorder(Color.WHITE, 1, true));
        panel_3.setBackground(Color.DARK_GRAY);
        GridBagConstraints gbc_panel_3 = new GridBagConstraints();
        gbc_panel_3.fill = GridBagConstraints.HORIZONTAL;
        gbc_panel_3.insets = new Insets(0, 0, 5, 0);
        gbc_panel_3.anchor = GridBagConstraints.NORTH;
        gbc_panel_3.gridx = 0;
        gbc_panel_3.gridy = 3;
        panel.add(panel_3, gbc_panel_3);
        panel_3.setLayout(new GridLayout(0, 1, 0, 0));

        JLabel lblGlobal = new JLabel("Global");
        panel_3.add(lblGlobal);
        lblGlobal.setBorder(new LineBorder(Color.WHITE));
        lblGlobal.setFont(new Font("SansSerif", Font.PLAIN, 23));
        lblGlobal.setForeground(Color.WHITE);

        JButton btnFunction = new JButton("Function");
        btnFunction.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                nextPlace = new JavaScriptFunktion();
                placeFrame.getContentPane().removeAll();
                DragItemComp c = nextPlace.getComponent();
                c.setLocation(0, 0);
                c.setSize(c.getPreferredSize());
                placeFrame.getContentPane().add(c);
                placeFrame.setSize(0,0);
            }
        });
        panel_3.add(btnFunction);

        JButton btnEvent = new JButton("Event");
        btnEvent.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                nextPlace = new EventItem();
                placeFrame.getContentPane().removeAll();
                DragItemComp c = nextPlace.getComponent();
                c.setLocation(0, 0);
                c.setSize(c.getPreferredSize());
                placeFrame.getContentPane().add(c);
                placeFrame.setSize(0,0);
            }
        });
        panel_3.add(btnEvent);

        JButton btnValue = new JButton("Value");
        btnValue.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        panel_3.add(btnValue);

        JButton btnVariable = new JButton("Variable");
        btnVariable.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                nextPlace = new JavaScriptVariable();
                placeFrame.getContentPane().removeAll();
                DragItemComp c = nextPlace.getComponent();
                c.setLocation(0, 0);
                c.setSize(c.getPreferredSize());
                placeFrame.getContentPane().add(c);
                placeFrame.setSize(0,0);
            }
        });
        panel_3.add(btnVariable);

        JPanel panel_4 = new JPanel();
        panel_4.setBorder(new LineBorder(Color.WHITE, 1, true));
        panel_4.setBackground(Color.DARK_GRAY);
        GridBagConstraints gbc_panel_4 = new GridBagConstraints();
        gbc_panel_4.fill = GridBagConstraints.HORIZONTAL;
        gbc_panel_4.insets = new Insets(0, 0, 5, 0);
        gbc_panel_4.anchor = GridBagConstraints.NORTH;
        gbc_panel_4.gridx = 0;
        gbc_panel_4.gridy = 4;
        panel.add(panel_4, gbc_panel_4);
        panel_4.setLayout(new GridLayout(0, 1, 0, 0));

        JLabel lblActions = new JLabel("Actions");
        panel_4.add(lblActions);
        lblActions.setForeground(Color.WHITE);
        lblActions.setFont(new Font("SansSerif", Font.PLAIN, 23));
        lblActions.setBorder(new LineBorder(Color.WHITE));

        JButton btnChangeVariable = new JButton("Change Variable");
        btnChangeVariable.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        panel_4.add(btnChangeVariable);

        JButton btnCallFunction = new JButton("Call Function");
        panel_4.add(btnCallFunction);

        JPanel panel_5 = new JPanel();
        panel_5.setBorder(new LineBorder(Color.WHITE, 1, true));
        panel_5.setBackground(Color.DARK_GRAY);
        GridBagConstraints gbc_panel_5 = new GridBagConstraints();
        gbc_panel_5.anchor = GridBagConstraints.NORTH;
        gbc_panel_5.fill = GridBagConstraints.HORIZONTAL;
        gbc_panel_5.gridx = 0;
        gbc_panel_5.gridy = 5;
        panel.add(panel_5, gbc_panel_5);
        panel_5.setLayout(new GridLayout(0, 1, 0, 0));

        JLabel label = new JLabel("Loops");
        panel_5.add(label);
        label.setForeground(Color.WHITE);
        label.setFont(new Font("SansSerif", Font.PLAIN, 23));
        label.setBorder(new LineBorder(Color.WHITE));

        JButton btnFor = new JButton("For");
        panel_5.add(btnFor);

        JButton btnForEach = new JButton("For Each");
        panel_5.add(btnForEach);

        Button btnWhile = new Button((String) null);
        btnWhile.setText("while");
        panel_5.add(btnWhile);

        JButton btnTimeLoop = new JButton("Time Loop");
        panel_5.add(btnTimeLoop);

        JPanel desingerPanel = new JPanel();
        splitPane.setRightComponent(desingerPanel);

        JPanel tryIt = new JPanel();
        tryIt.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(nextPlace == null)
                    return;
                DragItemComp comp = nextPlace.getComponent();
                nextPlace = null;
                comp.setLocation(e.getPoint());
                comp.setSize(comp.neededSize);
                tryIt.add(comp);
                tryIt.validate();
                tryIt.repaint();
                for(Component c : tryIt.getComponents()){
                    System.out.println(c);
                }
            }
        });

        GroupLayout gl_desingerPanel = new GroupLayout(desingerPanel);
        gl_desingerPanel.setHorizontalGroup(
                gl_desingerPanel.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_desingerPanel.createSequentialGroup()
                        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(tryIt, GroupLayout.PREFERRED_SIZE, 961, GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                );
        gl_desingerPanel.setVerticalGroup(
                gl_desingerPanel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_desingerPanel.createSequentialGroup()
                        .addComponent(tryIt, GroupLayout.PREFERRED_SIZE, 776, GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                );
        tryIt.setLayout(null);
        desingerPanel.setLayout(gl_desingerPanel);
        new Thread(new Runnable() {

            @Override
            public void run() {
                //Will change this soon
                while(isVisible()){
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(nextPlace == null || !tryIt.isVisible()){
                        if(placeFrame.isVisible())
                            placeFrame.setVisible(false);
                        continue;
                    }
                    Point p = MouseInfo.getPointerInfo().getLocation();
                    if(!new Rectangle(tryIt.getLocationOnScreen(),tryIt.getSize()).contains(p))
                    {
                        if(placeFrame.isVisible())
                            placeFrame.setVisible(false);
                        continue;
                    }
                    else{
                        if(!placeFrame.isVisible())
                            placeFrame.setVisible(true);
                    }
                    placeFrame.setLocation(p);
                    if(placeFrame.getHeight() < 20)
                        placeFrame.setSize(nextPlace.getComponent().neededSize);
                }
            }
        }).start();
    }
}

为了缩短我删除了getter / setter并导入。

一个有趣的事实是,当我设置nextPlace(按下一个按钮)时,CPU使用量会增加,而对于每个DragItem,程序需要15%-25%的CPU。

那为什么它需要这么多的CPU,我该如何改变呢?

另一个有趣的事实是CPU使用率并不取决于线程的休眠时间。我尝试了100000,1000,10,1毫秒。它没有改变任何东西!

uploaded您需要执行的所有类。 - &GT; DragTester.java是主类 您是否需要更改“package com.niton。**”decalration 我更新了需要较少CPU的代码。

1 个答案:

答案 0 :(得分:4)

简单的答案是:在你的绘画方法中,不要做比你必须做的更多的工作。

快速浏览一下,您每次调用paint时都会创建一个新Font并调用setPreferredSize。

创建一次Font并缓存它并从paint方法中引用它。

另外,在paint方法之外调用setPreferredSize。