嘿所有我有一个问题我是GUI新手所以当我想使用其他方法向窗口添加元素时我需要一些帮助或者如果语句我没有得到错误但它没有显示听到一个代码我标记的问题我在java工作的方式这不是整个程序但只是这是一个问题
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
}
}
);
}
}
答案 0 :(得分:2)
唯一不会显示的GUI元素是Jlabel
errorPic
。这是因为在添加组件后需要验证容器。你需要打电话:
revalidate();
repaint();
添加JLabel
后。更好的方法是在向JLabel
添加组件时添加没有图像的JFrame
,然后只需调用JLabel.setIcon
来更新标签。
一些附注:
JFrame
。而是直接创建窗口组件的实例。JPassword.getText
已弃用。更安全地使用JPassword.getPassword
。