0
這可能是一個相當愚蠢的問題,但我正在玩弄網格佈局,我試圖構建一個基本的登錄屏幕,將用戶信息發送到另一個與MySQL數據庫進行檢查的類。但在此之前,我必須找到一種方法來聽取我的登錄按鈕被按下,然後從文本字段中獲取文本(最後一部分是我遇到問題的地方)。我試圖在addComponentsToPane方法之外聲明JTextField,但無濟於事。使用actionlisterns從文本字段中獲取文本
這裏是我到目前爲止的代碼
也是我對不住我是新來這個網站,我還沒有見識到足夠多正確地格式化我的代碼的任何整潔。
/*
* 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[]);
}
}
}
你可以找到一個使用JOptionPane [here](http://stackoverflow.com/a/9852059/522444)的例子。 – 2012-07-22 23:10:32