如何使用Swing自定义窗口标题中的图标?

时间:2014-12-08 09:54:31

标签: java swing frame

我使用Swing创建了简单的表单。在这个表单中,我有2个名为username和password的字段。

在第一行中,我将标题设置为“登录”。如何使用自定义图像替换左侧的图标?

class LoginForm extends JFrame {

    public static boolean flag = false;
    JButton login, cancel;
    JTextField uname;
    JPasswordField pass;
    JLabel u, p;
    final CheckUser user = new CheckUser();
    private static final Insets insets = new Insets(0, 0, 0, 0);
    private static ArrayList<JavaBean> store = new ArrayList<JavaBean>();
    JavaBean bean = new JavaBean();
    ArrayList<JavaBean> list = new ArrayList<JavaBean>();
    int n = 0;

    public void login() {
        setTitle("Login");

        setLayout(new GridLayout(3, 2));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        u = new JLabel("Username");
        p = new JLabel("Password");

        uname = new JTextField(20);
        pass = new JPasswordField(20);

        login = new JButton("Login");
        cancel = new JButton("Cancel");

        add(u);
        add(uname);

        add(p);
        add(pass);

        add(login);
        add(cancel);

        uname.requestFocus();


        cancel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });

        login.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {

                String un = uname.getText();
                String pa = new String(pass.getPassword());

                //     JavaBean bean = new JavaBean();
                bean.setUsername(un);
                bean.setPassword(pa);
                System.out.println("Username :" + un + pa);

                store.add(bean);
                setList(store);


                dispose();

                //boolean checkUser = user.checkUser(un, pa, "https://greenhouse.lotus.com/connections/opensocial/basic/rest/activitystreams/@me/@mentions/@all?shortStrings=true&format=atom");
                boolean checkUser = user.checkUser(un, pa, "https://greenhouse.lotus.com/connections/opensocial/basic/rest/activitystreams/@me/@responses/@all?shortStrings=true&format=atom");
                if (checkUser) {
                    System.out.println("------------getData");
                    System.out.println("Check User Boolean!!!" + checkUser);
                    try {
                        final TrayIcon icon = new TrayIcon(createImage("socail.png", "tray icon"), "Connections Notifications");
                        final SystemTray tray = SystemTray.getSystemTray();

                        tray.add(icon);

                        final PopupMenu popup = new PopupMenu();


                        MenuItem view = new MenuItem("View");
                        MenuItem setting = new MenuItem("Settings");
                        MenuItem logout = new MenuItem("Logout");

                        popup.add(view);
                        popup.addSeparator();
                        popup.add(setting);
                        popup.addSeparator();
                        popup.add(logout);
                        icon.setPopupMenu(popup);


                        setting.addActionListener(new ActionListener() {
                            // private ArrayList<LoginBean> loginstore;

                            @Override
                            public void actionPerformed(ActionEvent e) {
                                new SettingForm();

                            }
                        });

                        logout.addActionListener(new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent e) {
                                System.exit(0);
                            }
                        });
                        System.out.println("Haiii For 10 Sec");
                        icon.displayMessage("Hello", "Please click here", TrayIcon.MessageType.INFO);
                        icon.addActionListener(new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent e) {
                                JOptionPane.showMessageDialog(null, "Hey, you activated me!");
                            }
                        });
                        ArrayList<JavaBean> list = user.getList();
                        Iterator itr = list.iterator();
                        System.out.println("Size!!!" + list.size());

                        while (itr.hasNext()) {
                            Object element = itr.next();

                            bean = (JavaBean) element;
                            System.out.print("---->" + bean.getTime());
                            System.out.print("---->" + bean.getTitle());
                            System.out.println("----->" + bean.getUrl());


                            final URI uri = new URI(bean.getUrl());
                            final JFrame frame = new JFrame();

                            frame.setSize(350, 70);
                            frame.add(new JSeparator(SwingConstants.HORIZONTAL));
                            frame.setAlwaysOnTop(true);
                            frame.setUndecorated(true);
                            frame.setLayout(new GridBagLayout());

                            // frame.add(new JLabel(new ImageIcon("socail.png")));


                            JButton cloesButton = new JButton("X");
                            JButton linkbutton = new JButton("links");
                            addComponent(frame, linkbutton, 0, 0, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH);
                            addComponent(frame, cloesButton, 1, 0, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH);
                            linkbutton.setText("<HTML><div style='width:200px; color:#000; border:1px solid #e5e5e5; margin-right:5px; '>"
                                    + bean.getTitle() + "</div>" + "</HTML>");
                            linkbutton.setBackground(Color.LIGHT_GRAY);

                            linkbutton.setHorizontalAlignment(SwingConstants.LEFT);

                            cloesButton.setFocusable(false);


                            linkbutton.setToolTipText(uri.toString());
                            JPanel panel = new JPanel();
                            JScrollPane scrollPane = new JScrollPane(panel);

                            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

                            panel.add(cloesButton, linkbutton);
                            //frame.add(panel);

                            frame.add(scrollPane);

                            frame.pack();
                            //frame.add(linkbutton);
                            // frame.add(cloesButton);
                            frame.setVisible(true);

                            //Set Pop up at bottom - right
                            Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();// size of the screen
                            Insets toolHeight = Toolkit.getDefaultToolkit().getScreenInsets(frame.getGraphicsConfiguration());// height of the task bar
                            //frame.setLocation(scrSize.width - frame.getWidth(), scrSize.height - toolHeight.bottom - frame.getHeight());
                            frame.setLocation(scrSize.width - frame.getWidth(), scrSize.height - toolHeight.bottom - (frame.getHeight() * (n + 1)));

                            n++;
                            linkbutton.addActionListener(new AbstractAction("links") {

                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    System.out.println("i am in link");
                                    open(uri);
                                }

                                private void open(URI uri) {
                                    if (Desktop.isDesktopSupported()) {
                                        try {
                                            Desktop.getDesktop().browse(uri);
                                        } catch (IOException e) {
                                        }
                                    }
                                }
                            });
                            //Close Button
                            cloesButton.addActionListener(new AbstractAction("x") {

                                @Override
                                public void actionPerformed(final ActionEvent e) {
                                    try {
                                        frame.dispose();
                                        Thread.sleep(1000);
                                    } catch (InterruptedException ex) {
                                        Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
                                    }


                                }
                            });

                        }

                    } catch (Exception e) {
                    }

                } else {
                    System.out.println("------------NoData");
                    new WelcomeFrame();
                }

            private void addComponent(JFrame frame, JButton linkbutton, int gridx, int gridy, int gridwidth, int gridheight, int anchor, int fill) {
                GridBagConstraints gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0, 1.0, anchor, fill, insets, 0, 0);
                frame.add(linkbutton, gbc);
            }
        });

        KeyAdapter k = new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent ke) {
                if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    login.doClick();
                }
            }
        };

        pass.addKeyListener(k);
        uname.addKeyListener(k);

        pack();
        setLocationRelativeTo(null);
    }

    /**
     * @return the loginstore
     */
    public static ArrayList<JavaBean> getList() {
        return store;
    }

    /**
     * @param loginstore the loginstore to set
     */
    public static void setList(ArrayList<JavaBean> store) {
        LoginForm.store = store;
    }
    // Notification Panel

    public class NotificationPanel extends JPanel {

        public NotificationPanel() {
            System.out.println("I am in notication Class!!!");

        }
    }

    class WelcomeFrame extends JFrame {

        public WelcomeFrame() {
            JOptionPane.showMessageDialog(WelcomeFrame.this, "Invalid username or password", "Login",
                    JOptionPane.ERROR_MESSAGE);
            new LoginForm();
            // reset username and password
        }
    }

    protected static Image createImage(String path, String description) {
        URL imageURL = Notifications.class.getResource(path);
        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }

}

2 个答案:

答案 0 :(得分:3)

您可以使用JFrame#setIconImage自定义图标的图标,或者更喜欢Window#setIconImages,这样您就可以提供不同尺寸的图像列表,系统可以使用这些图像做出决策哪个图像用于屏幕和任务栏/停靠点和其他可视元素

我也将setVisible(true);移动到你做的最后一次通话,因为它会影响UI在某些系统上的显示方式(缺少组件)

答案 1 :(得分:2)

您可以使用方法setIcon(图标图标),图标将显示在标签附近。

  

public void setIcon(Icon icon)定义此组件的图标   显示。如果icon的值为null,则不显示任何内容。该   此属性的默认值为null。

     

这是一个JavaBeans绑定属性。