so I have an assignment that include GUI that contain:
JTextField that lets user enter an input into the text field
AddButton adds the input into an ArrayList
ListButton displays the content of ArrayList in the JTextArea
The problem is: When I enter [1,2,3] the output only show me the last element [3], how to fix this?
public class Example extends JFrame {
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 300;
private JPanel panel1, panel2;
private JLabel messageLabel;
private JTextField input;
private JTextArea output;
private JButton addButton, listButton;
String userInput;
ArrayList<String> list = new ArrayList<>();
public Example() {
setTitle("Array Exercise");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1 = new JPanel();
panel1.setLayout(new GridLayout(6,1));
messageLabel = new JLabel("Input");
input = new JTextField(5);
addButton = new JButton("Add");
listButton = new JButton("List");
panel1.add(messageLabel);
panel1.add(input);
panel1.add(addButton);
panel1.add(listButton);
add (panel1, BorderLayout.WEST);
output = new JTextArea(12, 10);
panel2 = new JPanel();
panel2.add(output);
add(panel2, BorderLayout.EAST);
setVisible(true);
input.requestFocus();
ButtonListener bh = new ButtonListener();
addButton.addActionListener(bh);
listButton.addActionListener(bh);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
userInput = input.getText();
if (e.getSource() == addButton) {
list.add(userInput);
output.setText(userInput + " added.");
input.setText("");
input.requestFocus();
}
else if (e.getSource() == listButton) {
list.stream().forEach(x-> output.setText(x));
}
}
}
The JTextField its text to a new text for each element in your list. What you have to do is something like this instead:
for(String s : list){
outPut.append(s + "\n");
}
//Use "\n" if you want each string on a new line. Otherwise, skip it
(I used this type of for-loop for clarity)
Now it "adds" (appends) each new String in your list. In your code, it sets the text to the first String. The sets the text to the second String (and so on). So remember to clear the area with perhaps setText(""); every time you want to print out, for example, a new list of Strings.
complementing Oskar's answer:
setTest() sets the whole text of the text area, overwriting the previous content. So the last value set is the (only) one that will be saved at the end.
Since already using Streams, you could use:
output.setText(list.stream().collect(Collectors.joining("\n")));
Related
EDITED
I've probably just stared at the screen for WAYYY too long but I feel the need to submit this question prior to going to sleep incase my delirium remains true...
The problem I'm having is I'm trying to get an int/double from the JTextField textField and convert it to a(n) int/double to use later in a listener, after retrieving it from a listener... ListenForText implements KeyListener, specifically KeyTyped, to obtain, through toString(), and store it in a String txtFldAmnt. After which I will store the result of Integer.parseInt(txtFldAmnt) into fldAmnt (fldAmnt = Integer.pareseInt(txtFldAmnt)) LINE 99 if copied to an editor. Once it's converted into an int I want to be able to manipulate it and then use it again, at LINE 173, to display, in a new window, the fldAmnt. Honestly, I don't really care about whether it's an int or String displayed, but I know a String is required for JTextField. What magic am I missing? Answers are always welcome but I prefer a chance to learn. Also, as I'm fairly new to Java, off topic pointers, criticism, and better ways to implement this code is greatly welcomed :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame{
/**
* wtf is the serial version UID = 1L
*/
private static final long serialVersionUID = 1L;
private JButton wdBtn;
private JButton dpBtn;
private JButton xferBtn;
private JButton balBtn;
private JRadioButton chkRadio;
private JRadioButton savRadio;
private JTextField textField;
private static String txtFldAmnt;
private static int fldAmnt = 0;
private static Double chkBal = 0.00;
private static Double savBal = 0.00;
public static void main(String[] args){
new GUI();
}
public GUI() {
//default location and size
this.setSize(300,182);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("ATM Machine");
//add buttons
wdBtn = new JButton("Withdraw");
dpBtn = new JButton("Deposit");
xferBtn = new JButton("Transfer");
balBtn = new JButton("Show Balance");
chkRadio = new JRadioButton("Checking");
chkRadio.setSelected(false);
savRadio = new JRadioButton("Savings");
savRadio.setSelected(false);
textField = new JTextField("", 20);
final JLabel textLabel = new JLabel("Enter amount: ");
textField.setToolTipText("Enter amount");
//Listener class to pass button listeners
ListenForButton lForButton = new ListenForButton();
wdBtn.addActionListener(lForButton);
dpBtn.addActionListener(lForButton);
xferBtn.addActionListener(lForButton);
balBtn.addActionListener(lForButton);
chkRadio.addActionListener(lForButton);
savRadio.addActionListener(lForButton);
ListenForText textFieldListener = new ListenForText();
textField.addKeyListener(textFieldListener);
//Configure layouts
JPanel PANEL = new JPanel();
PANEL.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,2, 5, 10));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,2,10,10));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(2,1));
//add buttons to their panels
panel1.add(wdBtn);
panel1.add(dpBtn);
panel1.add(xferBtn);
panel1.add(balBtn);
panel2.add(chkRadio);
panel2.add(savRadio);
panel3.add(textLabel);
panel3.add(textField);
PANEL.add(panel1);
PANEL.add(panel2);
PANEL.add(panel3);
this.add(PANEL);
//this.setAlwaysOnTop(true);
this.setVisible(true);
}
//implement listeners
private class ListenForText implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
txtFldAmnt = (e.toString());
fldAmnt = Integer.parseInt(txtFldAmnt);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e){
//maybe do case/switch statements
if (e.getSource() == wdBtn) {
JFrame newFrame = new JFrame("Withdraw Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Withdraw Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == dpBtn) {
JFrame newFrame = new JFrame("Deposit Title");
/*
* Set the newFrame.setSize(300,182); to this comment in the if statement to place
* the window directly over current window
*/
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Deposit Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == xferBtn) {
JFrame newFrame = new JFrame("Transfer Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Transfer Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == balBtn){
JFrame newFrame = new JFrame("Balance Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JTextField newLbl = new JTextField(Integer.toString(fldAmnt));
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
}
}
}
-cheers
EDITED BELOW
Thank for the answers, and I'm sorry for the horrible description... but I found a work around, thoguh I'm not sure if it's appropriate.
with the above example:
fldAmnt = Integer.pareseInt(txtFldAmnt)
i just added a .getText() //Though I rewrote the entire source code
fldAmnt = Integer.pareseInt(txtFldAmnt.getText())
it's worked for me for my entire program.
I wish I didn't have to post my entire code below but I haven't decided on a great place to store all of my code yet.
(SUGGESTIONS ARE WELCOME :D)
but here it is:
import javax.swing.;
import java.awt.GridLayout;
import java.awt.event.;
import javax.swing.border.*;
public class ATM extends JFrame{
//buttons needed
JButton wBtn;
JButton dBtn;
JButton xBtn;
JButton bBtn;
//radios needed
JRadioButton cRadio;
JRadioButton sRadio;
//Text field needed
JTextField txt;
JLabel txtLabel;
static int withdraw = 0;
Double amount = 0.00;
Double cBal = 100.00;
Double sBal = 100.00;
double number1, number2, totalCalc;
public static void main(String[] args){
new Lesson22();
}
public ATM(){
this.setSize(400, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Third Frame");
wBtn = new JButton("Withdraw");
dBtn = new JButton("Deposit");
xBtn = new JButton("Transfer");
bBtn = new JButton("Show Balance");
cRadio = new JRadioButton("Checking");
sRadio = new JRadioButton("Savings");
txtLabel = new JLabel("Amount: $");
txt = new JTextField("", 10);
JPanel thePanel = new JPanel();
// Create an instance of ListenForEvents to handle events
ListenForButton lForButton = new ListenForButton();
wBtn.addActionListener(lForButton);
dBtn.addActionListener(lForButton);
xBtn.addActionListener(lForButton);
bBtn.addActionListener(lForButton);
// How to add a label --------------------------
// Creates a group that will contain radio buttons
// You do this so that when 1 is selected the others
// are deselected
ButtonGroup operation = new ButtonGroup();
// Add radio buttons to the group
operation.add(cRadio);
operation.add(sRadio);
// Create a new panel to hold radio buttons
JPanel operPanel = new JPanel();
JPanel btnPanel1 = new JPanel();
JPanel btnPanel2 = new JPanel();
btnPanel1.setLayout(new GridLayout(1,2));
btnPanel2.setLayout(new GridLayout(1,2));
Border btnBorder = BorderFactory.createEmptyBorder();
btnPanel1.setBorder(btnBorder);
btnPanel1.add(wBtn);
btnPanel1.add(dBtn);
btnPanel2.setBorder(btnBorder);
btnPanel2.add(xBtn);
btnPanel2.add(bBtn);
Border operBorder = BorderFactory.createBevelBorder(1);
// Set the border for the panel
operPanel.setBorder(operBorder);
// Add the radio buttons to the panel
operPanel.add(cRadio);
operPanel.add(sRadio);
// Selects the add radio button by default
cRadio.setSelected(true);
JPanel txtPanel = new JPanel();
txtPanel.add(txtLabel);
txtPanel.add(txt);
thePanel.add(btnPanel1);
thePanel.add(btnPanel2);
thePanel.add(operPanel);
thePanel.add(txtPanel);
thePanel.setLayout(new GridLayout(4,2));
this.add(thePanel);
this.setVisible(true);
txt.requestFocus();
}
private class ListenForButton implements ActionListener{
// This method is called when an event occurs
public void actionPerformed(ActionEvent e){
/******************************************************
* THIS IS FOR CHECKING
*****************************************************/
// Check if the source of the event was the button
if(cRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
cBal -= amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel cLabel = new JLabel(Double.toString(cBal));
JLabel CLBL = new JLabel("Checking: ");
panel.add(CLBL);
panel.add(cLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
amount = Double.parseDouble(txt.getText());
cBal += amount;
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (sBal >= 0 && sBal >= amount){
cBal += amount;
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
/******************************************************
* THIS IS FOR SAVINGS
*****************************************************/
if(sRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
if(sBal >= 0 && sBal >= amount){
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel sLabel = new JLabel(Double.toString(sBal));
JLabel SLBL = new JLabel("Savings: ");
panel.add(SLBL);
panel.add(sLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
try{
amount = Double.parseDouble(txt.getText());
sBal += amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (cBal >= 0 && cBal >= amount){
sBal += amount;
cBal -= amount;
}
else if (cBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
...and by the way can anyone explain this warning message:
The serializable class ATM does not declare a static final serialVersionUID field of type long
If not simply don't bother. I'll keep researching into it when I have time.
This is still not complete, but thank you all for your help!
KeyListener on any JTextComponent is a bad idea.
To monitor changes to a text component, use a DocumentListener, to filter the content that a text component can handle, use a DocumentFilter. See Listening for Changes on a Document, Implementing a Document Filter and DocumentFilter Examples for more details.
In your case, it'd probably better to use a JSpinner or JFormattedTextField as they are designed to handle (amongst other things) numbers
See How to Use Spinners and How to Use Formatted Text Fields for more details
This is for a Java program I'm working on as part of a homework assignment. I don't want the work done for me, but I'm stuck. I'm fairly new to Java, and using NetBeans IDE 7.0.1.
I'm having difficulty with some exception handling when trying to validate user input. This program will log charitable donations from user input. However, I've not been successful in validating the donation amount text field input. If a user inputs text instead of numbers, I would like them to be notified that their input was invalid, and I'd like the exception handling to handle the error and carry on after the user fixes their entry. Any help is greatly appreciated.
Here is my code:
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 510;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
int i = 0;
try {
i = Integer.parseInt (amount);
return true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid Input. Please enter a dollar amount");
return false;
}
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
Here is my revised code. After some user input testing, I'm getting an exception when I use 100.00, 40.00, etc... instead of whole dollar amounts, such as 100, 40, etc.
Any thoughts?
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 550;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if (donationAmt(pledgeField.getText())) {
donationAmt[i] = Double.parseDouble(pledgeField.getText());
}
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //checking for empty field
JOptionPane.showMessageDialog(null, "Please enter a dollar amount");
return false;
}
for(int i = 0; i < amount.length(); i++){ //verifying dollar amount entered as number
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a dollar amount");
return false;
}
}
return true;
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
You can use InputVerifier, discussed here.
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if(donationAmt(pledgeField.getText())){
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i] + " " + charityName[i] + " " + donationAmt[i] + "\n ");
i++;
}
}
}
Something like this would work. This checks so that the amount is not empty and contains only digits based on your exisiting method.
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //check so that the amount field is not empty, pherhaps you can add a check so the amound is not 0 :)
JOptionPane.showMessageDialog(null, "Invalid Input. The amount cannot be empty");
return false;
}
for(int i = 0; i < amount.length(); i++){ //loop thru the string and check so that each char is a digit
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "The amount can contain only numbers");
return false;
}
return true;
If you want to make sure that the amount is not 0, one approach would be to parse amount to int, and check so that parsedAmount<0. This should be done after it's verified that the amount is not empty and is only digits (e.i last:) ) to avoid NPE's and numberformatexception
Class SampleFiveA extends JPanel. This contains textfields, one below the other, each of which has a label on the left. All textfields will be of the same width and positioned against the right border of the panel. SampleFiveA has only one constructor that accepts the following three parameters:
ArrayList names,
ArrayList values,
int cols
I so far created the sample username password screen in GUI but now I have a problem implementing an ArrayList in JPanel one for User Name and the other for password. Kind of stuck there for hours now cant find a proper example to do it. Below is the code I commented what I need to be done using ArrayList.
public class SampleFiveA extends JPanel {
ArrayList<String> names = new ArrayList<String>(); //the text for the labels
ArrayList<String> values = new ArrayList<String>(); // the initial contents of the text fields
int col ; //the number of columns used to set the width of each textfield
public SampleFiveA()
{
JPanel p = new JPanel();
p.setLayout(new GridLayout(2,2));
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.add(lab1 = new JLabel("User Name"));
JTextField txt1 = new JTextField("User Name", JTextField.RIGHT);
p.add(txt1= new JTextField());
JLabel lab2 = new JLabel("Password ", JLabel.LEFT);
p.add(lab2 = new JLabel("Password"));
JPasswordField txt2 = new JPasswordField("*****",JPasswordField.RIGHT );
p.add(txt2 = new JPasswordField());
// names.add(lab1,lab2);// Not right but I want to put the label text to this arrayList
// values.add(txt1,txt2);//
add(p);
};
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new SampleFiveA());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
};
};
you can use
names.add(txt1.getText());
values.add(txt2.getText());
but maybe you should think about a better data structure, e.g. a HashMap and
hashmap.put(txt1.getText(),txt2.getText())
(and you should do this based on some event,e.g. user presses a button, not in the constructor, as otherwise the value will be the one you set before)
Here's a start for you.
It adds a FocusListener to the text fields and makes sure that the content of the ArrayList is updated with the current value when the text field looses focus.
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class Main extends JPanel {
ArrayList<String> names = new ArrayList<String>(); // the text for the
// labels
ArrayList<String> values = new ArrayList<String>(); // the initial contents
// of the text fields
int col; // the number of columns used to set the width of each textfield
public Main() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(2, 2));
names = new ArrayList<String>();
values = new ArrayList<String>();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.add(lab1);
JTextField txt1 = new JTextField("User Name", JTextField.RIGHT);
p.add(txt1);
names.add(lab1.getText());
values.add(txt1.getText());
JLabel lab2 = new JLabel("Password ", JLabel.LEFT);
p.add(lab2);
JPasswordField txt2 = new JPasswordField("*****", JPasswordField.RIGHT);
p.add(txt2);
names.add(lab2.getText());
values.add(txt2.getText());
// names.add(lab1,lab2);// Not right but I want to put the label text to
// this arrayList
// values.add(txt1,txt2);//
txt1.addFocusListener(new ArrayListFocusListener(txt1, values, 0));
txt2.addFocusListener(new ArrayListFocusListener(txt2, values, 1));
add(p);
// Start a thread to print the content of the list for 10 seconds
new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(values);
}
}
}.start();
};
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Main());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
};
class ArrayListFocusListener implements FocusListener {
JTextField textField;
ArrayList<String> backingList;
int myIndex;
public ArrayListFocusListener(JTextField textField,
ArrayList<String> backingList, int myIndex) {
this.textField = textField;
this.backingList = backingList;
this.myIndex = myIndex;
}
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
backingList.set(myIndex, textField.getText());
}
}
};
I'm sure what you are trying to do. You either want to put the JLabel in an ArrayList or the text of that label.
If you want to put the whole JLabel in an ArrayList, you should make a ArrayList<JLabel>. But I take it you want to get the text from the JLabel, so you should write names.add(lab1.getText());.
The constructor you have made doesn't take any parameters. The parameters you have wrote are the instance variable, meaning those are the variables any instance of that class will have. If you want to pass parameters in your constructor you should do what thasc told you.
You write:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.add(lab1 = new JLabel("User Name"));
But since you are already creating the lab1 JLabel you could just write p.add(lab1).
And a final note I think SampleFiveA should better extend JFrame unless you want it to extend JPanel to use it somewhere else. If you need it to be standalone you should change that.
cheers
i am looking to pass values entered in my Textfields into an array list, although i cannot seem to do this. i am able to view the details which have been entered in the console when using
System.out.println(houses.get(1).getHouseNumber())
but this does not post the newly entered values into the arraylist in my code and i can not understand why.
ArrayList and ActionListener code
final ArrayList<House> houses = new ArrayList<House>();
houses.add(new House());
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
House house = new House();
house.setHouseNumber(houseNumber.getText());
house.setStreetName(streetName.getText());
house.setTown(town.getText());
house.setPostcode(postcode.getText());
houses.add(house);
System.out.println(houses.get(1).getHouseNumber());
System.out.println(houses.get(1).getStreetName());
System.out.println(houses.get(1).getTown());
System.out.println(houses.get(1).getPostcode());
}
});
GUI Code
public void go(){
frame = new JFrame();
panel = new JPanel();
HouseNumberLabel = new JLabel ("House Number");
houseNumber = new JTextField ("");
StreetNameLabel = new JLabel ("Street name");
streetName = new JTextField ("");
TownLabel = new JLabel ("Town");
town = new JTextField ("");
PostcodeLabel = new JLabel ("Postcode");
postcode = new JTextField ("");
BedsLabel = new JLabel ("Number of beds");
beds = new JTextField ("");
PriceLabel = new JLabel ("Price (£)");
price = new JTextField ("");
TypeLabel = new JLabel ("Building Type");
type = new JTextField ("");
button = new JButton("Submit");
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true)
House Class code
class House {
private String houseNumber;
private String streetName;
private String town;
private String postcode;
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
String houseNumber;
This variable is not needed, get rid of it;
JTextField HouseNumber1;
This does not follow proper java naming conventions. Variable names do not start with an upper cased character. The variaible name should be:
JTextField houseNumber;
Now in the ActionListener you get the text from the text field directly:
house.setHouseNumber( houseNumber.getText() );
Edit:
okButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println( "ok" );
}
});
used it to print out the array and was presented with [demo2.House#e2eec8, demo2.House#aa9835].
House#e2eec8 and House#aa9835refer to the first and second house in the ArrayList, respectively. Try something like this instead:
System.out.println(houses.get(0).getHouseNumber());
Addendum:
I cannot see the details in the ArrayList in my code.
You can override toString() in House; that way you can just do this:
System.out.println(houses.get(0));
Addendum:
This does not post the newly entered values into the ArrayList.
System.out.println(houses.get(1).getHouseNumber());
Right, this always gets the second entry, starting from 0. The following will always get the last one sent to add().
System.out.println(houses.get(houses.size() - 1).getHouseNumber());
Addendum: You can loop through the houses like this.
for (House h : houses) {
System.out.print(h.getHouseNumber());
System.out.print(h.getStreetName());
...
}
Problems:
I am unable to get the values of the JTextFields or the rollResultTotal to update.
Even if the data in the JTextFields are valid, a NumberFormatException is still thrown.
Questions: Why don't the variables stay? Is this due to declaration in the class itself? Is it possible to update a JLabel panel to show an updated result? (tried this, epic failure)
Thanks in advance for any input and examples.
/*
ITP-120: Final Project
Programmer: S. Schnoor
Date: November 7th, 2009
Filename: SchnoorProject.java
Purpose: To generate "dice rolls" - a tally of random values as defined by the user,
including a final calculation modifier.
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.lang.*;
import java.math.*;
public class SchnoorProject extends JFrame implements ActionListener, EventListener
{
// Declare Class Variables
int sidesToRoll, diceToRoll, diceLeft, modifier, rollResult, rollResultTotal;
String getSides, getDice, getModifier;
JTextField inputSides = new JTextField();
JTextField inputDice = new JTextField();
JTextField inputModifier = new JTextField();
Random roll;
// Panels and Buttons
JPanel rollPanel;
JButton newRollButton, helpButton, exitButton;
// Create Colors
Color darkPurple = new Color ( 80, 0, 80);
Color darkGold = new Color (255, 215, 0);
Color darkCoal = new Color ( 24, 24, 24);
Color crimson = new Color (127, 12, 12);
Color ltSilver = new Color (140, 140, 180);
public static void main(String args[])
{
JFrame frame = new SchnoorProject();
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
}
public SchnoorProject()
{
// Construction of Components
rollPanel = new JPanel();
getContentPane().add(rollPanel);
JLabel sidesLabel = new JLabel ("Enter the number of sides on each die below. (1 to 99)");
sidesLabel.setForeground(darkGold);
sidesLabel.setHorizontalAlignment(sidesLabel.CENTER);
JTextField inputSides = new JTextField("6");
inputSides.setBackground(darkCoal);
inputSides.setForeground(darkGold);
inputSides.setHorizontalAlignment(inputSides.CENTER);
JLabel diceLabel = new JLabel ("Enter the number of dice to roll below. (1 to 99)");
diceLabel.setForeground(darkGold);
diceLabel.setHorizontalAlignment(diceLabel.CENTER);
JTextField inputDice = new JTextField("3");
inputDice.setBackground(darkCoal);
inputDice.setForeground(darkGold);
inputDice.setHorizontalAlignment(inputDice.CENTER);
JLabel modifierLabel = new JLabel ("Enter the final modifier below. (-99 to 99)");
modifierLabel.setForeground(darkGold);
modifierLabel.setHorizontalAlignment(modifierLabel.CENTER);
JTextField inputModifier = new JTextField("2");
inputModifier.setBackground(darkCoal);
inputModifier.setForeground(darkGold);
inputModifier.setHorizontalAlignment(inputModifier.CENTER);
JButton newRollButton = new JButton("ROLL");
newRollButton.setBackground(darkCoal);
newRollButton.setForeground(darkGold);
newRollButton.addActionListener(this);
JButton helpButton = new JButton("Help/About");
helpButton.setBackground(darkCoal);
helpButton.setForeground(ltSilver);
helpButton.addActionListener(this);
JButton exitButton = new JButton("Exit");
exitButton.setBackground(darkCoal);
exitButton.setForeground(crimson);
exitButton.addActionListener(this);
//Conversions
getSides = inputSides.getText();
getDice = inputDice.getText();
getModifier = inputModifier.getText();
sidesToRoll = Integer.parseInt(getSides);
diceToRoll = Integer.parseInt(getDice);
modifier = Integer.parseInt(getModifier);
diceLeft = diceToRoll;
//rollResultTotal = rollResultTotal;
// Paneling
rollPanel.setLayout(new GridLayout (3,3));
rollPanel.setBackground(darkPurple);
rollPanel.setForeground(darkGold);
rollPanel.add(sidesLabel);
rollPanel.add(diceLabel);
rollPanel.add(modifierLabel);
rollPanel.add(inputSides);
rollPanel.add(inputDice);
rollPanel.add(inputModifier);
rollPanel.add(newRollButton);
rollPanel.add(helpButton);
rollPanel.add(exitButton);
}
// Implement ActionListener for multiple JButtons
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
if ("Help/About".equals(arg))
{
JOptionPane.showMessageDialog(null,"This application generates random values, based on the parameters input by the user.\nPlease choose number of dice, sides on each die, and a +/- roll modifier.\nIf no roll modifier is needed, enter 0 (numeric zero) in the modifier field.\n(The starting numbers tell the program to roll 3 six-sided dice and add 2 or '3d6+2'.)","Help/About",JOptionPane.INFORMATION_MESSAGE);
}
if ("Exit".equals(arg))
{
System.exit(0);
}
if ("ROLL".equals(arg))
{
try
{
while (diceLeft>0)
{
getSides = inputSides.getText();
sidesToRoll = Integer.parseInt(getSides);
if(sidesToRoll<1 || sidesToRoll>99) throw new NumberFormatException();
else
getDice = inputDice.getText();
diceToRoll = Integer.parseInt(getDice);
if(diceToRoll<1 || diceToRoll>99) throw new NumberFormatException();
else
getModifier = inputModifier.getText();
modifier = Integer.parseInt(getModifier);
if(modifier<-99 || modifier>99) throw new NumberFormatException();
else
rollResult = roll.nextInt(sidesToRoll)+1;
rollResultTotal = rollResultTotal + rollResult;
diceLeft--;
}
}
catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(null,"You must enter an integer within the given range of each field.","ROLL",JOptionPane.INFORMATION_MESSAGE);
diceLeft = 0;
}
{ //Display the Roll Formula and Result
JOptionPane.showMessageDialog(null,"You entered a roll of " + (diceToRoll) + "d" + (sidesToRoll) + "+(" + (modifier) + ").\nYou rolled " + (rollResultTotal) + "!");
}
;}
;}
}
You initialize this member variable, but you never add this field to the UI:
JTextField inputSides = new JTextField(" ");
Here you read from this text field that still contains the String " ", which is not an integer.
getSides = inputSides.getText();
sidesToRoll = Integer.parseInt(getSides);
When you build your UI in the constructor, you declare another, local variable with the same name, pointing to a new object:
JTextField inputSides = new JTextField("6");
This is the object that appears in the UI. The local variable inputSides hides the member variable of the same name.
As an aside, this is not the right way to compare strings:
arg == "ROLL"
This only works because arg is pointing to the same, interned object instance. The correct way to compare these values would be:
"ROLL".equals(arg)
EDIT:
The trick you are missing is in thinking about the objects you are creating and which ones your reference variables are pointing at.
Consider this simplified version of your code:
public class ObjectReferences {
private final JLabel label = new JLabel("I am FOO"); // label 1
public ObjectReferences() {
JLabel label = new JLabel("I am BAR"); // label 2
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
onclick();
}
});
// will display "I am BAR"
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLayout(new FlowLayout());
frame.add(label); // label 2
frame.add(button);
frame.setVisible(true);
}
public void onclick() {
// will display "I am FOO"
JOptionPane.showMessageDialog(null, label.getText()); // label 1
}
public static void main(String[] args) {
new ObjectReferences();
}
}
Two label objects are created, but only one is added to the frame. label 1 is referenced by the member variable and this is the one visible to the onclick() method. Within the constructor, label 2 is referenced by a local variable called label that hides the member variable called label.
Your intent is to write something like this instead:
public class ObjectReferences {
private final JLabel label = new JLabel("I am FOO");
public ObjectReferences() {
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
onclick();
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(button);
frame.setVisible(true);
}
public void onclick() {
JOptionPane.showMessageDialog(null, label.getText());
}
public static void main(String[] args) {
new ObjectReferences();
}
}