-1

I have created simple form using Swing. In this form I have 2 fields named username and password.

In the first line, I am setting the title to 'Login'. How may I replace the icon to the left of it with a custom image?

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();
        }
    }

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
md razi
  • 67
  • 4
  • 12
  • Don't use `KeyListener` with `JTextComponent`s, use an `ActionListener`, it will do the same thing and is safer across platforms – MadProgrammer Dec 08 '14 at 10:14
  • I can't see your setIcon(...) method call. – marc3l Dec 08 '14 at 10:17
  • Holy crap! There was no need to post near on 300 LOC to show 'I can't load an Icon'! 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) One way to get images for an example, is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Dec 08 '14 at 10:23
  • `return (new ImageIcon(imageURL, description)).getImage();` It is far more informative to use `ImageIO` to load the image, since it will provide helpful feed-back that constructing an `ImageIcon` hides.. – Andrew Thompson Dec 08 '14 at 10:26
  • Here i am not getting here ,where i have write code for setting image icon..@MadProgrammer – md razi Dec 08 '14 at 11:07

2 Answers2

3

You can use JFrame#setIconImage to customise the frame's icon or preferrably Window#setIconImages which will allow you to provide a list of images at different sizes, which the system can use to make decisions about which image to use for the screen AND the task bar/docks and other visual elements

I'd also move setVisible(true); to be the last call you make, as it can affect how the UI is displayed on some systems (missing components)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • *"..or preferrably `Window#setIconImages`.."* See also [Sizes of frame icons used in Swing](http://stackoverflow.com/q/18224184/418556) for a working example. – Andrew Thompson Dec 08 '14 at 10:24
2

You can use the method setIcon(Icon icon) and the icon will be displayed near the label.

public void setIcon(Icon icon) Defines the icon this component will display. If the value of icon is null, nothing is displayed. The default value of this property is null.

This is a JavaBeans bound property.

marc3l
  • 2,525
  • 7
  • 34
  • 62