Hot questions for Using JTextField in gettext

Question:


Answer:

In your myTextField constructor I assume you wanted to initialize the JTextField field; instance variable but instead you created a local variable JTextField label = new JTextField(defaultText);.

I believe you should change the JTextField label = new JTextField(defaultText); in your constructor to:

 field = new JTextField(defaultText);
 frame.add(field);
 field.setBounds(xPos, yPos, xSize, ySize);

Then on wards if you invoke the getter getText() you won't face any NullPointerException.

Question:

2 different bugs, and I have no idea what is causing either of them. They both seem to be in the actionPerformed methods. These are 3 different files, sorry for the bad formatting, I can never get it to work properly.

package A8;

import javax.swing.*;

import java.awt.*;

public class a8main {

public static final int RES_X = 600;
public static final int RES_Y = 125;

public static JFrame window;
public static JPanel panel = new JPanel();
public static RatePanel ratePanel = new RatePanel();
public static MinutesPanel minutesPanel = new MinutesPanel();

public static void main(String[]args){
    createWindow();
    populateWindow();
}

public static void createWindow(){
    window = new JFrame();
    window.setTitle("A8 Long Distance Communications");
    window.setSize(RES_X, RES_Y);
    window.setEnabled(true);
    window.setVisible(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void populateWindow(){
    ratePanel.populatePanel(panel);
    minutesPanel.populatePanel(panel);
    window.add(panel);
}

}


package A8;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MinutesPanel implements ActionListener{

JTextField field = new JTextField();
JLabel minuteLabel = new JLabel();

int callTime;
double chosenRate;

public void populatePanel(JPanel Panel){
    createPanelObjects();
    Panel.add(minuteLabel);
    Panel.add(field);
}

public void createPanelObjects(){
    chosenRate = RatePanel.chosenRate;
    field.setColumns(10);
    minuteLabel = new JLabel("Enter length of call in minutes");
    field.addActionListener(new MinutesPanel());
}
public void displayCallPrice(){
    JOptionPane dialogBox = new JOptionPane();
    double cost = RatePanel.chosenRate * callTime;
    dialogBox.showMessageDialog(null, "The cost of your call is $" + cost);

}

@Override
public void actionPerformed(ActionEvent e) {
    String callStr;
    callStr = field.getText();  //problem is here.
    //callStr = "3";
    System.out.print(callStr);
    callTime = Integer.parseInt(callStr);
    System.out.print(callTime);
System.out.print(RatePanel.chosenRate);

displayCallPrice();

}

}


package A8;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class RatePanel implements ActionListener{

    public static final double DAY_RATE = 0.07;
    public static final double EVENING_RATE = 0.12;
    public static final double OFFPEAK_RATE = 0.05;
    public static double chosenRate = DAY_RATE; //Because button defaults to day rate it is init to that rate.

    JLabel categoryLabel = new JLabel();
    JRadioButton dayButton = new JRadioButton();
    JRadioButton eveningButton = new JRadioButton();
    JRadioButton offpeakButton = new JRadioButton();
    ButtonGroup buttons = new ButtonGroup();

    public void populatePanel(JPanel Panel){
        createPanelObjects();
        Panel.add(categoryLabel);
        Panel.add(dayButton);
        Panel.add(eveningButton);
        Panel.add(offpeakButton);
    }

    public void createPanelObjects(){
        categoryLabel = new JLabel("Select a rate category");
        dayButton = new JRadioButton("Day rate: $" + DAY_RATE);
        eveningButton = new JRadioButton("Evening rate: $" + EVENING_RATE);
        offpeakButton = new JRadioButton("Offpeak rate: $" + OFFPEAK_RATE);
        dayButton.setSelected(true);    //Used to make it impossible to not select a rate, prevents bugs.
        buttons.add(dayButton);
        buttons.add(eveningButton);
        buttons.add(offpeakButton);
        dayButton.addActionListener(new RatePanel());
        eveningButton.addActionListener(new RatePanel());
        offpeakButton.addActionListener(new RatePanel());

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(dayButton.isSelected()){
            chosenRate = DAY_RATE;
            System.out.println(DAY_RATE);
        }
        if(e.getSource() == eveningButton){
            chosenRate = EVENING_RATE;
            System.out.println(EVENING_RATE);
        }
        if(e.getSource() == offpeakButton){
            chosenRate = OFFPEAK_RATE;
            System.out.println(OFFPEAK_RATE);
        }
            System.out.println(e.getSource() == eveningButton);
            System.out.println(dayButton.isSelected());
    }


}

Answer:

You should not create a new instance of your ActionListener for every component.

Since your panels implement ActionListener, you are creating new instances of them every time you are calling addActionListener().

Instead of this:

field.addActionListener(new MinutesPanel());

// ...

eveningButton.addActionListener(new RatePanel());
offpeakButton.addActionListener(new RatePanel());

You should do this:

field.addActionListener(this);

// ...

eveningButton.addActionListener(this);
offpeakButton.addActionListener(this);

Question:

I have a class with over 50 JTextfield they all contain text

How to get the text from all Textfield without calling the fields in the code again.

I tried:

    Field[] fields = getClass().getDeclaredFields();       
    for (Field field : fields) {        
        if (field.getName().contains("_") == true) {
            // .getText();
        }
    }

Then I must get the text from the fields but how to manage this??

Or have someone a better idea to the the values??


Answer:

As Hovercraft Full Of Eels suggested, a clean implementation separates the matter : grouping fields gather and performing a processing on them. Especially, if grouping is performed by reflection. The following code is more readable and maintainable.

public class MyComponent extends JFrame{
  List<JTextField> fields = new ArrayList(); 

  private JTextField textField1;
  private JTextField textField2;
  private JTextField textField3;

  public MyComponent(){
   textField1 = new JTextField ("");
   textField2 = new JTextField ("");
   textField3 = new JTextField ("");
   addTextFieldInList(textField1, textField2, textField3);
  }

  public void addTextFieldInList(JTextField fieldArgs...) {
    fields.addAll(Arrays.asList(fieldArgs));
  }

  public void iterateAllTextFields(){
    for (JTextField field : fields){
      String yourValue = field.getText();
    }    
}

UPDATE after the update of the question where it is specified that the processing handle more than over 50 JTtextField.

In this case, another solution that which I proposed could be more suitable. Indeed, with a dozen of fields, risking to forget to add a JTextField in the list is not very probable but with over 50, we can understand that is a error-prone processing. Creating your custom JTextField is maybe a better alternative. The idea is the following : extending the JTextField with a new class JTextFieldWatched and forcing JTextFieldWatched constructor with an additional parameter : a object which registers JTextField instances.

JTextFieldWatched which extends JTextField :

public class JTextFieldWatched extends JTextField{
  public JTextFieldWatched(String text, JTextFieldWatcher textFieldWatcher){
    super(text);
    if (textFieldWatcher==null){
      // force the constraint
      throw new IllegalArgumentException("textFieldWatcher is mandatory");
    }        
     textFieldWatcher.add(this);
  }
}

A class which registers JTextfield instances :

public class JTextFieldWatcher {
   List<JTextField> fields = new ArrayList(); 

   public void add(JTextField textField){
      fields.add(textField);
   }   

   public List<JTextField> getAllTextField(){
      return new ArrayList(fields);
   }
}

How to use these classes:

public class MyComponent extends JFrame{
  private JTextFieldWatcher fieldsWatcher = new JTextFieldWatcher();

  private JTextFieldWatched textField1;
  private JTextFieldWatched textField2;
  private JTextFieldWatched textField3;

  public MyComponent(){
   textField1 = new JTextFieldWatched ("",fieldsWatcher);
   textField2 = new JTextFieldWatched ("",fieldsWatcher);
   textField3 = new JTextFieldWatched ("",fieldsWatcher);
  }   

  public void iterateAllTextFields(){
    for (JTextField field : fieldsWatcher.getAllTextField()){
      String yourValue = field.getText();
    }    
  }
}

All code is written at the hand without IDE, so sorry if any mistake.

Question:

I tell one button's text to change to name and instead the text changes to this:

javax.swing.JTextField[,3,140,200x25,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@2d5921cd,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]'s turn.

Why and what is this and how can I fix it? here is the code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;


public class Project {
static JTextField name = new JTextField();
static JTextField name2 = new JTextField();
static String name1 = name.getText();
static String nameTwo = name2.getText();
static JFrame frame = new JFrame("frame");
static JFrame frame2 = new JFrame("2nd frame");
static JButton button = new JButton("Submit");
static JButton button2 = new JButton(name1 + "'s turn.");
static JButton button3 = new JButton("Press");
static boolean a = true;

//actionlistener for 'button3'
static class Press implements ActionListener{
    public void actionPerformed(ActionEvent e){
        if(a==true){
        button2.setText(name2 + "'s turn.");
        a=false;
        } else {
            button2.setText(name + "'s turn");
            a=true;
        }
        //getting the button's text so I could copy it because it wouldn't fit on the button.
        System.out.println(button2.getText());
    }
}

//actionlistener for 'button'
static class Submit implements ActionListener{
    public void actionPerformed(ActionEvent e){
        frame.setVisible(false);
        frame2.setVisible(true);
        name1 = name.getText();
        nameTwo = name2.getText();
        button2.setText(name1 + "'s turn.");

    }
}

public static void main(String[] args){
    //setting up 'frame'
    frame.setLayout(null);
    frame.setSize(400, 400);
    frame.setVisible(true);
    //setting up 'frame2'
    frame2.setLayout(null);
    frame2.setSize(400, 400);
    //setting bounds
    name.setBounds(3, 70, 200, 25);
    name2.setBounds(3, 140, 200, 25);
    button.setBounds(220, 70, 100, 90);
    button2.setBounds(3, 200, 300, 75);
    button3.setBounds(0, 0, 300, 75);
    //adding actionlisteners
    button.addActionListener(new Submit());
    button3.addActionListener(new Press());
    //adding buttons to 'frame2'
    frame2.add(button3);
    frame2.add(button2);
    //adding buttons to 'frame'
    frame.add(name);
    frame.add(name2);
    frame.add(button);
}
}

Answer:

name2 and name are JTextField objects therefor you are setting the buttons text to the objects memory address information from here:

button2.setText(name2 + "'s turn.");

It should be button2.setText(name2.getText() + "'s turn."); to get the actual text from the JTextField that you inputted.

Question:

I am a complete newb to Java and I don't quite understand why I am not able to getText() from the JTextFields I have created.

I want to be able to create a new User with the email and password that has been input, but I am getting a nullPointerException on the JTextFields emailText and passwordText, presumably because they are remaining null even after something is typed into the fields after running the program.

Also, I know this isn't secure at all, but that's okay for now.

Thanks

import javax.swing.*;

import java.util.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;

public class Login {
  JFrame frame;
  JPanel panel;
  JTextField emailText;
  JPasswordField passwordText;
  ObjectOutputStream out;
  ObjectInputStream in ;

  public static void main(String[] args) {
    new Login().go();
  }

  public void go() {
    frame = new JFrame("Npact Login");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    BorderLayout layout = new BorderLayout();
    JPanel background = new JPanel(layout);
    background.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    Box buttonBox = new Box(BoxLayout.Y_AXIS);
    Font bigFont = new Font("sanserif", Font.BOLD, 24);

    JLabel instructions = new JLabel("Welcome.");
    instructions.setFont(bigFont);
    JLabel instructions2 = new JLabel("To begin, enter the email and password");
    instructions2.setFont(bigFont);
    buttonBox.add(instructions);
    buttonBox.add(instructions2);

    JLabel emailLabel = new JLabel("Email:");
    JTextField emailText = new JTextField(30);
    emailText.requestFocus();
    buttonBox.add(emailLabel);
    buttonBox.add(emailText);

    JLabel passwordLabel = new JLabel("Password:");
    JPasswordField passwordText = new JPasswordField(30);
    passwordText.addActionListener(new MyStartActionListener());
    buttonBox.add(passwordLabel);
    buttonBox.add(passwordText);

    JButton start = new JButton("Get Started!");
    start.addActionListener(new MyStartActionListener());
    buttonBox.add(start);

    frame.getContentPane().add(buttonBox);
    frame.setSize(1000, 250);
    frame.setVisible(true);
  }

  public class MyStartActionListener implements ActionListener {
    public void actionPerformed(ActionEvent a) {
      String name = emailText.getText();
      char[] pass = passwordText.getPassword();

      User newUser = new User(name, pass);
      try {
        out.writeObject(newUser);
      } catch (Exception ex) {
        System.out.println(ex);
      }
    }
  }
}
package co.npact;

public class User {
  private String email;
  private char[] password;

  public User(String e, char[] p) {
    e = email;
    p = password;
  }

  public String getEmail() {
    return email;
  }

  public char[] getPassword() {
    return password;
  }
}

Answer:

You defined your text fields twice. Once as an instance variable and once as a local variable. Get rid of the local variable. The code should be:

//JTextField emailText = new JTextField(30);
emailText = new JTextField(30);

Question:

´┐╝Create a program where you can enter a colour name into a textfield then use that colour to set the panel background colour with the colour specified in the text field Im having trouble getting the output

import javax.swing.*;

import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;

public class textfield implements  ActionListener{

    JTextField Input;
    JPanel color;
    JButton Button;

    public JPanel createContentPane (){

        // We create a bottom JPanel to place everything on.
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(null);

        // Creation of a Panel to contain the JLabels
        Input = new JTextField ("color", 35);
        Input.setBackground (Color.white);
        Input.setLocation(50,50);
        Input.setSize(100, 30);
        Input.addActionListener (this);
        totalGUI.add(Input);

        color = new JPanel();
        color.setBackground (Color.white);
        color.setLocation(200, 50);
        color.setSize(200, 100);
        totalGUI.add(color);


        totalGUI.setOpaque(true);
        return totalGUI;
    }

    public void actionPerformed(ActionEvent e) {

        String text = Input.getText();
        { if (text == "green")
            color.setBackground(color.green);
        }
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("Assignment");

        textfield demo = new textfield();
        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 300);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Answer:

There are a few problems.

  1. You should compare equality of strings with equals method and not with ==.

  2. Change color.green to Color.GREEN

    public void actionPerformed(ActionEvent e) {
    
        String text = Input.getText();
        if (text.equals("green"))
        {
            color.setBackground(Color.GREEN);
        }
    }
    

For more than one color, you can use if-else or switch case

Using if-else:

   public void actionPerformed(ActionEvent e) {

        String text = Input.getText();
        if (text.equals("green"))
        {
            color.setBackground(Color.GREEN);
        }
        else if(text.equals("red"))
        {
            color.setBackground(Color.RED);
        }
        else if(text.equals("yellow"))
        {
            color.setBackground(Color.YELLOW);
        }
        else
        {
            color.setBackground(Color.BLUE);
        }

    }

Using switch case:

public void actionPerformed(ActionEvent e) {

    String text = Input.getText();

    switch (text) {
        case "green":
            color.setBackground(Color.GREEN);
            break;
        case "red":
            color.setBackground(Color.RED);
            break;
        case "yellow":
            color.setBackground(Color.YELLOW);
            break;
        case "blue":
            color.setBackground(Color.BLUE);
            break;

    }

}

Question:

Here is my code Its asking to me set changeName to a static variable. This wouldnt make sense because I'm trying to capture user input.

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;

import CourseProject.General.exitApp;

public class Options extends JPanel{

    private JLabel changeLabel;
    private JTextField changeName;
    private JButton setName;
    private JButton exitButton;

    public Options(){
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.NORTH;
        setBackground(Color.WHITE);
        super.setLayout(gridbag);
        c.insets = new Insets(10, 10, 10, 10);

        changeLabel = new JLabel("Change Company Name:");
        changeName = new JTextField(10);
        setName = new JButton("Set New Name");
        exitButton = new JButton("Exit");       

        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        add(changeLabel, c);        

        c.gridx = 0;
        c.gridy = 1;    
        add(changeName, c);     

        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        add(setName, c);
        setName.addActionListener(new setNameAction());


        c.gridx = 1;
        c.gridy = 2;    
        add(exitButton, c);
        exitButton.addActionListener(new exitApp());
        exitButton.setSize(40,40);

    }
    static class setNameAction implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            String str = "";
            str = changeName.getText();
        }
    }

    static class exitApp implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }
}

I'm specifically having a problem with this part of the code

static class setNameAction implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String str = "";
        str = changeName.getText();
    }
}

Its asking to me set changeName to a static variable. This wouldnt make sense because I'm trying to capture user input.


Answer:

You inner class is declared static...

static class setNameAction ...

Remove the static reference from the class declaration if you want to be able to reference the instance fields of the outer class...

Otherwise you will be required to pass an instance of Options or JTextField to the setNameAction class.

You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Question:

I am trying to use getText() method from a JTextFeild in an ActionListener attatched with it ... the problem is I don't have a reference that points to it ... that is I'm adding those textFeilds with in a loop that takes a string from arraylist and showing new textFeild , I searched the Internet trying to find a way to use getText() but it was pointless because I have no ref. on it , my question is how to get the text in the JTextFeild in this action Listener , and is there is any way to get a reference to this JTextFeild that the action performed on ????

 JTextField t;
 for(MyClass m: MyArraylist) {
     t=new JTextField(m.toString());
     t.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    System.out.println(getText());
                    }
                    });
      }

I have tried getText(); super.getText(); t.getTaxt(); and for sure it will not work because t always changes ,also i tried system.out.println(m.toString()); and does not work


Answer:

You should get the source for the event and cast it to the TextField

t.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField tf = (TextField) e.getSource();
        System.out.println(tf.getText());
    }
});

Question:

I'm setting up a simple program that collects your name and then returns it in the console. The window opens successfully but when I enter text into 'jTextFieldPlayerName' and press 'continue' The console prints 'Your name is: null'. I am trying to make the console print out what you entered in 'jTextFieldPlayerName' (ex. Your name is: CrashDive) rather than 'Your name is: null'. -Thanks

package bin;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class main extends JPanel implements ActionListener {
protected JLabel text1;
protected JButton continue;
protected JTextField jTextFieldPlayerName;
protected String playerName;

public main() {

    text1 = new JLabel("<html><center>Before we can start we need to know your name.<br><html>");
    startText1.setVerticalTextPosition(JLabel.TOP);
    startText1.setHorizontalTextPosition(JLabel.CENTER);

    jTextFieldPlayerName = new JTextField();
    jTextFieldPlayerName.setPreferredSize(new Dimension(300,20));

    continue = new JButton("Continue");
    continue.setMnemonic(KeyEvent.VK_D);
    continue.addActionListener(this);
    continue.setVerticalTextPosition(AbstractButton.CENTER);
    continue.setHorizontalTextPosition(AbstractButton.CENTER);

    add(text1);
    add(jTextFieldPlayerName);
    add(continue);

    String playerName = jTextFieldPlayerName.getText();
}
public void actionPerformed(ActionEvent evt) {
    Object src = evt.getSource();

    if (src == startText1Continue && jTextFieldPlayerName.getText().length() > 0) {     
        System.out.println("Your name is: " +playerName);   
    }
}

private static void createAndShowGUI() {
    JFrame frame = new JFrame("Test Game");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main newContentPane = new main();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.setSize(1400, 700);
    frame.setVisible(true);
}
public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();  
        }
    });
}       

}


Answer:

You should place String playerName = jTextFieldPlayerName.getText(); inside actionPerformed method as you are printing global playerName but it's never been initialized thats why it prints null.

You can do something like below.

public void actionPerformed(ActionEvent evt) {
    Object src = evt.getSource();
    String playerName = jTextFieldPlayerName.getText();

    if (src == startText1Continue && playerName.length() > 0) {     
        System.out.println("Your name is: " +playerName);   
    }
}