摆脱对话框,用JLabel代替



我目前正在制作一个applet,并且在完成它时遇到了一点麻烦。我的代码工作得很好,但是我需要将JOptionDialog消息对话框的最后一部分更改为添加到applet的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");
            }
        }
    }
}

请帮忙!

试试这个:

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");
            }
        }
    }
}

它的示例代码,所以没有对齐,它将在按钮旁边显示消息。你可以随意改变对齐方式;)

最新更新