How to Validate a textfield in java - java

Hello I need some help validing textfield in my gui. My professor gave me a hint on how to do but it freezes up my program. I've tried other methods but if If I enter text the text field the next window doesn't show.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.*;
//import statements here
public class UserWindow extends JFrame
{
private JTextField nameField, ageField, creditCardField;
private JButton backButton, nextButton;
public UserWindow()
{
super("Please enter your information");
setSize(700,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4,2));
buildPanel();
setVisible(true);
}
private void buildPanel(){
nameField = new JTextField(10);
ageField = new JTextField(2);
creditCardField = new JTextField(10);
backButton = new JButton("Back");
nextButton = new JButton("Next");
nextButton.addActionListener(new NextButton());
backButton.addActionListener(new BackButton());
JLabel NameLabel = new JLabel("Please enter your name");
JLabel ageLabel = new JLabel("Enter your age");
JLabel creditCardLabel = new JLabel("Enter your credit card number");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
add(panel1);
add(panel2);
add(panel3);
add(panel4);
add(panel5);
add(panel6);
add(panel7);
add(panel8);
panel1.add(NameLabel);
panel2.add(nameField);
panel4.add(ageField);
panel6.add(creditCardField);
panel3.add(ageLabel);
panel5.add(creditCardLabel);
panel7.add(backButton);
panel8.add(nextButton);
}//end of panel building
//action listeners for fields/buttons
private class NextButton implements ActionListener{
public void actionPerformed(ActionEvent e){
String str;
int age;
str = nameField.getText();
if (str.equals("")){
JOptionPane.showMessageDialog(null,"Please enter your name.");
while(true){
nameField.requestFocusInWindow();
if(!str.equals(""))
break;
}
}
if(e.getSource() == nextButton)
new MovieSelection();
setVisible(false);
}
}
private class BackButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == backButton)
setVisible(false);
new SelectUserWindow();
}
}
}

You never assign a new value to str if it is initially the empty string.
I think you need something like
str = nameField.getText();
inside your while(true) loop.

It is freezing because you have a this:
if (str.equals("")){
JOptionPane.showMessageDialog(null,"Please enter your name.");
while(true){ //<- Runs forever
nameField.requestFocusInWindow();
if(!str.equals(""))
break;
}
}
AcId is correct when he say you never assign any value to str after you enter the loop (or the if). This means you never change the value of str and it will never not be equal to "" and it will run in the loop forever. The loop runs in the same thread as the user interface, so the user interface will not have time to do anything else (hence it is freezing).
It doesn't make sense to have a loop that runs forever in this situation. It seems you are trying to make the GUI busy wait until the user has entered a name. Don't do that. Instead check if the user have entered something, if not, alert the user and wait for the user to click the button again.
So remove the loop and use a simple if-else statement.
if (str.equals("")){ //User have not entered anything.
JOptionPane.showMessageDialog(null,"Please enter your name.");
nameField.requestFocusInWindow();
//Do NOT loop here.
}
else {
//Do everything you need to do when the user have entered something
}

Related

JButton won't show another jframe

I'm currently working on a project and whenever I click the jbutton on jframe 2 (the 2nd jframe after the log in) "set appointments"/btn1, it won't show the other jframe which is jframe3.
The program itself works but the button won't show the other jframe.
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Container;
public class me {
public static void main (String [] args) {
JFrame jframe = new JFrame();
jframe.setSize(450,350);
jframe.getContentPane().setBackground(Color.WHITE);
ImageIcon c = new ImageIcon("teethlogo5.png");
JLabel bi = new JLabel("",c,JLabel.RIGHT);
bi.setBounds(25,35,400,40);
jframe.add(bi);
ImageIcon a = new ImageIcon("teethlogo2.png");
JLabel si = new JLabel("",a,JLabel.RIGHT);
si.setBounds(50,90,100,120);
jframe.add(si);
JLabel jl1 = new JLabel("Username:");
jl1.setBounds(190,100,100,50);
jframe.add(jl1);
JTextField uss = new JTextField();
uss.setBounds(270,110,120,30);
jframe.add(uss);
JLabel jl2 = new JLabel("Password:");
jl2.setBounds(190,150,100,50);
jframe.add(jl2);
JPasswordField pss = new JPasswordField();
pss.setBounds(270,160,120,30);
jframe.add(pss);
JButton enter = new JButton("log in");
enter.setBounds(250,210,100,40);
jframe.add(enter);
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String userText;
String pwdText;
userText = uss.getText();
pwdText = String.valueOf(pss.getPassword());
if (userText.equals("user") && pwdText.equals("pass")) {
JOptionPane.showMessageDialog(null, "LoginSuccessful","Message",JOptionPane.PLAIN_MESSAGE);
jframe.setVisible(false);
JFrame jframe2 = new JFrame();
jframe2.setSize(850,560);
jframe2.getContentPane().setBackground(Color.WHITE);
ImageIcon b = new ImageIcon("teethlogo4.png");
JLabel sii = new JLabel("",b,JLabel.RIGHT);
sii.setBounds(10,0,600,100);
jframe2.add(sii);
JButton btn1 = new JButton("Set an Appointment");
btn1.setBounds(100,100,150,30);
jframe2.add(btn1);
JButton btn2 = new JButton("View Appointments");
btn2.setBounds(270,100,150,30);
jframe2.add(btn2);
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (btn1.isSelected()){
jframe2.setVisible(false);
JFrame jframe3 = new JFrame();
jframe3.setSize(850,560);
jframe3.getContentPane().setBackground(Color.WHITE);
jframe3.setLayout(null);
jframe3.setVisible(true);
jframe3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
});
jframe2.setLayout(null);
jframe2.setVisible(true);
jframe2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else {
JOptionPane.showMessageDialog(null, "Invalid Username or Password","Message",JOptionPane.PLAIN_MESSAGE);
uss.setText(null);
pss.setText(null);
}
}
});
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setResizable(false);
jframe.setLayout(null);
jframe.setVisible(true);
}
}
I'm a beginner in java and I really want to know how to fix this problem.
You're shooting your own self in the foot with:
if (btn1.isSelected()){
// ...
}
There is no need for this block of code -- a button isn't "selected" unless it extends from JToggleButton (such as JCheckBox) and has been checked, something that a JButton does not allow, and what is more, it is preventing the listener's code that it holds from running. Solution: just get rid of it.

Button in java not doing action

I'm working on a Java assignment. I have many classes linked together and one of the constructors is the following:
public class RemovePatientForm extends JFrame implements ActionListener {
JPanel northPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel midPanel = new JPanel();
JLabel removeLabel = new JLabel("Please type in the ID of the patient to be removed");
JLabel idLabel= new JLabel("ID");
JTextField idText=new JTextField();
JButton submit = new JButton("Submit");
JButton reset = new JButton("Clear");
boolean externalForm = false;
public RemovePatientForm(){
setTitle("Removing a patient");
setLayout(new BorderLayout());
setSize(400,200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
add("North", northPanel);
add("South", southPanel);
northPanel.add(removeLabel);
southPanel.add(submit);
southPanel.add(reset);
add(idLabel);
add(idText);
submit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==submit){
if(!(idText.getText().equals(""))){
int selectedvalue = JOptionPane.showConfirmDialog(null, "Do you want to proceed with the deletion?", "do you want to proceed with the deletion?", JOptionPane.YES_NO_OPTION);
if(selectedvalue==JOptionPane.YES_OPTION){
int id=Integer.parseInt(idText.getText());
if(searchForId(id)){
removeToDatabase();
dispose();
}
else{
JOptionPane.showMessageDialog(null,"This ID is not available!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Nothing is affected!");
}
}
else{
JOptionPane.showMessageDialog(null,"You have to fill the ID number!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
if(arg0.getSource()==reset && externalForm==false){
idText.setText("");
}
}
The problem in here is that when I press the submit button, everything is okay and working as written within the code.
But, if I press the reset button, nothing is happening.
What do you think the solution is? is this code enough to determine the problem?
You didn't add an action listener for the reset button.. i think you forgot it. Try to add it and it should work.
Add this code within your constructor:
reset.addActionListener(this);

How to make blank fields valid until user clicks SAVE -Java

This is a simple program that uses a JDialog to add or edit work orders. When the dialog appears, the user will enter information into the fields (name, date, position, billing rate, etc.). The program must validate each of these fields. The problem is that if I leave a field blank and I tab to the next field, the error message pops up. Actually, this isn't a problem, its working as it should, however, I would like to make it so that all blank fields are valid until the user clicks SAVE. Any suggestions or ideas? I have pasted the entire program below so feel free to compile and run it yourself, thank you!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.lang.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
import java.io.*;
import static javax.swing.GroupLayout.Alignment.*;
public class WorkOrderProject
{
public static void main (String args[])
{
new MyFrameClass();
}
}
class MyFrameClass extends JDialog implements ActionListener
{
JButton addButton, editButton;
JPanel buttonPanel;
WorkOrder workOrderToEdit = new WorkOrder();
MyFrameClass()
{
Container cp;
addButton = new JButton("ADD");
addButton.addActionListener(this);
addButton.setActionCommand("ADD");
editButton = new JButton("EDIT");
editButton.addActionListener(this);
editButton.setActionCommand("EDIT");
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(addButton);
buttonPanel.add(editButton);
cp = getContentPane();
cp.add(buttonPanel, BorderLayout.NORTH);
setupMainFrame();
}
void setupMainFrame()
{
Toolkit tk;
Dimension d;
tk = Toolkit.getDefaultToolkit();
d = tk.getScreenSize();
setLayout(new FlowLayout());
setTitle("Work Orders");
setSize(d.width/2, d.height/2);
setLocation(d.width/4, d.height/4);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("ADD"))
{
System.out.println("ADD");
new MyDialog();
}
else if(e.getActionCommand().equals("EDIT"))
{
System.out.println("EDIT");
new MyDialog(workOrderToEdit);
}
}
}
class MyDialog extends JDialog implements ActionListener
{
JPanel buttonPanel, fieldPanel;
JButton button1, button2, button3, button4;
GroupLayout layout;
WorkOrder workOrderToEdit;
String[] comboTypes = { "Sales", "Hardware", "Electronics" };
JComboBox<String> comboTypesList;
public MyDialog()
{
Container cp;
button1 = new JButton("SAVE");
button1.addActionListener(this);
button1.setActionCommand("SAVE");
button2 = new JButton("CANCEL");
button2.addActionListener(this);
button2.setActionCommand("CANCEL");
button2.setVerifyInputWhenFocusTarget(false);
button3 = new JButton("SAVE AND NEW");
button3.addActionListener(this);
button3.setActionCommand("SAVE AND NEW");
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(button2);
buttonPanel.add(button1);
buttonPanel.add(button3);
fieldPanel = setFields();
cp = getContentPane();
cp.add(fieldPanel, BorderLayout.NORTH);
cp.add(buttonPanel, BorderLayout.SOUTH);
setTitle("Add New Work Order");
setupMainFrame();
}
public MyDialog(WorkOrder w)
{
Container cp;
button1 = new JButton("SAVE");
button1.addActionListener(this);
button1.setActionCommand("SAVE");
button2 = new JButton("CANCEL");
button2.addActionListener(this);
button2.setActionCommand("CANCEL");
button2.setVerifyInputWhenFocusTarget(false);
buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(button2);
buttonPanel.add(button1);
fieldPanel = setFields();
getContentPane().add(fieldPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setTitle("Edit Work Order");
setupMainFrame();
}
void setupMainFrame()
{
Toolkit tk;
Dimension d;
tk = Toolkit.getDefaultToolkit();
d = tk.getScreenSize();
setLayout(new FlowLayout());
setSize(d.width/3, d.height/3);
setLocation(d.width/3, d.height/3);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModal(true);
setVisible(true);
}
JPanel setFields()
{
GroupLayout layout;
JPanel p;
JLabel label1, label2, label3, label4, label5;
JTextField text1, text2, text3, text4, text5;
String[] comboTypes = { "-Select-" ,"Sales", "Hardware", "Electronics" };
comboTypesList = new JComboBox<>(comboTypes);
comboTypesList.addActionListener(this);
label1 = new JLabel("Name: ");
label2 = new JLabel("Department: ");
label3 = new JLabel("Date of request: ");
label4 = new JLabel("Date request was fulfilled: ");
label5 = new JLabel("Billing rate: ");
text1 = new JTextField(20);
text1.setInputVerifier(new NameVerifier());
text2 = new JTextField(20);
text3 = new JTextField(20);
text4 = new JTextField(20);
text5 = new JTextField(20);
p = new JPanel();
layout = new GroupLayout(p);
p.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup().addComponent(label1).addComponent(label2).addComponent(label3).addComponent(label4).addComponent(label5));
hGroup.addGroup(layout.createParallelGroup().addComponent(text1).addComponent(comboTypesList).addComponent(text3).addComponent(text4).addComponent(text5));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label1).addComponent(text1));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label2).addComponent(comboTypesList));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label3).addComponent(text3));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label4).addComponent(text4));
vGroup.addGroup(layout.createParallelGroup(BASELINE).addComponent(label5).addComponent(text5));
layout.setVerticalGroup(vGroup);
return(p);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("SAVE"))
{
System.out.println("SAVED");
dispose();
}
else if(e.getActionCommand().equals("CANCEL"))
{
System.out.println("CANCELED");
dispose();
}
else if(e.getActionCommand().equals("SAVE AND NEW"))
{
System.out.println("SAVED AND NEW");
}
}
}
class WorkOrder
{
String name;
int department;
Object dateRequested;
Object dateFulfilled;
String description;
double billingRate;
}
class NameVerifier extends InputVerifier
{
public boolean verify(JComponent input)
{
String str;
boolean isValid;
int score;
str = ((JTextField)input).getText().trim();
if(str.equals(""))
{
isValid = false;
JOptionPane.showMessageDialog(input.getParent(), "Name field is blank.", "ERROR", JOptionPane.ERROR_MESSAGE);
}
else
{
isValid = true;
}
return(isValid);
}
}
The problem is that if I leave a field blank and I tab to the next field, the error message pops up.
Don't use an InputVerifier. The purpose of the InputVerifier is to validate a text field when it loses focus.
I would like to make it so that all blank fields are valid until the user clicks SAVE.
Add your validation logic (for all the fields) to the ActionListener of the "Save" button.
So you would use the InputVerifier on each text field to validate the format of the data entered (when the data is entered). For example, for the "billing rate" you would verify that the value is a double number, the date fields contain a valid date.
Then in the "Save" listener you validate that all fields contain data. So if the data is in a valid format and all fields contain data, then you know the forum can be submitted for processing.

Using JTextField for user input

Thanks for your help guys...now the program works and runs like it should.. but I have 2 more question.
1.How can I get the output into a JTestField t4 or t5
2.How can I close the application using the JButton Buton3
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TriangleFarfan{
JFrame Triangle = new JFrame("Triangle Calculator");
JButton Button1 = new JButton ("Area");
JButton Button2 = new JButton("Perimeter");
JButton Button3 = new JButton("Close");
JTextField t1 = new JTextField(20);
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
JPanel j1 = new JPanel (new FlowLayout());
JLabel l1 = new JLabel("Enter side 1:");
JTextField t2 = new JTextField();
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
JPanel j2 = new JPanel (new FlowLayout());
JLabel l2 = new JLabel("Enter side 2:");
JTextField t3 = new JTextField();
String t3TextBox = t3.getText();
double side3 = Double.parseDouble(t3TextBox);
JPanel j3 = new JPanel (new FlowLayout());
JLabel l3 = new JLabel("Enter side 3:");
JTextField t4 = new JTextField();
JPanel j4 = new JPanel (new FlowLayout());
JLabel l4 = new JLabel("Area Result");
JTextField t5 = new JTextField(20);
JPanel j5 = new JPanel (new FlowLayout());
JLabel l5 = new JLabel("Perimeter Result");
public TriangleFarfan()
{
j1.add(l1);
j1.add(t1);
j2.add(l2);
j2.add(t2);
j3.add(l3);
j3.add(t3);
j4.add(l4);
j4.add(t4);
j5.add(l5);
j5.add(t5);
Triangle.add(j1);
Triangle.add(j2);
Triangle.add(j3);
Triangle.add(j4);
Triangle.add(j5);
Triangle.add(Button1);
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});
Triangle.add(Button2);
Button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Perimeter Button");
}
});
Triangle.add(Button3);
Button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Close Button");
}
});
Triangle.setLayout(new FlowLayout());
Triangle.setSize(450,400);
Triangle.setVisible(true);
Triangle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In addition to missing a main method, as Reimeus pointed out, your order of instructions is wrong. You are trying to read the user input before anything is even shown on the screen, and even before an object is created. For example, this line:
String t1TextBox = t1.getText();
tries to obtain a text from a TextBox that wasn't even added to a Panel that wasn't yet created.
To solve this, you need to rethink the logic of your program. Here are a few hints:
avoid assignments outside methods. Instead of writing
JFrame Triangle = new JFrame("Triangle Calculator");
declare the variable in the class body like this:
JFrame Triangle;
and assign it inside the constructor like this:
Triangle = new JFrame("Triangle Calculator");
Build the whole UI, then worry about listeners. This way you can be sure that you are not referencing an UI element that does not exist when getting the user input.
Get the user input inside the listeners, like this:
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// get the size of side1 from the textbox
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
// get the size of side2 from the textbox
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
// now we can calculate the area
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});
Add a main method:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TriangleFarfan();
}
});
}
The declaration
JTextField t1 = new JTextField(20);
doesn't set the value in the JTextField to 20. Instead it sets the number of columns for the JTextComponent but with an empty String. Therefore the line
double side1 = Double.parseDouble(t1TextBox);
will throw an NumberFormatException on startup.

How to activate JOptionPane from another class?

I have main class with a main GUI from where I want to activate and get values from a new class with a JOptionPane like the code below. Since I already have a main GUI window opened, how and where should I activate/call the class below and finally, how do I get the values from the JOptionPane? Help is preciated! Thanks!
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class OptionPaneTest {
JPanel myPanel = new JPanel();
JTextField field1 = new JTextField(10);
JTextField field2 = new JTextField(10);
myPanel.add(field1);
myPanel.add(field2);
JOptionPane.showMessageDialog(null, myPanel);
}
Edit:
InputNewPerson nyPerson = new InputNewPerson();
JOptionPane.showMessageDialog(null, nyPerson);
String test = nyPerson.inputName.getText();
I guess looking at your question, you need something like this. I had made a small JDialog, where you will enter a UserName and Answer, this will then be passed to the original GUI to be shown in the respective fields, as you press the SUBMIT JButton.
Try your hands on this code and ask any question that may arise :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* This is the actual GUI class, which will get
* values from the JDIalog class.
*/
public class GetDialogValues extends JFrame
{
private JTextField userField;
private JTextField questionField;
public GetDialogValues()
{
super("JFRAME");
}
private void createAndDisplayGUI(GetDialogValues gdv)
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 2));
JLabel userName = new JLabel("USERNAME : ");
userField = new JTextField();
JLabel questionLabel = new JLabel("Are you feeling GOOD ?");
questionField = new JTextField();
contentPane.add(userName);
contentPane.add(userField);
contentPane.add(questionLabel);
contentPane.add(questionField);
getContentPane().add(contentPane);
pack();
setVisible(true);
InputDialog id = new InputDialog(gdv, "Get INPUT : ", true);
}
public void setValues(final String username, final String answer)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
userField.setText(username);
questionField.setText(answer);
}
});
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
GetDialogValues gdv = new GetDialogValues();
gdv.createAndDisplayGUI(gdv);
}
};
SwingUtilities.invokeLater(runnable);
}
}
class InputDialog extends JDialog
{
private GetDialogValues gdv;
private JTextField usernameField;
private JTextField questionField;
private JButton submitButton;
private ActionListener actionButton = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (usernameField.getDocument().getLength() > 0
&& questionField.getDocument().getLength() > 0)
{
gdv.setValues(usernameField.getText().trim()
, questionField.getText().trim());
dispose();
}
else if (usernameField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Enter USERNAME."
, "Invalid USERNAME : ", JOptionPane.ERROR_MESSAGE);
}
else if (questionField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Answer the question"
, "Invalid ANSWER : ", JOptionPane.ERROR_MESSAGE);
}
}
};
public InputDialog(GetDialogValues gdv, String title, boolean isModal)
{
this.gdv = gdv;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setModal(isModal);
setTitle(title);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
JLabel usernameLabel = new JLabel("Enter USERNAME : ");
usernameField = new JTextField();
JLabel questionLabel = new JLabel("How are you feeling ?");
questionField = new JTextField();
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(questionLabel);
panel.add(questionField);
submitButton = new JButton("SUBMIT");
submitButton.addActionListener(actionButton);
add(panel, BorderLayout.CENTER);
add(submitButton, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
}
JOPtionPane provides a number of preset dialog types that can be used. However, when you are trying to do something that does not fit the mold of one of those types, it is best to create your own dialog by making a sub-class of JDialog. Doing this will give you full control over how the controls are laid out and ability to respond to button clicks as you want. You will want to add an ActionListener for the OK button. Then, in that callback, you can extract the values from the text fields.
The process of creating a custom dialog should be very similar to how you created the main window for your GUI. Except, instead of extending JFrame, you should extend JDialog. Here is a very basic example. In the example, the ActionListener just closes the dialog. You will want to add more code that extracts the values from the text fields and provides them to where they are needed in the rest of your code.

Categories

Resources