获取文件图标会使JPanels消失吗?

时间:2012-07-13 10:38:42

标签: java swing filesystems icons jpanel

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

我希望实现像Windows 7任务栏这样的应用程序,我可以固定。所以我开始环顾四周寻找"提取"从exe文件到Java的图标。在此网站上找到了一些主题,大部分答案都只是this site的网址。

所有这些工作但问题是,当我呼吁这些功能(如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();
        }
    }

2 个答案:

答案 0 :(得分:3)

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

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

你应该非常谨慎地使用布局管理器。

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

它可能看起来不像,但从长远来看,ts会让你的生活变得如此轻松

<强>更新

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

看,不需要覆盖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周大的女儿,对不起)

答案 1 :(得分:0)

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

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

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

当我拿出它时,我得到了4-5,因为我调整窗口大小为7%的cpu然后再回到1%

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