0

Hey all I have one question I am new to GUI stuff so I need some help when I want to add an element to a window using some other method or if statement I don't get error but it doesn't show up hears a code I marked problem I am working in java by the way this is not whole program but only this is a problem

import java.awt.*;  

import java.awt.event.*;

import javax.swing.*;

public class Gui extends JFrame{

private JTextField usernameTF;
private JPasswordField passwordField;
private String username,password;
private JRadioButton A,B,C,D,F;

//private JComboBox box;
private JLabel logo,errorPic,promt;
private JButton logIn;
private boolean value;
private Apples function= new Apples();

public Gui(){
    super ("Awsome Progrma");
    setLayout(new FlowLayout());

    Icon errorIcon = new  ImageIcon(getClass().getResource("wrong.png"));
    errorPic = new JLabel(errorIcon);

    usernameTF = new JTextField(10);
    usernameTF.setToolTipText("Enter your user name hear");
    add(usernameTF);

    passwordField = new JPasswordField(10);
    passwordField.setToolTipText("Enter your password hear");
    add(passwordField);

    logIn = new JButton("Log IN");
    add(logIn);

    usernameTF.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    username = event.getActionCommand();
                    password = passwordField.getText();
                    value = function.chack(username,password);
                    if (value == true){add(errorPic);}                      // this is a problem JLabel dosn't show up in my window 
                }
            }
        );
    passwordField.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    username = usernameTF.getText();;
                    password = event.getActionCommand();
                    value = function.chack(username,password);
                    if (value == true){add(errorPic);}                          // this is a problem JLabel dosn't show up in my window 
                }
            }
        );
    logIn.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    username = usernameTF.getText();
                    password = passwordField.getText();
                    value = function.chack(username,password);
                    if (value == true){add(errorPic);}                                  // this is a problem JLabel dosn't show up in my window 
                    }
                }
            );
    }

}
4

1 回答 1

2

唯一不会显示的 GUI 元素是Jlabel errorPic. 这是因为容器需要在组件添加后进行验证。您需要致电:

revalidate();
repaint();

添加后JLabel。更好的方法是在向 中JLabel添加组件时添加没有图像,JFrame然后简单地调用JLabel.setIcon以更新标签。


一些旁注:

  • 不要延长JFrame。而是直接创建窗口组件的实例。
  • JPassword.getText弃用。使用起来更安全JPassword.getPassword
  • 考虑在应用程序启动时使用初始线程
于 2013-01-27T21:32:07.867 回答