2014-12-08 61 views
-1

我用Swing创建了简单的表单。在这种形式中,我有两个名为用户名和密码的字段。如何使用Swing自定义窗口标题中的图标?

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

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

} 
+0

不要使用' KeyListener'使用'JTextComponent',使用'ActionListener',它可以做同样的事情,并且跨平台更安全 – MadProgrammer 2014-12-08 10:14:48

+0

我看不到你的setIcon(...)方法调用。 – 2014-12-08 10:17:58

+0

圣洁的废话!没有必要在300 LOC附近发帖以显示'我无法加载图标'! 1)为了更快地获得更好的帮助,请发布[MCVE](http://stackoverflow.com/help/mcve)(最小完整可验证示例)或[SSCCE](http://www.sscce.org/)(简称,自包含,正确的例子)。 2)获取图像的一种方法是通过[本问答](http://stackoverflow.com/q/19209650/418556)中的图像进行热链接。 – 2014-12-08 10:23:24

回答

2

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

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

这是一个JavaBeans绑定属性。

+0

是的,我写下这个代码... ImageIcon img = new ImageIcon(“Feed Rss.png”); setIconImage(img.getImage());但它没有显示 – 2014-12-08 10:05:07

+0

@mdrazi setIconImage在JLabel中不可用。请向我们展示设置图标的完整代码。 – 2014-12-08 10:06:48

+0

@mdrazi听起来更像是无法找到图像。它存储在哪里? – MadProgrammer 2014-12-08 10:10:33

3

您可以使用JFrame#setIconImage定制框架的图标或preferrably Window#setIconImages,让您以提供不同尺寸的图像,该系统可以使用,使即将使用的屏幕和它的图像决定清单任务栏/码头和其他视觉元素

我也希望移居setVisible(true);是你做的最后一次通话,因为它会影响到用户界面的显示在某些系统上(缺少的组件)

+0

*“..或最好是'Window#setIconImages' ..”*另请参见[Swing中使用的框架图标的大小](http://stackoverflow.com/q/18224184/418556)中的工作示例。 – 2014-12-08 10:24:29

相关问题