这可能是一个相当愚蠢的问题,但我正在使用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[]);
}
}
}
答案 0 :(得分:1)
看起来你的解决方案是正确的(在方法之外移动声明JTextField声明),但你可能错过了将它们声明为静态(根据你的其他类)
private static JTextField user;
private static JPasswordField pass;