带有actionListeners的多个JFrame

时间:2016-08-12 01:52:33

标签: java swing jframe jbutton actionlistener

在我回到学校之前,我正在快速设置密码管理员。我不在乎它使用字符串以纯文本形式存储密码......这不是重点。

我需要一些帮助是在我的第二个JFrame窗口中我想在用户点击JButton时显示密码,"网站名称" (我正在使用地图)。但是,我无法让任何按钮在第二个JFrame窗口中执行任何操作。

这是代码。这只是视图类。我不相信模型或控制器适用于此。

import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import components.simplereader.SimpleReader;
 import components.simplereader.SimpleReader1L;

/**
 * View class.
 *
 * @author Redacted
 */
@SuppressWarnings("serial")
public final class PasswordManagerView1 extends JFrame
    implements PasswordManagerView {

//controller
private PasswordManagerController controller;

/**
 * GUI widgets that need to be in scope in actionPerformed method, and
 * related constants. (Each should have its own Javadoc comment, but these
 * are elided here to keep the code shorter.)
 */
private static final int ROWS_IN_BUTTON_PANEL_GRID = 1,
        COLUMNS_IN_BUTTON_PANEL_GRID = 2, KEY_LENGTH = 10,
        VALUE_LENGTH = 15;
// JLabels
private final JLabel keyText, valueText;

// JTextFields
private final JTextField key, value;

// JButtons
private final JButton resetButton, enterButton, recallButton, testButton;

//constructor
public PasswordManagerView1() {
    //JFrame title
    super("Password Manager");

    //widgets
    this.testButton = new JButton("Test Button");
    this.recallButton = new JButton("Recall");
    this.valueText = new JLabel("Enter password here",
            SwingConstants.CENTER);
    this.keyText = new JLabel("Enter store here", SwingConstants.CENTER);
    this.key = new JTextField(KEY_LENGTH);
    this.value = new JTextField(VALUE_LENGTH);
    this.resetButton = new JButton("Reset");
    this.enterButton = new JButton("Enter");

    //Button panel
    JPanel buttonPanel = new JPanel(new GridLayout(
            ROWS_IN_BUTTON_PANEL_GRID, COLUMNS_IN_BUTTON_PANEL_GRID));

    //Add to button panel
    buttonPanel.add(this.resetButton);
    buttonPanel.add(this.enterButton);

    //Grid layout
    this.setLayout(new GridLayout(0, 2, 5, 0));

    //Add to layout
    this.add(this.key);
    this.add(this.value);
    this.add(this.keyText);
    this.add(this.valueText);
    this.add(this.resetButton);
    this.add(this.enterButton);
    this.add(this.recallButton);
    this.add(this.testButton);

    //observers
    this.resetButton.addActionListener(this);
    this.enterButton.addActionListener(this);
    this.key.addActionListener(this);
    this.value.addActionListener(this);
    this.testButton.addActionListener(this);

    //Pack up
    this.pack();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
}

/**
 * Register argument as observer/listener of this.
 *
 * @param controller
 *            controller to register
 */
@Override
public void registerObserver(PasswordManagerController controller) {
    this.controller = controller;
}

/**
 * Updates key display based on String provided as argument.
 *
 * @param key
 *            new value of input display
 */
@Override
public void updateKeyDisplay(String key) {
    this.key.setText(key);
}

/**
 * Updates value display based on String provided as argument.
 *
 * @param value
 *            new value of output display
 */
@Override
public void updateValueDisplay(String value) {
    this.value.setText(value);
}

@Override
public void actionPerformed(ActionEvent event) {

    //Wait cursor
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    //What button was pressed
    Object source = event.getSource();
    if (source == this.resetButton) {
        this.controller.processResetEvent();
    } else if (source == this.enterButton) {
        this.controller.processEnterEvent(this.key.getText(),
                this.value.getText());
    } else if (source == this.recallButton) {
        this.controller.processRecallEvent();
    } else if (source == this.testButton) {
        //Creates new JFrame window
        JFrame test = new JFrame();
        //Reads in store names
        SimpleReader in = new SimpleReader1L("data/store.txt");
        //Counts how many buttons to create
        int passwordCount = 0;
        while (!in.atEOS()) {
            System.out.println(in.nextLine());
            passwordCount++;
        }
        /*
         * Previous operation went to the end of the file. We have to read
         * in the file again.
         */
        SimpleReader in2 = new SimpleReader1L("data/store.txt");
        //Layout gets set.
        test.setLayout(new FlowLayout());
        //Creation of an array of JButtons
        JButton[] storeButtons = new JButton[passwordCount];
        for (int i = 0; i < passwordCount; i++) {
            storeButtons[i] = new JButton(in2.nextLine());
            storeButtons[i].addActionListener(this);
            test.add(storeButtons[i]);
        }
        //Creates an array of Strings for the passwords
        String[] passwordString = new String[passwordCount];
        SimpleReader in3 = new SimpleReader1L("data/password.txt");
        for (int i = 0; i < passwordCount; i++) {
            passwordString[i] = in3.nextLine();
        }

        Object sourceFrame = event.getSource();
        /*
         * I'm just trying to get this to work with one of my buttons. I
         * will use a for loop to cover all the buttons later.
         */
        if (sourceFrame.equals(passwordString[0])) {
            JOptionPane.showMessageDialog(test, "HEY");
        }
        test.pack();
        test.setVisible(true);
        in.close();
        in2.close();
        in3.close();
    }

    //Cursor normal again
    this.setCursor(Cursor.getDefaultCursor());
}

}

2 个答案:

答案 0 :(得分:1)

所有storeButtons都有ActionListener this。因此,无论何时点击它们都会运行actionPerformed()。但是,您需要if个语句来检查ActionEvent的来源是resetButtonenterButtonrecallButton还是testButton。这意味着当来源是JButton的{​​{1}}之一时,它就不会做任何事情。

尝试向storeButtons添加匿名类,看看会发生什么。

storeButtons

答案 1 :(得分:1)

为了便于阅读和维护,您应该将代码分成新类JFrame2: JFrame2是这样的:

public JFrame2 extends JFrame implements ActionListener{

    String[] passwordString;
    JButton[] storeButtons;

    public JFrame2(){
          //Reads in store names
        SimpleReader in = new SimpleReader1L("data/store.txt");
        //Counts how many buttons to create
        int passwordCount = 0;
        while (!in.atEOS()) {
            System.out.println(in.nextLine());
            passwordCount++;
        }
        /*
         * Previous operation went to the end of the file. We have to read
         * in the file again.
         */
        SimpleReader in2 = new SimpleReader1L("data/store.txt");
        //Layout gets set.
        this.setLayout(new FlowLayout());
        //Creation of an array of JButtons
        storeButtons = new JButton[passwordCount];
        for (int i = 0; i < passwordCount; i++) {
            storeButtons[i] = new JButton(in2.nextLine());
            storeButtons[i].addActionListener(this);
            this.add(storeButtons[i]);
        }
        //Creates an array of Strings for the passwords
        passwordString = new String[passwordCount];
        SimpleReader in3 = new SimpleReader1L("data/password.txt");
        for (int i = 0; i < passwordCount; i++) {
            passwordString[i] = in3.nextLine();
        }


        this.pack();
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
          JButton button = (JButton)event.getSource();//the button you are clicking
        /*
         * I'm just trying to get this to work with one of my buttons. I
         * will use a for loop to cover all the buttons later.
         */
        if (button.getText().equals(passwordString[0])) {
            //JOptionPane.showMessageDialog(test, "HEY");
        }
    }
}