0

我目前正在开发一个小程序,并且在完成它时遇到了一些麻烦。我的代码工作得很好,但是我需要将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");
            }
        }
    }
}

请帮忙!

4

1 回答 1

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

            }
        }
    }
}

它的示例代码没有完成对齐,它将在按钮旁边显示消息。您可以根据需要更改对齐方式;)

于 2013-03-16T17:41:34.823 回答