0

这可能是一个相当愚蠢的问题,但我正在玩 gridbag 布局,我正在尝试构建一个基本的登录屏幕,将用户信息发送到另一个使用 mysql DB 检查的类。但在我这样做之前,我必须找到一种方法来监听我的登录按钮被按下,然后从文本字段中获取文本(最后一部分是我遇到问题的地方)。我尝试在 addComponentsToPane 方法之外声明 JTextField 但无济于事。

到目前为止,这是我的代码

我也很抱歉我是这个网站的新手并且还没有足够的知识来正确格式化我的代码。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


/**
 *
 * @author TeslaSolari
 */
public class login {

    public void login() {
        createAndShowGUI();
    }

    private static void createAndShowGUI() {
        //Create and setup the windows
        JFrame frame = new JFrame("Login");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Setup the content pane
        addComponentsToPane(frame.getContentPane());

        //Display the window
        frame.pack();
        frame.setVisible(true);
    }

    public static void addComponentsToPane(Container pane) {
        pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        //parts
        JButton login;
        JTextField user;
        JLabel[] label = new JLabel[10];
        JPasswordField pass;
        ActionListener loginB = null;

        pane.setLayout(new GridBagLayout());
        //Cpnstraints
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.CENTER;

        // Buttons
        login = new JButton("Login");
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 4;
        pane.add(login, c);
        login.addActionListener(new Action());

        // textfields / labels
        label[0] = new JLabel("Username");
        user = new JTextField();
        c.weightx = 0.5;
        c.gridx = 0;
        c.gridy = 0;
        pane.add(label[0], c);
        c.weightx = 0.5;
        c.gridx = 0;
        c.gridy = 1;
        pane.add(user, c);

        label[1] = new JLabel("Password");
        pass = new JPasswordField();
        c.weightx = 0.5;
        c.gridx = 0;
        c.gridy = 2;
        pane.add(label[1], c);
        c.weightx = 0.5;
        c.gridx = 0;
        c.gridy = 3;
        pane.add(pass, c);


    }

    //Actions

    static class Action implements ActionListener{
        public void actionPerformed (ActionEvent e){
            System.out.println(label[]);
        }
    }

}
4

1 回答 1

1

看来您的解决方案是正确的(将声明 JTextField 声明移到方法之外),但您可能错过了将它们声明为静态(根据您的类的其余部分)

private static JTextField user;
private static JPasswordField pass;
于 2012-07-22T23:50:58.183 回答