Java Swing TextField looking very small - java

I am trying to add a textfield next to some check boxes, but for some reason it looks only 1 char in size?
JButton addStaff = new JButton("Add Staff");
westPanel.add(addStaff);
// bind the button with the listener
addStaff.addActionListener(new StaffHandler());
c1 = new JCheckBox("Home Only?");
westPanel.add(c1);
c2 = new JCheckBox("Offer ShortHand?");
westPanel.add(c2);
t1 = new JTextField("");
westPanel.add(t1);
My output is the following, which looks a bit rubbish.

You can use the constructor new JTextField(int columns)
e.g. JTextField t1 = new JTextField(20);

Related

How to add validation to multiple text fields in JOptionPane?

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

How to plus 2 JTextField numbers?

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 :)

Writing actionListner to display form input on console upon confirmation

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.

Throwing a value to the other class

Can you help me with this?
Here is the code first:
public RegistrationForm(){
super("Registration Form (Assignment One)");
setLayout(new GridLayout(6,2));
l[0] = new JLabel("Name: ");
l[0].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[0]);
tf[0] = new JTextField();
tf[0].setToolTipText("Enter Your Full Name");
add(tf[0]);
l[1] = new JLabel("Age: ");
l[1].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[1]);
tf[1] = new JTextField();
tf[1].setToolTipText("Enter Your Age");
add(tf[1]);
l[2] = new JLabel("Birthday: ");
l[2].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[2]);
tf[2] = new JTextField();
tf[2].setToolTipText("Enter Your Birthday");
add(tf[2]);
l[3] = new JLabel("Address: ");
l[3].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[3]);
tf[3] = new JTextField();
tf[3].setToolTipText("Enter Your Address");
add(tf[3]);
l[4] = new JLabel("Contact Number: ");
l[4].setFont(new Font("Calibri Head",Font.BOLD,12));
add(l[4]);
tf[4] = new JTextField();
tf[4].setToolTipText("Enter Your Contact Number");
add(tf[4]);
b[0] = new JButton("Submit");
b[0].addActionListener(this);
add(b[0]);
b[1] = new JButton("Clear");
b[1].addActionListener(this);
add(b[1]);
}
So When I input a value to all and press "Submit" the previous class will close and another class will open and there it will show the value of the things I inputted from the previous class. . .
There is no default value to JTextfields, I'm going to enter the value myself.
How can i throw(I mean pass) a value to the other class?
Here is the code i have so far:
This is my method:
public String name(){
return tf[0].getText();
}
This is from my Other class:
public Form{
RegistrationForm form = new RegistrationForm();
JTextField name = form.name();
add(name);
}
You don't need to throw anything. Whatever class that displays this dialog will hold a reference to the instance of this class and can simply query the state of the fields once the dialog returns. This is much easier if the dialog window is a modal dialog such as a modal JDialog or a JOptionPane.
For instance, please look at my code in this example.
Edit
Also, this confuses me:
public Form{
RegistrationForm form = new RegistrationForm();
JTextField name = form.name();
add(name);
}
Does this code display the RegistrationForm object? Is RegistrationForm in fact a modal JDialog? It is very unusual to extract a JTextField from one GUI and add it to another, and I'm pretty sure that you don't want to do this. Again, what you want to do is:
Display your RegistrationForm as a modal JDialog.
After it returns, call getter methods on the RegistrationForm object that extracts the Strings held by the text fields of the object.
For more details, you'll still need to tell us a lot more about your code and your problem.

Recording user choice java

I have a scroll box where a user can choose between options. If I want the user's choice to print elsewhere, what will I need to call? I already have where I want the user choice.
results.setText();
What would go in the parenthesis?
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.*;
public class container implements ActionListener
{
JPanel panels;
Timer timer;
JTextField userTypingRegion;
JTextArea results;
JComboBox<Integer> ageEntries;
JComboBox<String> raceList;
public void init(Container pane)
{
JButton switcher = new JButton("Next / Back");
switcher.addActionListener(this);
JPanel infoPage = new JPanel();
infoPage.setBackground(Color.BLACK);
//CENTER
JPanel panelCenter = new JPanel();
panelCenter.setBackground(Color.GRAY);
panelCenter.setLayout(new BoxLayout(panelCenter, BoxLayout.Y_AXIS));
infoPage.add(BorderLayout.CENTER, panelCenter);
///Gender
JPanel genderSelection = new JPanel();
JLabel gender = new JLabel("Gender:");
JCheckBox checkGenderMale = new JCheckBox("Male");
JCheckBox checkGenderFemale = new JCheckBox("Female");
genderSelection.add(gender);
genderSelection.add(checkGenderMale);
genderSelection.add(checkGenderFemale);
panelCenter.add(genderSelection);
///Age
JPanel ageSelection = new JPanel();
JLabel age = new JLabel("Age:");
ArrayList<Integer> ageList = new ArrayList<Integer> ();
for (int i = 1; i <= 100; ++i)
{
ageList.add(i);
}
DefaultComboBoxModel<Integer> modelAge = new DefaultComboBoxModel<Integer>();
for (Integer i : ageList)
{
modelAge.addElement(i);
}
JComboBox<Integer> ageEntries = new JComboBox<Integer>();
ageEntries.setModel(modelAge);
ageSelection.add(age);
ageSelection.add(ageEntries);
panelCenter.add(ageSelection);
///Race
JPanel raceSelection = new JPanel();
JLabel race = new JLabel("Race/Ethnicity:");
String[] raceEntries = {"White", "Black", "Hispanic"
, "Asian/Pacific Islander"
, "Alaska Native/American Indian", "Confused"};
JComboBox<String> raceList = new JComboBox<String>(raceEntries);
raceList.addActionListener(new transferInfo());
raceSelection.add(race);
raceSelection.add(raceList);
panelCenter.add(raceSelection);
///Question 1
JPanel firstQuestion = new JPanel();
JLabel one = new JLabel("How often do you read?");
String[] oneEntries = {"Always", "Often", "Sometimes"
, "Not Often", "What is reading?"};
JComboBox<String> oneAnswer = new JComboBox<String>(oneEntries);
firstQuestion.add(one);
firstQuestion.add(oneAnswer);
panelCenter.add(firstQuestion);
///Question 2
JPanel secondQuestion = new JPanel();
JLabel two = new JLabel("Average time (in minutes) " +
"spent on the computer per day:");
ArrayList<Integer> hourList = new ArrayList<Integer>();
for (int z = 0; z <= 1440; z = z + 30)
{
hourList.add(z);
}
DefaultComboBoxModel<Integer> modelHour = new DefaultComboBoxModel<Integer>();
for (Integer z : hourList)
{
modelHour.addElement(z);
}
JComboBox<Integer> hourEntries = new JComboBox<Integer>();
hourEntries.setModel(modelHour);
secondQuestion.add(two);
secondQuestion.add(hourEntries);
panelCenter.add(secondQuestion);
///Question 3
JPanel thirdQuestion = new JPanel();
JLabel three = new JLabel("Favorite Subject");
String[] threeEntries = {"English", "Math", "Science"
, "Foreign Languages", "History", "Hate them all"};
JComboBox<String> threeAnswer = new JComboBox<String>(threeEntries);
thirdQuestion.add(three);
thirdQuestion.add(threeAnswer);
panelCenter.add(thirdQuestion);
///Question 4
JPanel fourthQuestion = new JPanel();
JLabel four = new JLabel("Average sleep (in minutes) per night:");
ArrayList<Integer> sleepTimeList = new ArrayList<Integer>();
for (int y = 0; y <= 1440; y = y + 30)
{
sleepTimeList.add(y);
}
DefaultComboBoxModel<Integer> modelSleepTime = new DefaultComboBoxModel<Integer>();
for (Integer z : sleepTimeList)
{
modelSleepTime.addElement(z);
}
JComboBox<Integer> sleepTimeEntries = new JComboBox<Integer>();
sleepTimeEntries.setModel(modelSleepTime);
fourthQuestion.add(four);
fourthQuestion.add(sleepTimeEntries);
panelCenter.add(fourthQuestion);
///Question 5
JPanel fifthQuestion = new JPanel();
JLabel five = new JLabel("I am...");
String [] fiveEntries = {"Outgoing", "In the middle", "Shy"};
JComboBox<String> fiveAnswer = new JComboBox<String>(fiveEntries);
fifthQuestion.add(five);
fifthQuestion.add(fiveAnswer);
panelCenter.add(fifthQuestion);
///Question 6
JPanel sixthQuestion = new JPanel();
JLabel six = new JLabel("I am...");
String [] sixEntries = {"Adventurous", "In the middle", "Lazy"};
JComboBox<String> sixAnswer = new JComboBox<String>(sixEntries);
sixthQuestion.add(six);
sixthQuestion.add(sixAnswer);
panelCenter.add(sixthQuestion);
///Question 7
JPanel seventhQuestion = new JPanel();
JLabel seven = new JLabel("I live in the...");
String [] sevenEntries = {"City", "Suburb", "Country", "Narnia"};
JComboBox<String> sevenAnswer = new JComboBox<String>(sevenEntries);
seventhQuestion.add(seven);
seventhQuestion.add(sevenAnswer);
panelCenter.add(seventhQuestion);
///Question 8
JPanel eighthQuestion = new JPanel();
JLabel eight = new JLabel("Please choose the painting you like.");
eighthQuestion.add(eight);
panelCenter.add(eighthQuestion);
///Adding Picture
JPanel pictures = new JPanel();
ImageIcon image = new ImageIcon("C:\\Users\\Kevin\\Desktop\\Left and Right.jpg");
JLabel imageButton = new JLabel();
imageButton.setIcon(image);
pictures.add(imageButton);
panelCenter.add(pictures);
///Question 9
JPanel ninthQuestion = new JPanel();
JCheckBox checkLeft = new JCheckBox("I like the left one!");
JCheckBox checkRight = new JCheckBox("I like the right one!");
ninthQuestion.add(checkLeft);
ninthQuestion.add(checkRight);
panelCenter.add(ninthQuestion);
////Second Card
JPanel programFrame = new JPanel();
programFrame.setBackground(Color.BLACK);
programFrame.setMinimumSize(new Dimension(200, 300));
programFrame.setMaximumSize(new Dimension(800, 700));
programFrame.setPreferredSize(new Dimension(500, 500));
///CENTER DATA COLLECTION REGION
JPanel dataCollectionRegion = new JPanel();
dataCollectionRegion.setBackground(Color.LIGHT_GRAY);
dataCollectionRegion.setLayout(
new BoxLayout(dataCollectionRegion, BoxLayout.Y_AXIS));
programFrame.add(BorderLayout.CENTER, dataCollectionRegion);
///South Region
JPanel southRegion = new JPanel();
southRegion.setBackground(Color.BLACK);
southRegion.setLayout(new BoxLayout(southRegion, BoxLayout.Y_AXIS));
programFrame.add(BorderLayout.NORTH, southRegion);
///Data Components
JLabel sampleWriting = new JLabel("<html>7 Dear friends, let us love one another, for love comes from God. <br>Everyone who loves has been born of God and knows God. 8 Whoever <br>does not love does not know God, because God is love. 9 This is how <br>God showed his love among us: He sent his one and only Son into <br>the world that we might live through him. 10 This is love: not that we <br>loved God, but that he loved us and sent his Son as an atoning sacrifice <br> for our sins. 11 Dear friends, since God so loved us, we also ought <br>to love one another. 12 No one has ever seen God; but if we love one <br> another, God lives in us and his love is made complete in us. <br> 1 Everyone who believes that Jesus is the Christ is born of God, and everyone <br> who loves the father loves his child as well. 2 This is how we know <br> that we love the children of God: by loving God and carrying out his commands. <br> 3 In fact, this is love for God: to keep his commands. And his commands <br> are not burdensome, 4 for everyone born of God overcomes the world. <br> This is the victory that has overcome the world, even our faith. 5 Who <br> is it that overcomes the world? Only the one who believes that Jesus is the Son of God.</html>");
userTypingRegion = new JTextField();
userTypingRegion.addActionListener( this);
dataCollectionRegion.add(sampleWriting);
dataCollectionRegion.add(userTypingRegion);
///Instructions South
JLabel instructions = new JLabel("Instruction: Type the " +
"passage as fast as possible in the space provided.");
instructions.setForeground(Color.white);
JLabel showResult = new JLabel("- - - Results - - -");
showResult.setForeground(Color.white);
showResult.setHorizontalTextPosition(JLabel.CENTER);
results = new JTextArea();
results.setEditable(false);
southRegion.add(instructions);
southRegion.add(Box.createRigidArea(new Dimension(0,5)));
southRegion.add(showResult);
southRegion.add(Box.createRigidArea(new Dimension(0,5)));
southRegion.add(results);
///add cards
panels = new JPanel(new CardLayout());
panels.add(infoPage);
panels.add(programFrame);
pane.add(switcher, BorderLayout.PAGE_START);
pane.add(panels, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent evt)
{
CardLayout layout = (CardLayout)(panels.getLayout());
layout.next(panels);
}
class transferInfo implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
results.setText("Selected: " + raceList.getSelectedItem());
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Biometric Keystroke Dynamics");
container TabChanger = new container();
TabChanger.init(frame.getContentPane());
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
You can see my attempt at resolving this issue near the end of the code. I apologize in advance for my messy coding. (it is my first)
First of all the mistakes you are committing in your code :
You are declaring JComboBox<Integer> ageEntries; and JComboBox<String> raceList; as your instance variables and as your localvariables inside your init(...) method. Don't declare them twice, use only the instance variables or the local variables, as the need be, but do not use them twice.
Always make this a habit of yours to add this ilne frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); as you make an object of JFrame, this helps in shutting down the JFrame window in a good manner.
Now for what to write in results.setText(); . You can make one validation method inside your container class, which will return boolean and will be called inside the actionPerformed(...) method of the NextButton and inside this method check the values as entered by the user as legitimate or not, if they are legal values then use StringBuilder to append it like say
StringBuilder sb = new StringBuilder(); // this will be your instance variable not local.
sb.append((String) ageEntries.getSelectedItem());
sb.append(" "); // Add this space to distinguish between two values.
// and so on for other values.
Once done you can write results.setText(containerObject.sb.toString()); to show these values.

Categories

Resources