Results 1 to 11 of 11
  1. #1
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default Jcheckbox problem

    I am trying to create an interface where I can enter a book's title, author, and if it is availabe. Ultimately, I will be writing this to a text file but before I get to that step I thought I'd check to make sure that I am capturing what I need by printing it to screen. I am able to get the title and author from the text boxes but I can't seem to get the checkbox to work properly. All I want to do is to see if the checkbox is selected. If it is, then I will have it say "available". Otheriwse, I will have it say "not available".

    Below is my code:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class Homework2a_GK extends JFrame {
    
            private JPanel panel;
            private JButton button;
            private JCheckBox check;
            private JTextField bookTitle;
            private JTextField authorField;
            private JLabel bookLabel;
            private JLabel authorLabel;
    
    
            public Homework2a_GK(String str) {
                    super(str);
    
            }
            public static void main(String[] args) {
    
                    Homework2a_GK myGUI = new Homework2a_GK("Save book records");
                            myGUI.createAndShowGUI();
                    }
            private void createAndShowGUI() {
    
                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    Container contentPane = getContentPane();
                    contentPane.setLayout(new BorderLayout());
                    contentPane.setLayout(null);
    
    
                    JButton button = new JButton("Save");
                    button.setBounds(230,125, 75,20);
                    this.add(button);
                    button.addActionListener(new BookEntry());
    
                    JCheckBox check = new JCheckBox("Available",false);
                    check.setBounds(230,100,100,20);
                    this.add(check);
                   
                    bookLabel = new JLabel("Book title:");
                    bookLabel.setBounds(10,10,100,20);
                    this.add(bookLabel);
                    bookTitle = new JTextField();
                    bookTitle.setBounds(120,10,350,20);
                    this.add(bookTitle);
                    bookTitle.setActionCommand("ChangeText");
                    bookTitle.addActionListener(new BookEntry());
    
    
                    authorLabel = new JLabel("Author:");
                    authorLabel.setBounds(10,50,100,20);
                    this.add(authorLabel);
                    authorField = new JTextField();
                    authorField.setBounds(120,50,350,20);
                    this.add(authorField);
                    authorField.setActionCommand("ChangeText");
                    authorField.addActionListener(new BookEntry());
    
                    setSize(500, 200);
    
    
                    setVisible(true);
    
            }
            public class BookEntry implements ActionListener {
                public void actionPerformed(ActionEvent ev) {
    
                        System.out.println(bookTitle.getText());
                        System.out.println(authorField.getText());
    
                        boolean selected = check.isSelected();
                        if (selected) {
                                System.out.println("is available");
                        } else {
                                System.out.println("is not available");
    
                        }
                }
    
        }
    }
    Last edited by Fubarable; 04-09-2011 at 05:00 PM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Moderator Edit: Code tags added to the post above.

    To the OP, in the future, to do this yourself, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag
    Java Code:
     above your pasted code and the tag
    below your pasted code like so:

    Java Code:
    [code]
      // your code goes here
      // notice how the top and bottom tags are different
    [/code]
    Best of luck

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    If your code generates an exception, you really should post the complete text of the exception rather than make us guess, since you want to make it as easy as possible for the volunteers here to help you. Also please indicate which line is causing the error.

    Edit: I see you're getting a NullPointerException on this line:

    Java Code:
    boolean selected = check.isSelected();
    meaning check is null. So you will need to look into your code to see why it is null, and the answer will fall out. Please see comments in your code for the problem:

    Java Code:
    public class Homework2a_GK extends JFrame {
       private JPanel panel;
       private JButton button;
       private JCheckBox check;  // this field is declared but never initialized
       //....
    
       public Homework2a_GK(String str) {
          super(str);
       }
    
       public static void main(String[] args) {
          Homework2a_GK myGUI = new Homework2a_GK("Save book records");
          myGUI.createAndShowGUI();
       }
    
       private void createAndShowGUI() {
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          
          // .... etc ....
          
          // the variable "check" below is a local variable as it is being declared inside of a method
          // and thus is only visible inside of this method.  
          // initializing it has no effect on the class field of the same name
    
          JCheckBox check = new JCheckBox("Available", false);
    Last edited by Fubarable; 04-09-2011 at 05:11 PM.

  4. #4
    baf06 is offline Member
    Join Date
    Jan 2011
    Location
    Beirut, Lebanon
    Posts
    90
    Rep Power
    0

    Default

    It seems that two JLabel and one JButton are calling the same actionListener, and your checkBox is not
    JCheckBox check = new JCheckBox("Available",false);
    check.setBounds(230,100,100,20);
    this.add(check);
    this is one problem and another, this actionListener will perform all the statements whenever any one of the labels or the button is pressed, so to fix this I think you have to state if statement in side the actionPerformed comparing what is the source to execute the proper action for its caller

  5. #5
    baf06 is offline Member
    Join Date
    Jan 2011
    Location
    Beirut, Lebanon
    Posts
    90
    Rep Power
    0

    Default

    Fubarable i need a small explanation for something please : i have been reading this code and one problem came to my mind. is it right to add an actionListener to a JTextFeild that prints what you entered in that field ?

    authorField = new JTextField();
    authorField.addActionListener(new BookEntry());
    what does he exactly means to do in the actionListener ?
    public class BookEntry implements ActionListener {
    public void actionPerformed(ActionEvent ev) {

    System.out.println(bookTitle.getText());
    System.out.println(authorField.getText());

    boolean selected = check.isSelected();
    if (selected) {
    System.out.println("is available");
    } else {
    System.out.println("is not available");

    }
    }

    }
    Is it me that can't understand it or is it wrong ?
    Last edited by baf06; 04-09-2011 at 05:29 PM.

  6. #6
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    I redid my code and it looks like this:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class Homework2a_GK extends JFrame {
    
    	JPanel panel;
    	JButton button;
    	JCheckBox check;
    	JTextField bookTitle;
    	JTextField authorField;
    	JLabel bookLabel;
    	JLabel authorLabel;
    	int avail;
    
    	public Homework2a_GK(String str) {
    		super(str);
    
    	}
    
    	public static void main(String[] args) {
    
    		Homework2a_GK myGUI = new Homework2a_GK("Save book records");
    		myGUI.createAndShowGUI();
    	}
    
    	public void createAndShowGUI() {
    
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		Container contentPane = getContentPane();
    		contentPane.setLayout(new BorderLayout());
    		contentPane.setLayout(null);
    
    		JButton button = new JButton("Save");
    		button.setBounds(230, 125, 75, 20);
    		this.add(button);
    		button.addActionListener(new BookEntry());
    
    		JCheckBox check = new JCheckBox("Available");
    		check.setBounds(230, 100, 100, 20);
    		this.add(check);
    
    		avail = 0;
    		if (check.isSelected()) {
    			avail = 1;
    		}
    
    		bookLabel = new JLabel("Book title:");
    		bookLabel.setBounds(10, 10, 100, 20);
    		this.add(bookLabel);
    		bookTitle = new JTextField();
    		bookTitle.setBounds(120, 10, 350, 20);
    		this.add(bookTitle);
    
    		authorLabel = new JLabel("Author:");
    		authorLabel.setBounds(10, 50, 100, 20);
    		this.add(authorLabel);
    		authorField = new JTextField();
    		authorField.setBounds(120, 50, 350, 20);
    		this.add(authorField);
    
    		setSize(500, 200);
    
    		setVisible(true);
    
    	}
    
    	public class BookEntry implements ActionListener {
    		public void actionPerformed(ActionEvent ev) {
    
    			System.out.println(bookTitle.getText());
    			System.out.println(authorField.getText());
    			if (avail == 1) {
    				System.out.println(avail);
    			} else {
    				if (avail == 0) {
    					System.out.println(avail);
    				}
    			}
    
    		}
    
    	}
    }
    I want an action to be done only when I press a button, so I remove the action listener from the text fields. However, it seems the code insists on making the checkbox not checked (my test here is to use variable avail.. when selected, avail = 1, otherwise avail =0. my test print out always says '0' regardless if the box is checked)

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by baf06 View Post
    Fubarable i need a small explanation for something please : i have been reading this code and one problem came to my mind. is it right to add an actionListener to a JTextFeild that prints what you entered in that field ?



    what does he exactly means to do in the actionListener ?


    Is it me that can't understand it or is it wrong ?
    I think the problem with this approach is that there is a higher chance of the listener being triggered before data entry has been complete since the listener are triggered by either button press or by pressing enter in either JTextField. Myself in this situation, I'd put the ActionListener only on the JButton with the thought being that I'd likely press the button only after all fields have been filled. Also, if necessary, I'd put in code in the listener to check that necessary text fields are not empty.

  8. #8
    baf06 is offline Member
    Join Date
    Jan 2011
    Location
    Beirut, Lebanon
    Posts
    90
    Rep Power
    0

    Default

    okay then, this is more sensible, but you didn't pay attention to this post :
    // the variable "check" below is a local variable as it is being declared inside of a method
    // and thus is only visible inside of this method.
    // initializing it has no effect on the class field of the same name
    since you still initialized both the "button" and "check" outside and then declared them again inside your method

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Swing is event driven, and your avail variable is only set once here:

    Java Code:
    		avail = 0;
    		if (check.isSelected()) {
    			avail = 1;
    		}
    but is never changed anywhere else in your code. So it makes sense that it never changes. I suggest that you get rid of the avail variable as it adds nothing but confusion to the code. Instead use only one JCheckBox variable, check, do not redeclare it in the method, but use it in the method:

    not this:
    Java Code:
          //!! JCheckBox check = new JCheckBox("Available", false);

    but this:

    Java Code:
          check = new JCheckBox("Available", false);

  10. #10
    baf06 is offline Member
    Join Date
    Jan 2011
    Location
    Beirut, Lebanon
    Posts
    90
    Rep Power
    0

    Default

    okay :) thanks a lot for this clarification because at first I thought that I miss understood what is going on, but now I am sure of what I know about this aspect. thanks :)

  11. #11
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    Thank you everyone! I implemented your suggestions and it now works. Now onto the text step (capturing the information and saving to a text file).

Similar Threads

  1. JCheckbox in jtable
    By anilkumar_vist in forum Advanced Java
    Replies: 3
    Last Post: 09-07-2010, 06:29 AM
  2. How to add a jcheckbox in jtable
    By lakshayghai in forum AWT / Swing
    Replies: 9
    Last Post: 04-15-2010, 12:32 AM
  3. How can I add JCheckBox to each row?
    By batya in forum AWT / Swing
    Replies: 1
    Last Post: 11-04-2009, 10:25 PM
  4. JCheckbox in Jtree
    By shajuantony in forum AWT / Swing
    Replies: 10
    Last Post: 09-09-2009, 11:42 AM
  5. jcheckbox issues need help. thanks.
    By carlos123 in forum New To Java
    Replies: 3
    Last Post: 11-05-2007, 11:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •