I have the following method which pops up a window when a button is clicked.
public void cardPopUp() {
String[] cardTypes = {"Visa", "Mastercard", "Electron", "Cashcard"};
JComboBox combo = new JComboBox(cardTypes);
JTextField field1 = new JTextField("");
JTextField field2 = new JTextField("");
JTextField field3 = new JTextField("");
JTextField field4 = new JTextField("");
JTextField field5 = new JTextField("");
JPanel panel = new JPanel(new GridLayout(0, 2));
panel.add(new JLabel("Card Type:"));
panel.add(combo);
panel.add(new JLabel("Cardholder Name:"));
panel.add(field1);
panel.add(new JLabel("Card Number:"));
panel.add(field2);
panel.add(new JLabel("Month Expiry:"));
panel.add(field3);
panel.add(new JLabel("Year Expiry:"));
panel.add(field4);
panel.add(new JLabel("CVC:"));
panel.add(field5);
int input = JOptionPane.showConfirmDialog(MainActivity.this, panel, "Card Payment",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (input == JOptionPane.OK_OPTION) {
Basket.orderNo+=1;
dispose();
new OrderConfirmationScreen().setVisible(true);
} else {
System.out.println("Payment Cancelled");
}
}
How can i add validation so that the fields are checked to see if correct data was entered for a card payment. For example, field1 should only allow text, field2 should only allow a 16 digit number and so on.
I'm guessing i would need to create more methods that validate each field and then just call the method in cardPopUp() method.
For example :
field1 should only allow text
if(field1.getText().matches("\\w+\\.?")){
...
}else{...}
field2 should only allow a 16 digit number
if(field2.getText().matches("(\\d{16})")){
...
}else{...}
And so on.
as i understand your question what u want is to match the character types that are inputted, for this i would suggest to take a look at the String.matches see javaDoc using this you can setup a function that checks the input for any regrex epression and returns true or false, if this is NOT what you wanted i'm afraid i don't understand the question
Related
Hello fellow programmers across the world I am currently having a problem with one of my frames in my GUI. I have managed to change the font of my messeges to itallic and the color to grey and i have set my textfield to editable(true). The problem is that when I delete the string in gray and italic and try to write something useful in the textfield, rather that plain font and a color of black for the string it always comes out italic and gray. Is there any way that a string in a text message can change font and color and then then next string you write to have the normal font and black color? Would appreciate any sugggestions at this point. Here is my code:
void makeSecondFrame(){
frame2 = new JFrame("Step one!Vertification!");
Container contentPane2 = frame2.getContentPane();
JLabel label2 = new JLabel("Welcome to step 1 of our algorithm, Verification!" + "To varify yourself of owning an account please enter the following:");
JLabel label3 = new JLabel("First Name:");
JLabel label4 = new JLabel("Middle Name:");
JLabel label5 = new JLabel("Surname:");
JLabel label6 = new JLabel("Account Number:");
JLabel label7 = new JLabel ("Registration Number:");
firstName = new TextField("Enter your name here");
firstName.setForeground(Color.gray);
firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
firstName.setEditable(true);
middleName = new TextField("Enter your middle name here");
middleName.setForeground(Color.gray);
middleName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
middleName.setEditable(true);
surname = new TextField("Enter your surname here");
surname.setForeground(Color.gray);
surname.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
surname.setEditable(true);
accountNumber = new TextField("Enter your main account number");
accountNumber.setForeground(Color.gray);
accountNumber.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
accountNumber.setEditable(true);
registrationNumber = new TextField("Enter your registration number");
registrationNumber.setForeground(Color.gray);
registrationNumber.setFont(new java.awt.Font("Arail", Font.ITALIC, 12));
registrationNumber.setEditable(true);
JPanel p2 = new JPanel(new GridLayout(1,1));
p2.add(label2);
contentPane2.add(p2, BorderLayout.NORTH);
JPanel p3 = new JPanel(new GridLayout(10,1));
p3.add(label3);
p3.add(firstName);
p3.add(label4);
p3.add(middleName);
p3.add(label5);
p3.add(surname);
p3.add(label7);
p3.add(registrationNumber);
p3.add(label6);
p3.add(accountNumber);
contentPane2.add(p3, BorderLayout.WEST);
JButton next = new JButton("Next!");
next.addActionListener(this);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(this);
JPanel p4 = new JPanel(new GridLayout(1,1));
p4.add(next);
p4.add(cancel);
contentPane2.add(p4, BorderLayout.SOUTH);
frame2.pack();
frame2.setVisible(true);
}
You need to act on an appropriate action on the JTextField. The best I can think of is the FocusListener.focusGained():
firstName = new TextField("Enter your name here");
firstName.setForeground(Color.gray);
firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
firstName.setEditable(true);
firstName.addFocuListener(new FocusAdapter(){
#Overwrite
public void focusGained(FocusEvent e){
firstName.setText("");// remove help message, will also remove previously entered text!
firstName.setFont(new JTextField().getFont()); // reset to default
}
}
Well that did remove the helper message – Христо Петков
as I mentioned...
and I want to keep it – Христо Петков
Then you might want to use the other method in the FocusListener interface too:
#Overwrite
public void focusLost(FocusEvent e){
if(userDidNotEnterTextIn(firstName){ // hopefully you know how to find out...
firstName.setText("Enter your name here");
// do formatting again
}
}
I want to add two numbers and put the result into a JTextFields (textboxes). Why doesn't this code work?
public class Window extends JFrame implements ActionListener {
private JButton plus;
private JLabel text;
private JTextField textbox1;
private JTextField textbox2;
public Okno(){
this.setLayout(new FlowLayout());
this.setBounds(400,400,400,400);
plus = new JButton("+");
text = new JLabel("");
plus.addActionListener(this);
textbox1 = new JTextField(" ");
textbox2 = new JTextField(" ");
this.add(text);
this.add(textbox1);
this.add(textbox2);
this.add(plus);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(plus)){
int result = Integer.valueOf(textbox1.getText()) + Integer.valueOf(textbox2.getText());
text.setText(Integer.toString(result)); //gtregergregergergreg
}
}
}
Thank you for your help.
It works, if you remove spaces while putting numbers to the text fields, otherwise you get NumberFormatException. By the way don't use spaces for aligning the text fields. You can use setColumns or different layout manager. Also you should validate input to be sure there are just numbers, if you want to add them together.
Delete spaces from:
textbox1 = new JTextField(" ");
textbox2 = new JTextField(" ");
cause while parsing to Integer it fails.
Set prefered size of textbox1 and textbox2:
textbox1 = new JTextField();
textbox1.setPreferredSize(new Dimension(20,20));
textbox2 = new JTextField();
textbox2.setPreferredSize(new Dimension(20,20));
Hope I helped :)
I am creating a simple option pane that asks for multiple user inputs. I have specified the labels and text fields, but at the end of my option pane, there lies a text field that doesn't belong to any variable, so I'm guessing it comes along when specifying the option pane.
Here's my code:
JTextField locationField = new JTextField(10);
JTextField usedByField = new JTextField(5);
JTextField commentField = new JTextField(50);
...
myPanel.add(new JLabel("Location: ");
myPanel.add(locationField);
myPanel.add(new JLabel("Used By: ");
myPanel.add(usedByField);
myPanel.add(new JLabel("Comments: ");
myPanel.add(commentField);
...
JOptionPane.showInputDialog(myPanel);
My dialog ends up looking like this, and as you can see there is a stray text field at the bottom of my pane:
My question is, where in my code would I be secretly specifying this? I don't think I am, so how do I go about in order to get rid of this stray text field that I don't need.
Thank you.
The solution is simple: don't use JOptionPane.showInputDialog(...). Instead use JOptionPane.showMessageDialog(...).
The showInputDialog is built to get a single String input from the user, and so it is structured to show an embedded JTextField for this purpose, and returns the String entered into that field, a String that you're not using.
The showMessageDialog on the other hand does not do this, and instead returns an int depending on which of its button has been pressed.
Please have a look at the JOptionPane API for more on this.
Edit: I was wrong. Use a JOptionPane.showConfirmDialog(...) if you want the dialog to supply dialog-handling buttons, such as "OK", "Cancel" or "Yes" and "No" and to allow the user to press these buttons and then get input from the button.
For example:
final JTextField userNameField = new JTextField(10);
final JPasswordField passwordField = new JPasswordField(10);
JPanel pane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2), 0, 0);
pane.add(new JLabel("User Name:"), gbc);
gbc.gridy = 1;
pane.add(new JLabel("Password:"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
pane.add(userNameField, gbc);
gbc.gridy = 1;
pane.add(passwordField, gbc);
int reply = JOptionPane.showConfirmDialog(null, pane, "Please Log-In",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (reply == JOptionPane.OK_OPTION) {
// get user input
String userName = userNameField.getText();
// ****** WARNING ******
// ** The line below is unsafe code and makes a password potentially discoverable
String password = new String(passwordField.getPassword());
System.out.println("user name: " + userName);
System.out.println("passowrd: " + password);
}
which displays:
I am currently constructing a GUI which allows me to add new cruises to the system. I want to write an actionListner which once the user clicks on "ok" then the form input will be displayed as output on the console.
I currently have the following draft to complete this task:
ok = new JButton("Add Cruise");
ok.setToolTipText("To add the Cruise to the system");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
int selected = typeList2.getSelectedIndex();
String tText = typeList2[selected];
Boolean addtheCruise = false;
addtheCruise = fleet.addCruise();
fleet.printCruise();
if (addtheCruise)
{
frame.setVisible(false);
}
else
{ // Report error, and allow form to be re-used
JOptionPane.showMessageDialog(frame,
"That Cruise already exists!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
buttonPanel.add(ok);
Here is the rest of the code to the Form input frame:
contentPane2 = new JPanel (new GridLayout(18, 1)); //row, col
nameInput = new JLabel ("Input Cruise Name:");
nameInput.setForeground(normalText);
contentPane2.add(nameInput);
Frame2.add(contentPane2);
Cruisename = new JTextField("",10);
contentPane2.add(Cruisename);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
confirmPanel = new JPanel ();
confirmPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
confirmPanel.setBorder(BorderFactory.createLineBorder(Color.PINK));
addItinerary = new JButton("Add Itinerary");
confirmPanel.add(Add);
confirmPanel.add(addItinerary );
Frame2.add(confirmPanel, BorderLayout.PAGE_END);
Frame2.setVisible(true);
contentPane2.add(Cruisename);
Frame2.add(contentPane2);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
contentPane2.setBorder(BorderFactory.createLineBorder(Color.black));
//Label for start and end location jcombobox
CruiseMessage = new JLabel ("Enter Start and End Location of new Cruise:");
CruiseMessage.setForeground(normalText);
contentPane2.add(CruiseMessage);
Frame2.add(contentPane2);
/**
* creating start location JComboBox
*/
startL = new JComboBox();
final JComboBox typeList2;
final String[] typeStrings2 = {
"Select Start Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
startL = new JComboBox(typeStrings2);
contentPane2.add(startL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
/**
* creating end location JComboBox
*/
endL = new JComboBox();
final JComboBox typeList3;
final String[] typeStrings3 = {
"Select End Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
endL = new JComboBox(typeStrings3);
contentPane2.add(endL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
//Label for select ship jcombobox
selectShipM = new JLabel ("Select Ship to assign Cruise:");
selectShipM.setForeground(normalText);
contentPane2.add(selectShipM);
Frame2.add(contentPane2);
/**
* creating select ship JCombobox
* select ship to assign cruise
*/
selectShip = new JComboBox();
final JComboBox typeList4;
final String[] typeStrings4 = {
"Select Ship", "Dalton Princess", "Stafford Princess" };
selectShip = new JComboBox(typeStrings4);
contentPane2.add(selectShip);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
I need all form inputs from the code above to be displayed on the console upon completion.
Summary:
1. I have two ships in one fleet
2. To add new cruise, all fields (Name, start date, end date, ship) must be selected.
The Problem:
1. I keep coming up with errors when creating " fleet = new Fleet();" in my constructor. Even though I have declared it in my class.
2. In the draft code below, line 5 states "typeList2", however, I have two JComboBox's - two different type Strings for both drop down menu's (Shown in the rest of the code). How do I input both typeLists to the output rather than just one?
Thank you.
I'm working on a project for school in Java programming. I need to design a GUI that will take in questions and answers and store them in a file. It should be able to contain an unlimited number of questions. We have covered binary I/O.
How do I write the input they give to a file? How would I go about having them add multiple questions from this GUI?
package multiplechoice;
import java.awt.*;
import javax.swing.*;
public class MultipleChoice extends JFrame {
public MultipleChoice() {
/*
* Setting Layout
*/
setLayout(new GridLayout(10,10));
/*
* First Question
*/
add(new JLabel("What is the category of the question?: "));
JTextField category = new JTextField();
add(category);
add(new JLabel("Please enter the question you wish to ask: "));
JTextField question = new JTextField();
add(question);
add(new JLabel("Please enter the correct answer: "));
JTextField correctAnswer = new JTextField();
add(correctAnswer);
add(new JLabel("Please enter a reccomended answer to display: "));
JTextField reccomendedAnswer = new JTextField();
add(reccomendedAnswer);
add(new JLabel("Please enter a choice for multiple choice option "
+ "A"));
JTextField A = new JTextField();
add(A);
add(new JLabel("Please enter a choice for multiple choice option "
+ "B"));
JTextField B = new JTextField();
add(B);
add(new JLabel("Please enter a choice for multiple choice option "
+ "C"));
JTextField C = new JTextField();
add(C);
add(new JLabel("Please enter a choice for multiple choice option "
+ "D"));
JTextField D = new JTextField();
add(D);
add(new JButton("Compile Questions"));
add(new JButton("Next Question"));
}
public static void main(String[] args) {
/*
* Creating JFrame to contain questions
*/
FinalProject frame = new FinalProject();
// FileOutputStream output = new FileOutputStream("Questions.dat");
JPanel panel = new JPanel();
// button.setLayout();
// frame.add(panel);
panel.setSize(100,100);
// button.setPreferredSize(new Dimension(100,100));
frame.setTitle("FinalProject");
frame.setSize(600, 400);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
First:
There are basically two ways to write to a file in java.
ObjectOutputStream(FileOutputStream("blah")) API
PrintWriter("blah") API
Second:
Three or more; use a for.
This is what comes to mind for me when reading JTextField A = new JTextField(); and JTextField B = new JTextField();