Hot questions for Using JTextField in jcheckbox

Question:

I am creating a ManageUsers GUI which will look like this:

I want the checkboxes to go next to the names in a list that were entered from the Add New User section. I know that most of it is not done but Here's what i have so far:

AddUsers

public class AddUsers {

   private String userName;

   public AddUsers(String userName) {
      this.userName = userName;
   }

   public AddUsers() {
      userName = "";
   }   

   public void setUserName(String userName) {
      this.userName = userName;   
   }

   public String getUserName() {
      return userName;
   }

   public String toString() {
      return userName + "\n";
   }

}      

ManageUsersGUI

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.awt.TextField;


public class ManageUsersGUI1 extends JPanel {
    public static ArrayList<AddUsers> users = new ArrayList<>();

    private JLabel addNewUserLabel;
    private JTextField addNewUserTextField;
    private JLabel deleteUsersLabel;
    private JCheckBox jcomp4;
    private JCheckBox jcomp5;
    private JCheckBox jcomp6;
    private JButton addButton;
    private JButton deleteButton;

    public ManageUsersGUI1() {         
        //construct components
        addNewUserLabel = new JLabel ("Add new User here:");
        addNewUserTextField = new JTextField (0);
        deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
        jcomp4 = new JCheckBox ("newCheckBox");
        jcomp5 = new JCheckBox ("newCheckBox");
        jcomp6 = new JCheckBox ("newCheckBox");
        addButton = new JButton ("Add");
        deleteButton = new JButton ("Delete");

        //set components properties
        addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
        addButton.setToolTipText ("Click here to Add new user.");
        deleteButton.setToolTipText ("Click here to delete User(s) selected.");

        //adjust size and set layout
        setPreferredSize (new Dimension (580, 485));
        setLayout (null);

        //add components
        add (addNewUserLabel);
        add (addNewUserTextField);
        add (deleteUsersLabel);
        add (jcomp4);
        add (jcomp5);
        add (jcomp6);
        add (addButton);
        add (deleteButton);

        //set component bounds (only needed by Absolute Positioning)
        addNewUserLabel.setBounds (85, 130, 120, 25);
        addNewUserTextField.setBounds (235, 130, 125, 25);
        deleteUsersLabel.setBounds (135, 225, 281, 25);
        jcomp4.setBounds (225, 270, 140, 25);
        jcomp5.setBounds (225, 300, 140, 25);
        jcomp6.setBounds (225, 330, 140, 25);
        addButton.setBounds (385, 130, 100, 25);
        deleteButton.setBounds (230, 410, 100, 25);

        addButton.addActionListener(new AddButtonListener());

    }

    private class AddButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           String text = addNewUserTextField.getText();
           users.add(new AddUsers(text));

           // Display the charges.
           JOptionPane.showMessageDialog(null, text + " has been added.");
        }
   }


    public static void main (String[] args) {
        JFrame frame = new JFrame ("AddUsersPanel1");
        frame.setTitle("Manage Users");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new ManageUsersGUI1());
        frame.pack();
        frame.setVisible (true);
    }
}

Answer:

You could use a JPanel with BoxLayout as the layout manager.

That way, for each new name entered in the JTextField, you can add a new JCheckBox to the JPanel and it automatically lists lays them out in order vertically.

I've made some modifications to your code to exemplify, so you can adjust to your needs:

public class ManageUsersGUI1 extends JPanel {
    public static ArrayList<AddUsers> users = new ArrayList<>();

    private JLabel addNewUserLabel;
    private JTextField addNewUserTextField;
    private JLabel deleteUsersLabel;
    private JButton addButton;
    private JButton deleteButton;
    private JPanel namePanel;

    public ManageUsersGUI1() {
        //construct components
        addNewUserLabel = new JLabel ("Add new User here:");
        addNewUserTextField = new JTextField (0);
        deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
        addButton = new JButton ("Add");
        deleteButton = new JButton ("Delete");
        namePanel = new JPanel();
        namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));

        //set components properties
        addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
        addButton.setToolTipText ("Click here to Add new user.");
        deleteButton.setToolTipText ("Click here to delete User(s) selected.");

        //adjust size and set layout
        setPreferredSize (new Dimension (580, 485));
        setLayout (null);

        //add components
        add (addNewUserLabel);
        add (addNewUserTextField);
        add (deleteUsersLabel);
        add (namePanel);
        add (addButton);
        add (deleteButton);

        //set component bounds (only needed by Absolute Positioning)
        addNewUserLabel.setBounds (85, 130, 120, 25);
        addNewUserTextField.setBounds (235, 130, 125, 25);
        deleteUsersLabel.setBounds (135, 225, 281, 25);
        addButton.setBounds (385, 130, 100, 25);
        namePanel.setBounds(225, 270, 140, 0);
        deleteButton.setBounds (230, 335, 100, 25);

        addButton.addActionListener(new AddButtonListener());

    }

    private class AddButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String text = addNewUserTextField.getText();
            users.add(new AddUsers(text));

            // Display the charges.
            JOptionPane.showMessageDialog(null, text + " has been added.");

            JCheckBox nameCheckBox = new JCheckBox();
            nameCheckBox.setText(addNewUserTextField.getText());
            namePanel.add(nameCheckBox);
            namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
            deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
            JFrame frame = (JFrame) getRootPane().getParent();
            frame.setSize(frame.getWidth(), frame.getHeight() + 25);
            frame.pack();
        }
    }


    public static void main (String[] args) {
        JFrame frame = new JFrame ("AddUsersPanel1");
        frame.setTitle("Manage Users");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new ManageUsersGUI1());
        frame.pack();
        frame.setVisible (true);
    }
}

Question:

I'm trying to create an application that allows a user to choose insurance options in JCheckBoxes. For each option that is selected, the name and price are supposed to appear in a text field. My problem is that even when I select it, it doesn't display the Name & Price. At the moment I'm just trying to make the HMO checkbox work.

package p3s4;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JInsurance extends JFrame implements ItemListener
{       
        FlowLayout flow = new FlowLayout();
        final double HMO_PRICE = 200;
        final double PPO_PRICE = 600;
        final double DENTAL_PRICE = 75;
        final double VISION_PRICE = 20;
        JLabel heading = new JLabel("Choose insurance options: ");
        JCheckBox hmo = new JCheckBox("HMO");
        JCheckBox ppo = new JCheckBox("PPO");
        ButtonGroup providersGroup = new ButtonGroup();
        JCheckBox dental = new JCheckBox("Dental");
        JCheckBox vision = new JCheckBox("Vision");
        JTextField hmoSelection = new JTextField(hmo + " " + HMO_PRICE);
public JInsurance()
{
    super("Insurance Options");

    setLayout(flow);
    add(heading);
    providersGroup.add(hmo);
    providersGroup.add(ppo);
    add(hmo);
    add(ppo);
    add(dental);
    add(hmoSelection);
    hmoSelection.setVisible(false);
    add(vision);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    hmo.addItemListener(this);
}
public void itemStateChanged(ItemEvent event)
{
    if(event.getStateChange() == ItemEvent.SELECTED)
    {
            hmoSelection.setVisible(true);
    }    
    else
        hmoSelection.setVisible(false);
}
public static void main(String[] args) 
{
    JInsurance first = new JInsurance();
    final int WIDTH = 400;
    final int HEIGHT = 300;
    first.setSize(WIDTH, HEIGHT);
    first.setVisible(true);
}
}

Answer:

Add the following code in your if block and it will work as expected

hmoSelection.getParent().revalidate();

The API docs for revalidate:

Revalidates the component hierarchy up to the nearest validate root.

This method first invalidates the component hierarchy starting from this component up to the nearest validate root. Afterwards, the component hierarchy is validated starting from the nearest validate root.

This is a convenience method supposed to help application developers avoid looking for validate roots manually. Basically, it's equivalent to first calling the invalidate() method on this component, and then calling the validate() method on the nearest validate root.

Question:

I'm currently doing a form which involves text fields and checkboxes. I already linked the check box to the text field, which if the check box is SELECTED, the text field is enabled; while check box is DESELECTED, text field is disabled.

My problem now is if users selects the check box and type some value into the text field and then deselect the check box again, my program would still read the input from the disabled text field. Is there any way to overcome this issue? Below is my coding:

 private void pnl1submitbtnActionPerformed(java.awt.event.ActionEvent evt) {                                              
    moduleFunc moduleFunc;
    String module = moduletxtfield.getText();
    double exam = Double.parseDouble(examtextfield.getText());
    double ct = Double.parseDouble(cttextfield.getText());
    double quiz = Double.parseDouble(quiztextfield.getText());
    double assign = Double.parseDouble(asstextfield.getText());
    try {
        if (module.trim().isEmpty()) {
            moduleerrorlbl.setText("Field cannot be empty");
        }
        else if (!(exam+ct+quiz+assign == 100)) {
            markerrorlbl.setText("Total marks must be 100");
        }
        else
        {
            markerrorlbl.setText("");
            moduleerrorlbl.setText("");
        }

Thanks.

EDITED:

Thanks guys, I've figured out how it works.

 private void pnl1submitbtnActionPerformed(java.awt.event.ActionEvent evt) {                                              
    moduleFunc moduleFunc;
    String module = moduletxtfield.getText();
    double exam = 0.0, assign = 0.0, quiz = 0.0, ct = 0.0;
   try {
        if (module.trim().isEmpty()) {
            moduleerrorlbl.setText("Field cannot be empty");
        }
        else if (OODJ.moduleRecord.containsKey(module)) {
            moduleerrorlbl.setText("Module already exists!");
        }
        else {
            if (examchkbox.isSelected()) {
            exam = Double.parseDouble(examtextfield.getText());
            }
            if(ctchkbox.isSelected()) {
            ct = Double.parseDouble(cttextfield.getText());    
            }
            if(quizchkbox.isSelected()) {
            quiz = Double.parseDouble(quiztextfield.getText());    
            }
            if(asschkbox.isSelected()) {
            assign = Double.parseDouble(asstextfield.getText());    
            }
            if (!(exam + ct + quiz + assign == 100)) {
            markerrorlbl.setText("Total marks must be 100");
            }
            else {
            // self-coded
            }
            }
        }
    catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
    }

Answer:

You have to check whenever the JCheckBox linked to your JTextField is selected. For this you have to use the isSelected() method of the JCheckBox.

Example:

if(checkBox.isSelected())
{
    if (module.trim().isEmpty())
    {
        moduleerrorlbl.setText("Field cannot be empty");
    }
    else if (!(exam+ct+quiz+assign == 100))
    {
        markerrorlbl.setText("Total marks must be 100");
    }
    else
    {
        markerrorlbl.setText("");
        moduleerrorlbl.setText("");
    }
}
else
{
    System.out.println("The textfield is disabled!");
}

Question:

I have been wondering about saving and loading jcheckbox and jtextfields values in Java. Is it possible to save and load jcheckbox and jtextfields values? I have attached the picture of a small program in which I would like to save the values of checkbox and load them to review later. Do I use JFileChooser to do the operation?

   public class Try extends JFrame {
   private JPanel contentPane;
   private JCheckBox chckbx_1;
private JCheckBox chckbx_2;
private JTextField textField;
private JTextField textField_1;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Try frame = new Try();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Try() {
    setTitle("Price tag");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    chckbx_1 = new JCheckBox("Price");
    chckbx_1.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED){
                textField.setEnabled(true);
                textField.setText("");
            }
            else if(e.getStateChange() == ItemEvent.DESELECTED){
                textField.setEnabled(false);
                textField.setText("");
        }
        }
    });

    chckbx_1.setBounds(72, 7, 81, 41);
    contentPane.add(chckbx_1);

    chckbx_2 = new JCheckBox("New Price");
    chckbx_2.addItemListener(new ItemListener() {
         @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED){
                textField.setEnabled(true);
                textField.setText("");
            }
            else if(e.getStateChange() == ItemEvent.DESELECTED){
                textField_1.setEnabled(false);
                textField_1.setText("");
        }
        }
    });
    chckbx_2.setBounds(72, 51, 89, 50);
    contentPane.add(chckbx_2);

    textField = new JTextField();
    textField.setBounds(196, 17, 86, 20);
    contentPane.add(textField);
    textField.setColumns(10);

    textField_1 = new JTextField();
    textField_1.setBounds(196, 66, 86, 20);
    contentPane.add(textField_1);
    textField_1.setColumns(10);

    JButton btn1 = new JButton("Save");
    btn1.setBounds(193, 173, 89, 23);
    contentPane.add(btn1);

    JButton btn2 = new JButton("Load");
    btn2.setBounds(314, 173, 89, 23);
    contentPane.add(btn2);
}}


Answer:

The variables that you should use are :

 private FileWriter fw;
 private PrintWriter pw;
 private BufferedReader br;

For Saving the checkbox status and textfield value you can use FileWriter and PrintWriter to save in file:

btn1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String desktopPath = System.getProperty("user.home") + "/Desktop/";
                try {
                    fw = new FileWriter(desktopPath + "yourfile.txt");
                } catch (IOException ex) {
                    System.out.println("Error : " + ex);
                }
                pw = new PrintWriter(fw);
                pw.println(chckbx_1.isSelected() + "-" + textField.getText() + "-" + chckbx_2.isSelected()
                        + " -" + textField_1.getText());
                if (pw != null) {
                    pw.close();
                }
            }
        });

And for reading from the file you can use BufferedReader and use StringTokenizer for splitting the read line from the file :

btn2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String desktopPath = System.getProperty("user.home") + "/Desktop/";
                try {
                    String sCurrentLine;
                    br = new BufferedReader(new FileReader(desktopPath + "yourfile.txt"));
                    while ((sCurrentLine = br.readLine()) != null) {
                        StringTokenizer tokenizer = new StringTokenizer(sCurrentLine, "-");
                        if (tokenizer.hasMoreElements()) {
                             Boolean boolean1 = Boolean.valueOf(tokenizer.nextToken());
                             chckbx_1.setSelected(boolean1);
                        }
                        if (tokenizer.hasMoreElements()) {
                            textField.setText(tokenizer.nextToken());
                        }
                        if (tokenizer.hasMoreElements()) {
                             Boolean boolean1 = Boolean.valueOf(tokenizer.nextToken());
                             chckbx_2.setSelected(boolean1);
                        }
                        if (tokenizer.hasMoreElements()) {
                            textField_1.setText(tokenizer.nextToken());
                        }

                    }
                } catch (FileNotFoundException ex) {
                    System.out.println("Error : " + ex);
                } catch (IOException ex) {
                    System.out.println("Error : " + ex);
                }
            }
        });

And if you want to read from multi-file u can use JFileChooser like :

    btn2.addActionListener(new ActionListener() {
                @Override
                    public void actionPerformed(ActionEvent e) {
                        JFileChooser fc = new JFileChooser();
                        int ret = fc.showOpenDialog(null);
                        if (ret == JFileChooser.APPROVE_OPTION) {
                            File file = fc.getSelectedFile();
                             filename = file.getAbsolutePath();
                        }
....

and then, put the code for read:

br = new BufferedReader(new FileReader(filename));

Question:

I have a JTable 2 columns, column name and check-box. If the user clicks the check box next to the name of the column that creates a new field for data entry. I wish the unclick check box input field has disappeared.

How can I do that?

My code to add a new field:

 headerTable.getModel().addTableModelListener(new TableModelListener() {

                @Override
                public void tableChanged(TableModelEvent e) {
                    if(e.getColumn() >= 0  && e.getFirstRow()>-1){
                        int id =  e.getFirstRow();
                        String colName = (String)headerTable.getValueAt(e.getFirstRow(), 1);
                        boolean colValue = (boolean)headerTable.getValueAt(e.getFirstRow(), 2);

                        System.out.println("Row : " + e.getFirstRow() +
                                   " value :" + headerTable.getValueAt(e.getFirstRow(), 2));
                        appListener.getColumnId(id);
                        //create texfield
                        if(colValue==false){
                            System.out.println("Delete");
                        }                         
                        jTextField = new JTextField(20);
                        textField.put(id,jTextField);
                        if (textField != null && !textField.isEmpty()) {
                            textField.get(textField.size()-1);
                            System.out.println("Add");
                        }
                        JLabel kolor1name = new JLabel(colName+": ");
                        operationContent.add(kolor1name,"");
                        operationContent.add(jTextField, "growy, wrap");

                        revalidate();
                        repaint();
                    }
                }
            });

Answer:

You can create a Vector of all the fields that you want. And when the user clicks on the check-box, you can add it to the Vector. for eg:

Vector fields = new Vector();

And when you get the notification, you add the name of the field in the vector, and call the refreshPanel() method, which removes all the fields in it, and add the new fields to it.

// In the tableChanged(...) method
fields.addElement(colname);
refreshPanel();

Then the refreshPanel() method:

public void refreshPanel()
{
     String fNames[] = (String[]) fields.toArray();
     panel.removeAll();
     for(String fname : fNames)
     {
          //add the fields in `newPanel`, the field name is in `fname` variable
     }
     revalidate();
     repaint();
}

And when the user deselects the check-box, then remove the field name from the Vector:

fields.removeElement(colname);
refreshPanel();

Question:

i want my app to create jcheckboxes from an input that always changes. I want to create a jtextfield near every checkbox, that will be set enabled, only when his checkbox is pressed.

I managed to create this code:

 //Create checkboxes with textfileds
    for (int i = 0; i < activeProjects.length; i++) {
        projectPanels[i] = new JCheckBox(activeProjects[i]);
        projectPanels[i].setSelected(false);
        projectPanels[i].setComponentOrientation   (ComponentOrientation.RIGHT_TO_LEFT);
        projectPanels[i].setAlignmentX(RIGHT_ALIGNMENT);
        projectPanels[i].addItemListener(this);

        projectStorageNum[i] = new JTextField("");
//          projectStorageNum[i].setEnabled(false);
        projectStorageNum[i].setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        projectStorageNum[i].setMaximumSize(new Dimension(200,30));
        projectStorageNum[i].setMinimumSize(new Dimension(200,30));
        projectStorageNum[i].setPreferredSize(new Dimension(200,30));
        projectStorageNum[i].setAlignmentX(RIGHT_ALIGNMENT);

        tmppnl = new JPanel();
        tmppnl.add(projectStorageNum[i]);
        tmppnl.add(projectPanels[i]);

        checkBoxPanel.add(tmppnl);

    }

and this is my state change listener:

public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
JCheckBox myBox= (JCheckBox)source;
String bName = myBox.getText();

if (e.getStateChange() == ItemEvent.SELECTED)
{
// enable matching text field.
// add bName to projects list.
}
    else
    {
     //disable matching textfield
     // remove bName from list
    }

when I access the checkboxes in a dynamic way I don't have access to the second array of textfields. is there any way to link them , or any other idea ?

thanks

Dave.


Answer:

One thing you could do is use the setName and getName methods of Component to save the index of the JCheckBox.

projectPanels[i].setName(Integer.toString(i));

Then, in your state change listener.

int i = Integer.valueOf(e.getName());

This gives you the index of the JTextField.