我目前正在开发一个小程序,并且在完成它时遇到了一些麻烦。我的代码工作得很好但是我需要将最后一部分从JOptionDialog
消息对话框更改为只添加到小程序的JLabel
。我已经尝试过各种我能想到的方式,但我仍然做得很短。我目前的代码如下:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
JOptionPane.showMessageDialog(null, "Access Granted");
return
}
else {
JOptionPane.showMessageDialog(null, "Access Denied");
}
}
}
}
请帮忙!
答案 0 :(得分:0)
试试这个:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
JLabel message = new JLabel();
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.add(message);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
message.setText("Access Granted");
return;
}
else {
message.setText("Access Denied");
}
}
}
}
它的示例代码因此没有对齐,它将在按钮旁边显示消息。您可以根据需要更改对齐方式;)