gpt4 book ai didi

java - 通过按 java swing 按钮添加另一个标签

转载 作者:行者123 更新时间:2023-12-01 16:30:05 27 4
gpt4 key购买 nike

我是一名初学者程序员,我在按下按钮时添加标签时遇到问题,因为当我按下按钮 b1 时给出的代码它应该打印标签 1 或标签 2 但它什么也不打印,我无法理解为什么会发生

  import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
public class passField extends JFrame implements ActionListener
{
private JPasswordField pass;
private JButton b1;
private JLabel l,l0;
private JLabel l1;
private JLabel l2;

String password;
Container c;
passField()
{
password="pass3word";
c=super.getContentPane();
pass=new JPasswordField(20);
b1=new JButton("OK");
l=new JLabel("Enter Password: ");
l1=new JLabel("PASSWORD MATCH");
l2=new JLabel("INCORRECT PASSWORD");
Font f=new Font("SERIF",Font.PLAIN,22);
l0=new JLabel("PASSWORD CHECKER");
l1.setFont(f);
l2 .setFont(f);
l0.setFont(f);
l0.setForeground(Color.WHITE);
l.setForeground(Color.WHITE);
l1.setForeground(Color.WHITE);
l2.setForeground(Color.WHITE);
add(l0);
add(l);
add(pass);
add(b1);
b1.addActionListener(this);
setVisible(true);
setSize(400,400);
setLayout(new FlowLayout());
c.setBackground(Color.BLACK);
}
public void actionPerformed(ActionEvent e)
{
if(password==pass.getText())
add(l1);
else
add(l2);
}
}

image

最佳答案

建议进行以下更改:
1.添加在标签之前,只需相应地更改文本
2.替换传递时已弃用的 getText()

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
public class passField extends JFrame implements ActionListener
{
private JPasswordField pass;
private JButton b1;
private JLabel l,l0;
private JLabel l1;
private JLabel l2;

String password;
Container c;
passField()
{
password="pass3word";
c=super.getContentPane();
pass=new JPasswordField(20);
b1=new JButton("OK");
l=new JLabel("Enter Password: ");
l1=new JLabel("PASSWORD MATCH");
l1.setText("nothing");
l2=new JLabel("INCORRECT PASSWORD");
Font f=new Font("SERIF",Font.PLAIN,22);
l0=new JLabel("PASSWORD CHECKER");
add(l1);
l1.setFont(f);
l2 .setFont(f);
l0.setFont(f);
l0.setForeground(Color.WHITE);
l.setForeground(Color.WHITE);
l1.setForeground(Color.WHITE);
l2.setForeground(Color.WHITE);
add(l0);
add(l);
add(pass);
add(b1);
b1.addActionListener(this);
setVisible(true);
setSize(400,400);
setLayout(new FlowLayout());
c.setBackground(Color.BLACK);
}
public void actionPerformed(ActionEvent e)
{
String outPass = new String(pass.getPassword());
System.out.println(password+"\n"+outPass);
if(password.equals(outPass))
l1.setText("PASSWORD MATCH");
else
l1.setText("INCORRECT PASSWORD");

}
public static void main(String args[])
{
new passField();
}
}

输出:

enter image description here


enter image description here

关于java - 通过按 java swing 按钮添加另一个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62064622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com