-1

所以最近我开始学习一些 Java,我有其他语言的经验(主要是面向 Web 的语言,如 PHP、HTML 等)。所以我从一些小项目开始,喜欢简单的启动器/桌面覆盖。基于JPanel和here,它开始出现问题。

我想用我可以固定的应用程序来实现类似于 Windows 7 任务栏的东西。所以我开始四处寻找从exe文件中寻找“提取”图标到Java的方法。在这个站点上找到了一些主题,大多数答案只是这个站点的 URL 。

所有这些工作,但问题是,当我调用这些功能(如getSystemIcon)时,它会使上面的所有面板(父母)消失。我可以通过重新粉刷将它们全部取回,但是是否有其他解决方案或者我只是做错了什么?

代码:

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Graphics;
import java.io.File;
import javax.swing.Icon;
import javax.swing.JPanel;
import javax.swing.filechooser.FileSystemView;


public class Startbar extends JPanel{


private static final long serialVersionUID = 1L;
Config cfg = new Config();
public Startbar() {
    
    
    setPreferredSize(new Dimension(cfg.Resx,35));
    setBounds(0,1015,cfg.Resx,35);
    setVisible(true);
   
    this.setLayout(null);
    StartbarClock clock = new StartbarClock();
    clock.setBounds(cfg.Resx-135,0, 135, 35);
    this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    
    
    add(clock);
    AddPins();
}
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.black);
    g.fillRect(0, 0, cfg.Resx, 35);
    repaint();
}
public void AddPins(){
    String filename = "C:/Program Files (x86)/Skype/Phone/Skype.exe";
    
    Icon ico = FileSystemView.getFileSystemView().getSystemIcon(new File(filename));
    System.out.println(ico.getIconHeight());
        
    }
}

编辑:在函数中添加 1 秒的超时后,一切正常... wtf ?一些代码:

public class Startbar extends JPanel{
        
        ActionListener listener = new ActionListener(){
              public void actionPerformed(ActionEvent event){
                pin();
              }
        };
        
        Timer timer = new Timer(1000 ,listener);
        
        private static final long serialVersionUID = 1L;
        Config cfg = new Config();
        public Startbar() {
            
            
            setPreferredSize(new Dimension(cfg.Resx,35));
            setBounds(0,1015,cfg.Resx,35);
            setVisible(true);
            setBackground(Color.black);
            this.setLayout(null);
            StartbarClock clock = new StartbarClock();
            
            add(clock);
            
            timer.start();
            //pin();
        }
        
        public void pin(){
            String filename = "C:/Program Files (x86)/Skype/Phone/Skype.exe";
            FileSystemView view = FileSystemView.getFileSystemView();    
            Icon icon = view.getSystemIcon(new File(filename));
            System.out.println(icon.getIconHeight());
            timer.stop();
        }
    }
4

2 回答 2

3

对于您正在尝试做的事情,将 StartBar 的背景设置为黑色,然后您不需要覆盖paintComponet。

不要设置 StartBar 的边界,而是使用 set/getPreferredSize。这将允许父容器有机会计算组件的最佳大小(这可能会解释您的问题)

您应该认真考虑使用布局管理器。

我有两个子面板(内容和任务)。我会将所有应用程序图标放置在内容中,可能使用流布局和时钟作为/在任务中,再次,可能使用流布局。然后我会使用网格包布局或边框布局将它们添加到任务栏面板。

它可能看起来不像,但从长远来看,这会让你的生活变得更加轻松

更新

好的,那么请向我解释为什么我的工作原理:

并且看,无需重写paintComponent 或重新绘制视线。

public class TaskBarPane extends javax.swing.JPanel {

    /**
     * Creates new form TaskBarPane
     */
    public TaskBarPane() {
        
        initComponents();
        
        setPreferredSize(new Dimension(800, 24));
        
        pinTask(new File("C:/Program Files/BabyCounter/BabyCounter x64.exe"));
        
    }
    
    protected void pinTask(File task) {
        
        pnlContent.add(new TaskPane(task));
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        pnlContent = new javax.swing.JPanel();
        pnlClock = new test.ClockPane();

        setBackground(new java.awt.Color(0, 0, 0));
        setLayout(new java.awt.BorderLayout());

        pnlContent.setOpaque(false);
        java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT);
        flowLayout1.setAlignOnBaseline(true);
        pnlContent.setLayout(flowLayout1);
        add(pnlContent, java.awt.BorderLayout.CENTER);

        pnlClock.setOpaque(false);
        add(pnlClock, java.awt.BorderLayout.EAST);
    }// </editor-fold>
    // Variables declaration - do not modify
    private test.ClockPane pnlClock;
    private javax.swing.JPanel pnlContent;
    // End of variables declaration
}

..

public class ClockPane extends javax.swing.JPanel {

    /**
     * Creates new form ClockPane
     */
    public ClockPane() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jLabel1 = new javax.swing.JLabel();

        setLayout(new java.awt.GridBagLayout());

        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Hello World");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 100;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
        add(jLabel1, gridBagConstraints);
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    // End of variables declaration
}

..

public class TaskPane extends javax.swing.JPanel {

    /**
     * Creates new form TaskPane
     */
    public TaskPane() {
        initComponents();
    }

    public TaskPane(File task) {

        this();

        Icon ico = FileSystemView.getFileSystemView().getSystemIcon(task);
        lblIcon.setIcon(ico);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        lblIcon = new javax.swing.JLabel();

        setOpaque(false);
        setLayout(new java.awt.GridBagLayout());

        lblIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblIcon.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblIcon.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        add(lblIcon, new java.awt.GridBagConstraints());
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JLabel lblIcon;
    // End of variables declaration
}

...

public class TestFrame extends javax.swing.JFrame {

    /**
     * Creates new form TestFrame
     */
    public TestFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        pnlTaskBar = new test.TaskBarPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(pnlTaskBar, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TestFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private test.TaskBarPane pnlTaskBar;
    // End of variables declaration
}

我花了 10 分钟才完成(不得不喂我 11 周大的女儿,对不起)

于 2012-07-13T10:52:04.987 回答
0

我将 System.out.println("inRepaint") 添加到您的 paintComponent 方法中并运行代码...

16
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
...

在我杀死它之前,我的 CPU 使用率上升到了 85%。

当我把它拿出来时,当我用大约 7% 的 cpu 调整窗口大小时,我得到了 4-5,然后它又回到了 1%

所以,是的,你的代码坏了。

于 2012-07-13T12:18:54.727 回答