gpt4 book ai didi

java - jbutton事件ActionListener

转载 作者:行者123 更新时间:2023-12-01 22:43:27 25 4
gpt4 key购买 nike

美好的一天,我正在实现一个项目,对于 NewPatient() 这个类,我有 3 个按钮,我想为其触发事件,但不幸的是,到目前为止我还能够触发我的两个按钮的事件,即“返回”和“清除”。但“提交”没有触发任何我不明白的事件。我不知道我错过了什么。我已经发布了以下 3 个类(class)

    in short that is how I refined it 

import javax.swing.JFrame;

public class MyCare
{

public static void main(String[] args)
{

NewPatient application = new NewPatient();

application.setVisible(true);

application.setLocation(500,150);
//application.setLocationRelativeTo(null);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}

/**
* @(#)NewPatient.java
*
*
* @author
* @version 1.00 2014/9/8
*/

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.border.TitledBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.Border;
import java.awt.Color;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JTabbedPane;
import java.awt.Font;
import javax.swing.JComboBox;
import java.util.Random;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JTextArea;
import javax.swing.Box;
import javax.swing.JScrollPane;

public class NewPatient extends JFrame implements ActionListener
{
//////////////////////// new patient labels

private JLabel name;
private JLabel sname;
private JLabel initial;

/////////////////////////////// new patient textfields

private JTextField nameField;
private JTextField snameField;
private JTextField initialField;
//
/////// buttons

private JButton back;
private JButton clear;
private JButton send;

///// container

private JPanel container;

public NewPatient()
{
super("NEW PATIENT");

this.setSize(600,580);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);


//////////////// initializing and setting the main panel

container = new JPanel();


Border titleBorder = new TitledBorder(new LineBorder(Color.BLACK),"REGISTER");
container.setBorder(titleBorder);
container.setLayout(null);

//////////////////////// folder


name = new JLabel("NAME(S):");
name.setBounds(10,85,80,15);
// name.setFont(labeNameFont);

nameField = new JTextField();
nameField.setBounds(80,80,150,27);
// nameField.setFont(labeNameFont);


initialField = new JTextField(15);
initialField.setBounds(407,80,60,27);
// initialField.setFont(labeNameFont);


///////////////// surname

sname = new JLabel("SURNAME:");
sname.setBounds(10,119,80,15);
// sname.setFont(labeNameFont);

snameField = new JTextField(15);
snameField.setBounds(80,115,150,27);
// snameField.setFont(labeNameFont);


////////////////////////////// back

back = new JButton("BACK");
// back.setFont(labeNameFont);
back.setBounds(80,490,80,27);

///////////////////////// clear

clear = new JButton("CLEAR");
// clear.setFont(labeNameFont);
clear.setBounds(280,490,80,27);

///////////////////////// Proceed

send = new JButton("SUBMIT");
// send.setFont(labeNameFont);
send.setBounds(480,490,80,27);

////////////////add components to panel

registerPatient();

///////////////// register button events

back.addActionListener(this);
clear.addActionListener(this);
send.addActionListener(this);
//// countryBox.addItemListener(this);

////////////adding panel


add(container);

}

public void registerPatient()
{

container.add(name);
container.add(nameField);
container.add(sname);
container.add(snameField);



////////// add buttons

container.add(back);
container.add(clear);
container.add(send);


this.setVisible(true);
this.setLocation(500,80);
}


/////////////////// clear fields

public void clearFields()
{

nameField.setText("");

snameField.setText("");


}

//////////////////////// triggering events



public void actionPerformed(ActionEvent event)
{
if(event.getActionCommand().equals("BACK"))
{
//

this.dispose();
}


if(event.getActionCommand().equals("CLEAR"))
{
clearFields();
}


if(event.getActionCommand().equals("SUBMIT"))
{
//ValidateInput validateData = new ValidateInput(); //// input validation

FullDetails mydetails = new FullDetails();

System.out.println("gtmtfsgsdg");

try
{
if(!ValidateInput.validateFirstName(nameField.getText()))
{
System.out.println("youtube");

String message = String.format("Invalid Format!!! NAME must only be one word");

JOptionPane.showMessageDialog(null,message, "ERROR", JOptionPane.ERROR_MESSAGE);
}

else
{
mydetails.setFirstName(nameField.getText()) ;

if(!ValidateInput.validateSurName(snameField.getText()))
{
String msg = String.format("Invalid Format!!! SURNAME must only be one word");

JOptionPane.showMessageDialog(null, msg, "ERROR", JOptionPane.ERROR_MESSAGE);
}

else{

mydetails.setSurname(snameField.getText());
}

}


}

catch(Exception e)
{


String msg = String.format("Invalid input. Please make sure that you have filled every text fields!!! Please enter a correct one");

JOptionPane.showMessageDialog(null, msg, "ERROR", JOptionPane.ERROR_MESSAGE);
}
}

}

}


/**
* @(#)ValidateInput.java
*/

public class ValidateInput
{
public static boolean validateFirstName(String firstName)
{
return firstName.matches("[a-zA-Z]*");
}

public static boolean validateSurName(String surname)
{
return surname.matches("[A-zA-z]+(['-][a-zA-Z]+)*");
}
public static boolean validateInitial(String initial)
{
return initial.matches("[A-Z]*");
}
}


public class FullDetails
{


private static String firstName;

private static String surname;

public void setFirstName(String firstName)
{
this.firstName = firstName;
}

public String getFirstName()
{
return firstName;
}

public void setSurname(String surname)
{
this.surname = surname;
}
public String getSurname()
{
return surname;
}
public static String getSurnam()
{
return surname;
}

}

最佳答案

您在 actionPerformed 方法的 SUBMIT 部分创建了一个 FullDetails 对象,将其分配给 mydetails 变量,并且似乎向其中添加了一些数据,包括名称信息,但您似乎没有对该对象执行任何操作及其数据。您需要对这个对象做一些事情,也许在 GUI 上的某个地方显示它的内容,让它做任何事情。

另请注意,您的 FullDetails 类因静态字段的不当使用而受到影响。大多数所有这些字段都应该是非静态实例字段。通过这样做,每个 FullDetails 实例将共享所有相同的数据,这会带来严重的副作用,包括 FullDetails 对象的集合,它们都不是唯一的。您将想要解决这个问题。

其他不太重要的问题:

  • 您的 GUI 主要使用 null 布局和 setBounds,这是您希望避免执行的操作,因为使用 null 布局会导致 GUI 非常不灵活,虽然它们在一个平台上看起来不错,但在大多数平台上看起来很糟糕其他平台或屏幕分辨率,并且很难更新和维护。
  • 如果您仍然需要帮助,那么根据我对您原始帖子的评论,您需要创建并发布 minimal example program 。我看到您已经缩短了发布的代码,但它仍然具有非核心对象,例如 JDateChooser,它仍然引用我们没有的其他类,例如 PatientPanel,并且仍然没有 main 方法这意味着我们无法编译、运行或测试它。
<小时/>

编辑
我尝试制作代码的可编译版本,但是当我运行它时,SUBMIT 部分中的 System.out.println 起作用:

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

//!! import com.toedter.calendar.*; //!! we don't have this package

public class NewPatient extends JFrame implements ActionListener, ItemListener {
// ////////////////////// new patient labels
// !! enter code here //!! WTF??? this shouldn't be here, non commented
private JLabel name;
private JLabel sname;
private JLabel initial;
private JLabel gender;
private JLabel address;
private JLabel confirm;
private JLabel phone;
private JLabel email;
private JLabel dob;
private JLabel country;
private JLabel city;
private JLabel province;
private JLabel balance;
private JLabel userName;
private JLabel password;
private JLabel mail;
private JLabel folderLabel;
private JLabel idLabel;
private JLabel label;
private JLabel label1;
// ///////////////////////////// new patient textfields
private JTextField nameField;
private JTextField snameField;
private JTextField initialField;
// private JTextField dobField;
private JTextField provinceField;
private JTextField phoneField;
private JTextField emailField;
private JTextField balanceField;
private JTextField userNameField;
private JTextField folderField;
private JTextField idField;
private JTextField cityField;
private JTextField mailField;
// /////////////////// state province combo box
private JComboBox countryBox;
// private JComboBox cityBox;
// private JComboBox provinceBox;
// ////////////// password fields
private JPasswordField passwordField;
private JPasswordField confirmField;
// /////////////// radio buttons
private JRadioButton maleBtn;
private JRadioButton femaleBtn;
// ///////////// radio button group
private ButtonGroup groupSex;
// //////////////panel to containt components
private JPanel container;
// ///////////// fonts
Font labeNameFont = null;
// //////////// text area
private JTextArea addressArea;
// ///////////// box
private Box boxArea;
// /////////////////////// variables
private static final String[] countryNames = { "", "BOTSWANA", "CONGO",
"DR CONGO", "SOUTH AFRICA", "RWANDA", "ZIMBABWE" };
// //////////////////// buttons
private JButton back;
private JButton clear;
private JButton send;

// ///////////// calendar
// !! private JDateChooser chooser;
public NewPatient() {
super("NEW PATIENT");
this.setSize(600, 580);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
// /////////////////// labels fonts
labeNameFont = new Font("SansSerif", Font.BOLD, 12);
// ////////////// initializing and setting the main panel
container = new JPanel();
Border titleBorder = new TitledBorder(new LineBorder(Color.BLACK),
"REGISTER");
container.setBorder(titleBorder);
container.setLayout(null);
// ////////////////////// folder
folderLabel = new JLabel("FOLDER NUMBER:");
folderLabel.setBounds(140, 30, 110, 25);
folderLabel.setFont(labeNameFont);
folderField = new JTextField(15);
folderField.setBounds(250, 30, 90, 27);
folderField.setEditable(false);
folderField.setBackground(Color.YELLOW);
folderField.setText(patientNum());
folderField.setFont(labeNameFont);
// ////////////////// name
name = new JLabel("NAME(S):");
name.setBounds(10, 85, 80, 15);
name.setFont(labeNameFont);
nameField = new JTextField();
nameField.setBounds(80, 80, 150, 27);
nameField.setFont(labeNameFont);
// //////////////////// initial
initial = new JLabel("INITIAL:");
initial.setFont(labeNameFont);
initial.setBounds(347, 82, 80, 20);
initialField = new JTextField(15);
initialField.setBounds(407, 80, 60, 27);
initialField.setFont(labeNameFont);
// /////////////// surname
sname = new JLabel("SURNAME:");
sname.setBounds(10, 119, 80, 15);
sname.setFont(labeNameFont);
snameField = new JTextField(15);
snameField.setBounds(80, 115, 150, 27);
snameField.setFont(labeNameFont);
// //////////////////////////// gender radio and group button
gender = new JLabel("GENDER:");
gender.setBounds(347, 117, 80, 15);
gender.setFont(labeNameFont);
maleBtn = new JRadioButton("MALE");
maleBtn.setBounds(407, 114, 80, 20);
maleBtn.setFont(labeNameFont);
femaleBtn = new JRadioButton("FEMALE");
femaleBtn.setFont(labeNameFont);
femaleBtn.setBounds(490, 114, 80, 20);
groupSex = new ButtonGroup();
groupSex.add(maleBtn);
groupSex.add(femaleBtn);
// ////////////////// id
idLabel = new JLabel("ID NUM:");
idLabel.setBounds(10, 154, 80, 15);
idLabel.setFont(labeNameFont);
idField = new JTextField(15);
idField.setBounds(80, 150, 150, 27);
idField.setFont(labeNameFont);
// /////////////////// address
address = new JLabel("Address:");
address.setBounds(347, 154, 70, 15);
address.setFont(labeNameFont);
boxArea = Box.createHorizontalBox();
addressArea = new JTextArea(10, 10);
addressArea.setLineWrap(true);
addressArea.setFont(labeNameFont);
boxArea.setBounds(407, 150, 150, 80);
boxArea.setFont(labeNameFont);
boxArea.add(new JScrollPane(addressArea));
// /////////// date of birth
dob = new JLabel("D.O.B:");
dob.setBounds(10, 190, 50, 15);
dob.setFont(labeNameFont);
/*
* dobField = new JTextField(15); dobField.setBounds(80,185,150,27);
* dobField.setFont(labeNameFont);
*/
// !! chooser = new JDateChooser();
// chooser.setFont(labeNameFont);
// chooser.setBounds(80,185,150,27);
// ///////////////////////// country
country = new JLabel("COUNTRY:");
country.setBounds(10, 230, 70, 15);
country.setFont(labeNameFont);
countryBox = new JComboBox(countryNames);
countryBox.setBounds(80, 225, 150, 27);
countryBox.setFont(labeNameFont);
countryBox.setMaximumRowCount(3);
// /////////////////////////////////// city
city = new JLabel("CITY:");
city.setFont(labeNameFont);
city.setBounds(347, 248, 70, 15);
// city.setVisible(false);
cityField = new JTextField(15);
cityField.setFont(labeNameFont);
cityField.setBounds(407, 242, 150, 27);
// cityField.setVisible(false);
cityField.setEditable(false);
// //////////////////// province
province = new JLabel("PROVINCE:");
province.setBounds(10, 271, 80, 15);
province.setFont(labeNameFont);
provinceField = new JTextField(15);
provinceField.setFont(labeNameFont);
provinceField.setBounds(80, 267, 150, 27);
provinceField.setEditable(false);
// /////////////////////// phone
phone = new JLabel("PHONE:");
phone.setBounds(10, 313, 70, 15);
phone.setFont(labeNameFont);
phoneField = new JTextField(15);
phoneField.setBounds(80, 306, 150, 27);
phoneField.setFont(labeNameFont);
// /////////////////////// email
email = new JLabel("EMAIL:");
email.setBounds(347, 288, 70, 15);
email.setFont(labeNameFont);
emailField = new JTextField(15);
emailField.setBounds(409, 282, 150, 27);
emailField.setFont(labeNameFont);
mail = new JLabel("CONFIRM EMAIL:");
mail.setBounds(347, 335, 100, 15);
mail.setFont(labeNameFont);
mailField = new JTextField(15);
mailField.setBounds(410, 360, 150, 27);
mailField.setFont(labeNameFont);
label1 = new JLabel("\" name@kalilinux.org \"");
label1.setFont(new Font("SansSerif", Font.BOLD + Font.ITALIC, 12));
label1.setBounds(420, 300, 150, 27);
// ///////////// phone formaat label
// Font font = null;
label = new JLabel("(0XX-XXX-XXXX)");
label.setFont(new Font("SansSerif", Font.BOLD + Font.ITALIC, 12));
label.setBounds(100, 325, 150, 27);
// ////////////// address
balance = new JLabel("BALANCE:");
balance.setBounds(10, 360, 70, 15);
balance.setFont(labeNameFont);
balanceField = new JTextField(15);
balanceField.setBounds(80, 357, 150, 27);
balanceField.setFont(labeNameFont);
// /////// username and password
userName = new JLabel("USER NAME:");
userName.setBounds(10, 395, 100, 15);
userName.setFont(labeNameFont);
userNameField = new JTextField(15);
userNameField.setBounds(80, 392, 150, 27);
userNameField.setFont(labeNameFont);
password = new JLabel("PASSWORD:");
password.setBounds(10, 435, 80, 15);
password.setFont(labeNameFont);
passwordField = new JPasswordField(15);
passwordField.setBounds(80, 432, 150, 27);
passwordField.setFont(labeNameFont);
confirm = new JLabel("CONFIRM PASSWORD:");
confirm.setBounds(347, 403, 150, 15);
confirm.setFont(labeNameFont);
confirmField = new JPasswordField(15);
confirmField.setBounds(410, 425, 150, 27);
confirmField.setFont(labeNameFont);
// //////////////////////////// back
back = new JButton("BACK");
back.setFont(labeNameFont);
back.setBounds(80, 490, 80, 27);
// /////////////////////// clear
clear = new JButton("CLEAR");
clear.setFont(labeNameFont);
clear.setBounds(280, 490, 80, 27);
// /////////////////////// Proceed
send = new JButton("SUBMIT");
send.setFont(labeNameFont);
send.setBounds(480, 490, 80, 27);
// //////////////add components to panel
registerPatient();
// /////////////// register button events
back.addActionListener(this);
clear.addActionListener(this);
send.addActionListener(this);
countryBox.addItemListener(this);
// //////////adding panel
add(container);
}

public String patientNum() {
Random numberGenerated = new Random();
String myNumGen = " MKW - ";
int starter;
starter = 473 + numberGenerated.nextInt(9528);
String start = String.format("%d", starter);
return myNumGen + " " + start;
}

public void registerPatient() {
container.add(folderLabel);
container.add(folderField);
container.add(name);
container.add(nameField);
container.add(sname);
container.add(snameField);
container.add(idLabel);
container.add(idField);
container.add(dob);
// container.add(dobField);
// !! container.add(chooser);
container.add(initial);
container.add(initialField);
container.add(gender);
container.add(maleBtn);
container.add(femaleBtn);
container.add(address);
container.add(boxArea);
container.add(country);
container.add(countryBox);
container.add(city);
container.add(cityField);
container.add(province);
container.add(provinceField);
container.add(phone);
container.add(phoneField);
container.add(label);
container.add(label1);
container.add(email);
container.add(emailField);
container.add(balance);
container.add(balanceField);
container.add(mail);
container.add(mailField);
container.add(userName);
container.add(userNameField);
container.add(password);
container.add(passwordField);
container.add(confirm);
container.add(confirmField);
// //////// add buttons
container.add(back);
container.add(clear);
container.add(send);
this.setVisible(true);
this.setLocation(500, 80);
}

// ///////////////// clear fields
public void clearFields() {
folderField.setText(patientNum());
folderField.setFont(labeNameFont);
nameField.setText("");
initialField.setText("");
snameField.setText("");
idField.setText("");
// !! chooser.setCalendar(null);
provinceField.setText("");
cityField.setText("");
emailField.setText("");
confirmField.setText("");
passwordField.setText("");
mailField.setText("");
userNameField.setText("");
balanceField.setText("");
addressArea.setText("");
phoneField.setText("");
countryBox.setSelectedIndex(0);
groupSex.clearSelection();
// femaleBtn.setSelected(false);
}

// ////////////////////// triggering events
public void itemStateChanged(ItemEvent myevent) {
Object selected = countryBox.getSelectedItem();
if (selected.toString().equals("")) {
provinceField.setText("");
cityField.setText("");
} else if (selected.toString().equals("BOTSWANA")) {
provinceField.setText("SOUTH-EAST");
cityField.setText("GABORONE");
} else if (selected.toString().equals("CONGO")) {
provinceField.setText("POOL");
cityField.setText("BRAZAVILLE");
} else if (selected.toString().equals("DR CONGO")) {
provinceField.setText("KINSHASA");
cityField.setText("KINSHASA");
} else if (selected.toString().equals("SOUTH AFRICA")) {
provinceField.setText("WESTERN CAPE");
cityField.setText("CAPE TOWN");
} else if (selected.toString().equals("RWANDA")) {
provinceField.setText("KIGALI");
cityField.setText("KIGALI CITY");
} else if (selected.toString().equals("ZIMBABWE")) {
provinceField.setText("HARARE");
cityField.setText("HARARE");
}
}

public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("BACK")) {
PatientPanel patient = new PatientPanel();
patient.setVisible(true);
patient.setLocation(500, 250);
dispose();
}
if (event.getActionCommand().equals("CLEAR")) {
clearFields();
}
if (event.getActionCommand().equals("SUBMIT")) {
// ValidateInput validateData = new ValidateInput(); //// input
// validation
FullDetails mydetails = new FullDetails();
System.out.println("gtmtfsgsdg");
try {
if (!ValidateInput.validateFirstName(nameField.getText())) {
System.out.println("youtube");
String message = String
.format("Invalid Format!!! NAME must only be one word");
JOptionPane.showMessageDialog(null, message, "ERROR",
JOptionPane.ERROR_MESSAGE);
} else {
mydetails.setFirstName(nameField.getText());
if (!ValidateInput.validateSurName(snameField.getText())) {
String msg = String
.format("Invalid Format!!! SURNAME must only be one word");
JOptionPane.showMessageDialog(null, msg, "ERROR",
JOptionPane.ERROR_MESSAGE);
} else {
mydetails.setSurname(snameField.getText());
}
}
} catch (Exception e) {
String msg = String
.format("Invalid input. Please make sure that you have filled every text fields!!! Please enter a correct one");
JOptionPane.showMessageDialog(null, msg, "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}

private static void createAndShowGui() {
NewPatient gui = new NewPatient();
gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
gui.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

class ValidateInput {
public static boolean validateFirstName(String firstName) {
return firstName.matches("[a-zA-Z]*");
}

public static boolean validateSurName(String surname) {
return surname.matches("[A-zA-z]+(['-][a-zA-Z]+)*");
}

public static boolean validateInitial(String initial) {
return initial.matches("[A-Z]*");
}
}

class FullDetails {
// !! These fields should not be static
private static String firstName;
private static String surname;

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setSurname(String surname) {
this.surname = surname;
}

public String getSurname() {
return surname;
}

public static String getSurnam() {
return surname;
}
}

//!! a bare bones class to allow your code to compile
class PatientPanel extends JPanel {
public PatientPanel() {
add(new JLabel("Patient Panel"));
setBorder(BorderFactory.createTitledBorder("Patient Panel"));
}
}

此代码尚未以任何方式“修复”,并且仍然存在我上面提到的问题。

<小时/>

编辑
一个小示例程序,显示了我讨论过的一些内容。

import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;

@SuppressWarnings("serial")
// I try to gear my GUI's towards creation of JPanels, not JFrames
// I then can put the panel into a JFrame or into something else if desired
public class SimpleGui extends JPanel {
private JTextField firstNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
private JTextComponent[] textComponents = {firstNameField, lastNameField};
private DefaultListModel<SimpleDetails> detailsListModel = new DefaultListModel<>();
private JList<SimpleDetails> detailsList = new JList<>(detailsListModel);

public SimpleGui() {
JPanel dataEntryPanel = new JPanel();
dataEntryPanel.add(new JLabel("First Name:"));
dataEntryPanel.add(firstNameField);
dataEntryPanel.add(Box.createHorizontalStrut(15)); // add space
dataEntryPanel.add(new JLabel("Last Name:"));
dataEntryPanel.add(lastNameField);

JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(new JButton(new ClearAction("Clear", KeyEvent.VK_C)));
buttonPanel.add(new JButton(new SubmitAction("Submit", KeyEvent.VK_S)));
buttonPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));

JPanel detailsPanel = new JPanel();
detailsList.setPrototypeCellValue(new SimpleDetails("AAAAAAAAAAAA", "BBBBBBBBBBBB"));
detailsList.setVisibleRowCount(12);
JScrollPane detailsScrollPane = new JScrollPane(detailsList);
detailsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
detailsPanel.add(detailsScrollPane);

setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(detailsPanel);
add(dataEntryPanel);
add(buttonPanel);
}

public void clearTextFields() {
for (JTextComponent jTextComponent : textComponents) {
jTextComponent.setText("");
}
}

private class SubmitAction extends AbstractAction {
public SubmitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();

// validate input here or after creating details object
// if valid, then

// create your details object
SimpleDetails simpleDetails = new SimpleDetails(firstName, lastName);

if (Validate.test(simpleDetails)) {
// and then DO something with it.
// Here I add it to a JList
detailsListModel.addElement(simpleDetails);
} else {
// notify user that data is bad
// consider clearing the GUI
clearTextFields();
}

}
}

private class ClearAction extends AbstractAction {

public ClearAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
clearTextFields();
}
}

private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
// clean up an problems
Window win = SwingUtilities.getWindowAncestor(SimpleGui.this);
win.dispose();
}
}

private static void createAndShowGui() {
SimpleGui mainPanel = new SimpleGui();

JFrame frame = new JFrame("SimpleGui");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args) {
// so that the program runs on the Swing event thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

class SimpleDetails {
private String firstName;
private String lastName;

public SimpleDetails(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

@Override
public String toString() {
return lastName + ", " + firstName;
}

}

class Validate {
public static boolean test(SimpleDetails simpleDetails) {
if (simpleDetails.getFirstName().trim().isEmpty()) {
return false;
}
if (simpleDetails.getLastName().trim().isEmpty()) {
return false;
}

// default, has passed all tests
return true;
}
}

关于java - jbutton事件ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25731411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com