8 Replies - 2908 Views - Last Post: 23 May 2010 - 08:34 AM Rate Topic: -----

#1 mufasa  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 44
  • Joined: 12-February 10

Getting infro from JTextField

Posted 23 May 2010 - 07:40 AM

Hey, so I'm having a bit of trouble getting data from a JTextField. This is basically a little GUI to get some player's info before the game starts. I haven't started on the "prettying up" phase yet because I'm having an issue getting the player's name from the text field. I've tried implementing a key listener for the enter key in the text field, but I feel as though I'm doing it wrong. This is my first time really having a go at all this in java, so any and all help is greatly appreciated.
Thanks!

//Import Declaration
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;


/***
 * Human class
 */
public class Human extends JFrame{

	public static void main(String[] args){
		Human human = new Human(1);
	}
	
	
	private static final long serialVersionUID = 1L;
	private String color;
	private int position;
	private String name;
	private boolean human;
	
	private boolean nameIsSet;
	private boolean colorIsSet;
	
	
	
	//Constructors
	public Human(int pos){
		name = "";
		color = "";
		//GUI stuff
		//Initialize all components
		Container pane = getContentPane();
	    nextButton = new JButton("Next");
	    colorChoiceBox = new JComboBox();
	    constructorTitle = new JLabel("Enter Player Info", SwingConstants.CENTER);
	    playerNameTitle = new JLabel("Player Name:", SwingConstants.RIGHT);
	    playerColorTitle = new JLabel("Player Color:", SwingConstants.RIGHT);
	    playerName = new JTextField(10);
	    forDebugging1 = new JLabel();
	    forDebugging2 = new JLabel();
	    
	    if(pos == 1){
	    	colorChoiceBox.setModel(new DefaultComboBoxModel(new String[]{"None", "Blue", "Green"}));
	    }else
	    	colorChoiceBox.setModel(new DefaultComboBoxModel(new String[]{"None", "Yellow", "Purple"}));
	    
	    //Create ActionListeners
	    nextButtonHandler = new NextButtonHandler();
	    colorChoiceHandler = new ColorChoiceHandler();
	    
	    //Add ActionListeners to JFrame fields
	    nextButton.addActionListener(nextButtonHandler);
	    playerName.addActionListener(textFieldHandler);
	    colorChoiceBox.addActionListener(colorChoiceHandler);
	    this.addWindowFocusListener(new WindowAdapter() {
	    	public void windowGainedFocus(WindowEvent e) {
	    		playerName.requestFocusInWindow();
	    	}
	    });
	    
	    //Add components to a JFrame
	    pane.setLayout(new GridLayout(4, 2));
		pane.add(constructorTitle);
		pane.add(forDebugging1);
		pane.add(playerNameTitle);
		pane.add(playerName);
		pane.add(playerColorTitle);
		pane.add(colorChoiceBox);
		pane.add(forDebugging2);
	    pane.add(nextButton);
		
		setSize(/*WIDTH*/ 400, /*HEIGHT*/ 300);
		setVisible(true);
		
		System.out.printf("This player's name is: %s, and their color is %s.", name, color);
	}//End of overridden default constructor
	
	
	//Accessors and Mutators
	/***
	 * Gives a player the color for his/her pieces
	 * @param s The given color
	 */
	public void setColor(String s){
		color = s;
	}//End of setColor()
	
	public void setHumanName(String s){
		name = s;
	}
	
	/***
	 * Gets the color of the player's pieces
	 * @return The color of the player's pieces
	 */
	public String getColor(){
		return color;
	}//End of getColor()
	
	/***
	 * Sets the player as a human player
	 * @param b Sets the player's "human" status
	 */
	public void setHuman(boolean B)/>{
		human = b;
	}//End of setHuman()
	
	/***
	 * Tells whether the player is human or not
	 * @return true if the player is human, false otherwise
	 */
	public boolean isHuman(){
		return human;
	}//End of isHuman()
	
	/***
	 * Detects whether the player's data has been set for a human player
	 * @return true if correctly set human player, false otherwise
	 */
	public boolean playerValidity(){
		return ((color != "") && (human));
	}//End of playerValidity()
	
	/***
	 * Prints out a player with all of their info
	 * @
	 */
	public void display(){
		System.out.printf("\nPlayer %d:\t\t%s\t\tPlayer Color: %s", position + 1, name, color);
	}//End of display()
	
	/***
	 * Takes the players input and places their piece
	 * @param b The game's board
	 */
	public void turn(Board B)/>{
		int r, col;
		b.display();
		System.out.printf("\nWhere would you like to place your piece (Which column)?\nColumn: ");
		Scanner scanner = new Scanner(System.in);
		col = scanner.nextInt();
		col = col - 1;
		//System.out.printf("Column: ");
		//col = scanner.nextInt();
		//col = col - 1;
		Piece piece = new Piece(color);
		Slot slot = new Slot();
		slot.setPiece(piece);
		//b.getBoard()[r][col] = slot;
		r = b.getHeight();
		Slot temp;
		for(int y=r-1; y>=0; y--){
			temp = b.getBoard()[y][col];
			if(temp.getPiece() == null){
				b.getBoard()[y][col] = slot;
				y = 0;
			}
		}
	}//End of turn()
	
	/***
	 * Returns the player's name
	 * @return The player's name
	 */
	public String getName(){ return name;}//End of getName()
	
	
	
	// Variables declaration - do not modify
    	//Fields in Frame
	private JButton nextButton;
    private JComboBox colorChoiceBox;
    private JLabel constructorTitle;
    private JLabel playerNameTitle;
    private JLabel playerColorTitle;
    private JLabel forDebugging1;
    private JLabel forDebugging2;
    private JTextField playerName;
    	//ActionListeners
    private NextButtonHandler nextButtonHandler;
    private TextFieldHandler textFieldHandler;
    private ColorChoiceHandler colorChoiceHandler;
    // End of variables declaration
    
    private class NextButtonHandler implements ActionListener{
    	
    	public void actionPerformed(ActionEvent e){
    		if(validate()){
    			System.out.printf("The player's name is: %s, and their color is: %s", name, color);
    			//TODO find a way to close the window without closing the program
    		}
    	}
    	
    	public boolean validate(){
    		if(getName() == ""){
    			return false;
    		}else if(color == "" || color == "None"){
    			return false;
    		}
    		return true;
    	}
    }
	
	private class TextFieldHandler implements ActionListener, KeyListener{
		
		public TextFieldHandler(){
			setFocusable(true);
		}
		
		public void actionPerformed(ActionEvent e){
			
			JTextField source = (JTextField)e.getSource();
			String tempName = (String)source.getText();
			setName(tempName);
			setName(playerName.getText());
			System.out.printf("\nThe player's name is: %s", name);
		}
		
		public void keyTyped(KeyEvent e){
			//TODO
		}
		
		public void keyPressed(KeyEvent e){
			//TODO
			int key = e.getKeyCode();
			if(key == KeyEvent.VK_ENTER){
				Toolkit.getDefaultToolkit().beep();
				JTextField source = (JTextField)e.getSource();
				String tempName = (String)source.getText();
				setName(tempName);
				System.out.printf("\nThe player's name is: %s", name);
			}
		}
		
		public void keyReleased(KeyEvent e){
			//TODO
		}

		
	}
	
	private class ColorChoiceHandler implements ActionListener{
		
		public void actionPerformed(ActionEvent e){
			JComboBox source = (JComboBox)e.getSource();
			String tempColor = (String)source.getSelectedItem();
			setColor(tempColor);
			System.out.printf("\nThe player's color is: %s", color);			
		}
	}
	

	
	
	
	
}//End of Human class





Is This A Good Question/Topic? 0
  • +

Replies To: Getting infro from JTextField

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10549
  • View blog
  • Posts: 39,044
  • Joined: 27-December 08

Re: Getting infro from JTextField

Posted 23 May 2010 - 07:58 AM

You can use the JTextField getText() method, which returns a String with the text entered. Rather than using a listener for the JTextField, I would use a JButton to tell the program when to get the data. Then tie a Listener to the JButton, and in the actionPerformed() method, get the text. KeyListeners are rather inaccurate b/c the JTextField may or may not be selected.
Was This Post Helpful? 1
  • +
  • -

#3 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 496
  • View blog
  • Posts: 1,453
  • Joined: 19-October 09

Re: Getting infro from JTextField

Posted 23 May 2010 - 08:11 AM

In addition to macosxnerd101's advice, I've noticed a few things in your code.

I can also see that you are using the == operator to check whether the String is empty.

Instead of this,

 if(getName() == ""){

You can do this
if(getName().isEmpty()){


When using the == operator, it simply compares references, not values.

Whereas using .equals() compares values for equality.

So you should really pay attention to this method below which i spotted

 public boolean validate(){
                if(getName() == ""){
                        return false;
                }else if(color == "" || color == "None"){
                        return false;
                }
                return true;
        }
    }



:)
Was This Post Helpful? 2
  • +
  • -

#4 mufasa  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 44
  • Joined: 12-February 10

Re: Getting infro from JTextField

Posted 23 May 2010 - 08:17 AM

Thanks for both posts! Ya, I was pretty lazy by just doing the == operator, thanks for that catch. And thanks for the advice to set the player's name at the button click, I was trying it before but I realized what I was doing was actually overriding the setName() method for the container class, so I renamed that and it works great now, thank you both!

If I have another question pertaining to this same file can I ask it here or should I begin a new thread?
Was This Post Helpful? 0
  • +
  • -

#5 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10549
  • View blog
  • Posts: 39,044
  • Joined: 27-December 08

Re: Getting infro from JTextField

Posted 23 May 2010 - 08:20 AM

Go ahead and ask here. :)
Was This Post Helpful? 0
  • +
  • -

#6 mufasa  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 44
  • Joined: 12-February 10

Re: Getting infro from JTextField

Posted 23 May 2010 - 08:26 AM

How would you close the screen upon hitting a button, but not close the program (excluding hitting the X button)? I mean is there like a System.exit(int) way of doing it?
Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10549
  • View blog
  • Posts: 39,044
  • Joined: 27-December 08

Re: Getting infro from JTextField

Posted 23 May 2010 - 08:28 AM

If you want to hide the JFrame without exiting the Program, you can use the JFrame setVisible(boolean) method.
Was This Post Helpful? 1
  • +
  • -

#8 mufasa  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 44
  • Joined: 12-February 10

Re: Getting infro from JTextField

Posted 23 May 2010 - 08:32 AM

Ahh, good idea. Thanks!
Was This Post Helpful? 0
  • +
  • -

#9 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 496
  • View blog
  • Posts: 1,453
  • Joined: 19-October 09

Re: Getting infro from JTextField

Posted 23 May 2010 - 08:34 AM

Create a JButton and add an ActionListener to it then call this.

this.setVisible(false);

This post has been edited by m-e-g-a-z: 23 May 2010 - 08:35 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1