package me.daniel.practice;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Switch
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Password Login System");
frame.setSize(400, 100);
frame.setResizable(false);
frame.setVisible(true);
frame.setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Password: ");
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.EAST);
frame.add(panel);
}
private static String password = "daniel";
static class AL implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JPasswordField input = (JPasswordField) e.getSource();
char[] passy = input.getPassword();
String p = new String(passy);
if (p.equals(password))
{
JOptionPane.showMessageDialog(null, "Correct");
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
}
}
我想要打开一个框架,并在其中显示文本“输入密码:”,在其右侧有一个文本框,您可以在其中输入密码。这种情况下的密码是“daniel”。
当您输入正确的密码时,会弹出另一个窗口,提示密码正确。如果不正确,则会弹出另一个窗口,提示其不正确。但是,当我运行该程序时,只显示框架,而不显示框架内的实际内容。
最佳答案
您应该在向框架添加内容后使其可见:
frame.add(panel);
frame.setVisible(true); // move down here
}
P.S. JPanel
有默认的布局管理器,即 FlowLayout
,因此所有内容都会内联显示。简而言之,panel.add(label, BorderLayout.WEST)
不会给出预期的输出。
关于java - 如何调试 Java Swing 中丢失的帧内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32241532/