Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Keystoke Problem :-(

  1. #1
    Junior Member
    Join Date
    Apr 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Keystoke Problem :-(

    Everything works, except when I use the buttons, I lose all keystroke functionality. Any ideas, i'm lost in space on fixing this.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
     
    public class TogizKumalakFinal {
     
    	/**
    	 * Togiz Kumalak Final Project.
    	 */
    	public static void main(String[] args) {
    		TogizKumalakFrame myFrame = new TogizKumalakFrame();
    		myFrame.setTitle("TogizKumalak, Final Version");
    		myFrame.setVisible(true);
    	}
     
    }
     
    class TogizKumalakFrame extends JFrame{
    	private final int FRAMEW = 300;
    	private final int FRAMEH = 200;
    	private int subFrameLocation = 50;
     
    	public TogizKumalakFrame()
    	{
    		setSize(FRAMEW, FRAMEH);
    		addWindowListener(new WindowCloser());
     
    		/*  Menu added with subframe option.  */
    		JMenuBar menuBar = new JMenuBar();
    		setJMenuBar(menuBar);
     
    		JMenu fileMenu = new JMenu("File");
    		menuBar.add(fileMenu);
     
    		JMenuItem makeSubFrameItem = new JMenuItem("Play The Game");
    		fileMenu.add(makeSubFrameItem);
     
    		MakeSubFrameListener mySubFrameListener = new MakeSubFrameListener();
    		makeSubFrameItem.addActionListener(mySubFrameListener);
     
    		JMenuItem exitItem = new JMenuItem("Exit");
    		fileMenu.add(exitItem);
     
    		ExitListener myExitListener = new ExitListener();
    		exitItem.addActionListener(myExitListener);
    	}
     
    	private class WindowCloser extends WindowAdapter
    	{
    		public void windowClosing(WindowEvent event)
    		{
    			System.exit(0);
    		}
    	}
     
    	/*  Subframe listener.  */
    	private class MakeSubFrameListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    			TogizKumalakSubFrame myframe = new TogizKumalakSubFrame();
    			myframe.setLocation(subFrameLocation, subFrameLocation);
    			if(subFrameLocation >= 500)
    			{
    				subFrameLocation = 50;
    			}
    			else
    			{
    				subFrameLocation += 50;
    			}
    			myframe.setVisible(true);
    		}
    	}
     
    	/*  exit listener  */
    	private class ExitListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    			System.exit(0);
    		}
    	}
     
    }
     
    class TogizKumalakSubFrame extends JFrame
    {
    	private TogizKumalakPanel myPanel;
    	private final int FRAMEW = 900;
    	private final int FRAMEH = 400;
     
    	/*  Version 11, 23.1, serializability.  Declared contentPane at the beginning in case access was
    	needed at more than one point later on when saving and loading.  */
     
    	Container contentPane;
     
    	/*  Version 11, 23.2.  JFileChooser.  */
     
    	JFileChooser myChooser;
     
    	public TogizKumalakSubFrame()
    	{
    	/*  Version 11, 23.2.  JFileChooser.  */
     
    	/***  Note this obscure problem:  Constructing a JFileChooser will take an inordinate amount of time
    	If there are zip files on the desktop.  This is a hideous interaction between Microsoft Windows and
    	Java.  The solution to the problem is not to change the Java code--there's not much that can be done
    	there.  The solution is to move any zipped folders on the desktop into a non-zipped folder.  */
     
    		myChooser = new JFileChooser();
     
    		setSize(FRAMEW, FRAMEH);
     
    		myPanel = new TogizKumalakPanel();
    		contentPane = getContentPane();
     
    		contentPane.add(myPanel);
    		addWindowListener(new WindowCloser());
     
    		/*  Version 11, 23.3.  Close menu option for subframe.  */
     
    		JMenuBar menuBar = new JMenuBar();
    		setJMenuBar(menuBar);
     
    		JMenu fileMenu = new JMenu("File");
    		menuBar.add(fileMenu);
     
    		JMenuItem restartItem = new JMenuItem("Restart");
    		fileMenu.add(restartItem);
     
    		RestartListener myRestartListener = new RestartListener();
    		restartItem.addActionListener(myRestartListener);
     
     
    		/*  Version 11, 23.1.  Serializability/saving.  */
     
    		JMenuItem saveItem = new JMenuItem("Save");
    		fileMenu.add(saveItem);
     
    		SaveListener mySaveListener = new SaveListener();
    		saveItem.addActionListener(mySaveListener);
     
    		JMenuItem loadItem = new JMenuItem("Load");
    		fileMenu.add(loadItem);
     
    		LoadListener myLoadListener = new LoadListener();
    		loadItem.addActionListener(myLoadListener);
     
    		JMenuItem closeItem = new JMenuItem("Close");
    		fileMenu.add(closeItem);
     
    		CloseListener myCloseListener = new CloseListener();
    		closeItem.addActionListener(myCloseListener);
    	}
     
     
     
    	private class WindowCloser extends WindowAdapter
    	{
    		public void windowClosing(WindowEvent event)
    		{
    			dispose();
    		}
    	}
     
    	/*  Version 10, 22.3, menu support for restarting, in subframe for Version 11, 23.3.  */
     
    	private class RestartListener implements ActionListener {
    		public void actionPerformed(ActionEvent event){
     
    			myPanel.renewBoard();
     
    			/*  Version 10, 22.2.  Text area support.  */
     
    			myPanel.renewTextArea();
     
    			myPanel.setMoveCount(1);
    		}
    	}
     
    	/*  Version 11, 23.3.  Close listener added for subframe.  */
     
    	private class CloseListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    			dispose();
    		}
    	}
     
    	/*  Version 11, 23.1.  Serializability/saving.  */
     
    	private class SaveListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    			String fileName;
    			myChooser.setCurrentDirectory(new File("."));
    			myChooser.showSaveDialog(TogizKumalakSubFrame.this);
    			fileName = myChooser.getSelectedFile().getPath();
     
    			try
    			{
    				ObjectOutputStream objOut = new ObjectOutputStream(
    					new FileOutputStream(fileName));
     
    				for (int j = 7; j > 0; j--) {
    					objOut.writeInt(myPanel.getSeedCount(1, j));
    					objOut.writeInt(myPanel.getSeedCount(2, j));
    				}
    				objOut.writeInt(myPanel.getCapturedCount(1));
    				objOut.writeInt(myPanel.getCapturedCount(2));
     
     
    				/*  Version 11, 23.1.  Scroll pane and text area support when saving.  */
     
    				objOut.writeObject(myPanel.getText());
    				objOut.writeObject(myPanel.getMoveCount());
     
     
    			}
     
    			catch(IOException e)
    			{
    				System.out.println("Problem making or writing to an output stream.");
    				System.out.println(e);
    			}
    		}
    	}
     
    	/*  Version 11, 23.1.  Serializability/saving/loading.  */
     
    	private class LoadListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    			String fileName;
    			myChooser.setCurrentDirectory(new File("."));
    			myChooser.showOpenDialog(TogizKumalakSubFrame.this);
    			fileName = myChooser.getSelectedFile().getPath();
     
    			try
    			{
    				Container contentPane = getContentPane();
    				contentPane.remove(myPanel);
    				myPanel = new TogizKumalakPanel();
    				contentPane.add(myPanel, "Center");
     
    				ObjectInputStream objIn = new ObjectInputStream(
    					new FileInputStream(fileName));
     
    				for (int j = 7; j > 0; j--) {
    					myPanel.setSeedCount(1, j, objIn.readInt());
    					myPanel.setSeedCount(2, j, objIn.readInt());
    				}
     
    				myPanel.setCapturedCount(1, objIn.readInt());
    				myPanel.setCapturedCount(2, objIn.readInt());
     
    				/*  Version 11, 23.1.  Scroll pane and text area support when loading.  */
     
    				myPanel.setText((String) objIn.readObject());
    				Integer localMoveCountObject = (Integer) objIn.readObject();
    				int localMoveCount = localMoveCountObject.intValue();
    				myPanel.setMoveCount(localMoveCount);
     
    				setVisible(true);
    			}
    			catch(IOException e)
    			{
    				System.out.println("Problem making an input stream.");
    			}
    			catch(ClassNotFoundException e)
    			{
    				System.out.println("Class not found problem when reading objects.");
    			}
    		}
    	}
     
    }
     
    class TogizKumalakPanel extends JPanel {
    	private Board playBoard;
    	private int playTurn;
    	private JTextArea actionRecordArea;
    	private JScrollPane actionScrollPane;
    	private JPanel gamePanel = new JPanel();
    	private int moveCount = 1;
    	private JButton[][] buttons = new JButton[3][8];
    	private JPanel boardPanel = new JPanel();
    	private JPanel[] labelPanels = new JPanel[3];
    	private JPanel[] buttonPanels = new JPanel[3];
    	private ButtonListener[][] buttonListeners = new ButtonListener[3][8];
    	private JLabel[][] cupLabels = new JLabel[3][8];
     
     
    	public TogizKumalakPanel(){
    		super();
    		playTurn = 1;
    		playBoard = new Board();
    		actionRecordArea = new JTextArea(6, 24);
    		actionRecordArea.setEditable(false);
    		actionScrollPane = new JScrollPane(actionRecordArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    		add(actionScrollPane);
     
    		//Setup panels for components.
     
    		boardPanel.setLayout(new GridLayout(6,1));
    		//gamePanel.setLayout(new GridLayout(3,1));
     
     
    		buttonPanels[1] = new JPanel();
    		buttonPanels[2] = new JPanel();
    		buttonPanels[1].setLayout(new GridLayout(1,7));
    		buttonPanels[2].setLayout(new GridLayout(1,7));
     
     
    		labelPanels[1] = new JPanel();
    		labelPanels[2] = new JPanel();
    		labelPanels[1].setLayout(new GridLayout(1,7));
    		labelPanels[2].setLayout(new GridLayout(1,7));
     
    		//Create Buttons
    		for (int j = 7; j > 0; j--){
    			buttons[1][j] = new JButton("Play");
    			buttonListeners[1][j] = new ButtonListener();
    			buttons[1][j].addActionListener(buttonListeners[1][j]);
    			buttonPanels[1].add(buttons[1][j]);
    		}
     
            for (int j = 1; j < 8; j++){
    			buttons[2][j] = new JButton("Play");
    			buttonListeners[2][j] = new ButtonListener();
    			buttons[2][j].addActionListener(buttonListeners[2][j]);
    			buttonPanels[2].add(buttons[2][j]);
    		}
     
            //Create labels
            for (int j = 7; j > 0; j--){
            	cupLabels[1][j] = new JLabel("Player 1, Cup " + Integer.toString(j), JLabel.LEFT);
    			labelPanels[1].add(cupLabels[1][j]);
    		}
     
            for (int j = 1; j < 8; j++){
            	cupLabels[2][j] = new JLabel("Player 2, Cup " + Integer.toString(j), JLabel.LEFT);
    			labelPanels[2].add(cupLabels[2][j]);
    		}
     
            //Place component panels in boardPanel
            boardPanel.add(labelPanels[1]);
            boardPanel.add(buttonPanels[1]);
    		boardPanel.add(playBoard.getCupPanel(1));
    		boardPanel.add(playBoard.getCupPanel(2));
    		boardPanel.add(buttonPanels[2]);
    		boardPanel.add(labelPanels[2]);
     
    		gamePanel.add(playBoard.getCapturedPanel(1), BorderLayout.PAGE_START);
    		gamePanel.add(boardPanel, BorderLayout.CENTER);
    		gamePanel.add(playBoard.getCapturedPanel(2), BorderLayout.PAGE_END);
    		add(gamePanel);
     
    		addKeyListener(new KeyHandler());
    		setFocusable(true);
    	}
     
    	public void renewBoard(){
    		playBoard.resetCups();
    	}
     
    	public void renewTextArea(){
    		actionRecordArea.setText("");
    	}
     
    	public String getText(){
    		return actionRecordArea.getText();
    	}
     
    	public void setText(String textIn){
    		actionRecordArea.setText(textIn);
    	}
     
    	public int getMoveCount(){
    		return moveCount;
    	}
     
    	public void setMoveCount(int countIn){
    		moveCount = countIn;
    	}
     
    	public int getSeedCount(int player, int cup){
    		return playBoard.getSeedCount(player, cup);
    	}
     
    	public void setSeedCount(int player, int cup, int seeds){
    		playBoard.setSeedCount(player, cup, seeds);
    	}
     
    	public int getCapturedCount(int player){
    		return playBoard.getCapturedCount(player);
    	}
     
    	public void setCapturedCount(int player, int seeds){
    		playBoard.setCapturedCount(player, seeds);
    	}
     
    	private class KeyHandler extends KeyAdapter{
    		public void keyTyped(KeyEvent event){
    			char keyChar = event.getKeyChar();
    			int keyCharAsInt;
     
    			if(keyChar == '1' || keyChar == '2' || keyChar == '3' || keyChar == '4' || keyChar == '5' || keyChar == '6' || keyChar == '7'){
     				keyCharAsInt = (int) keyChar - 48;
    				setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    				playBoard.moveBoard(playTurn, keyCharAsInt);
     
    				/* Text area and scroll pane support.  */
    				actionRecordArea.append("Move:  " + moveCount + ".  Player:  " + playTurn + ".  Cup:  " + keyCharAsInt + ".\n");
    				moveCount++;
     
    				if(playTurn == 1)
    				  playTurn = 2;
    				else
    				  playTurn = 1;
    			}
    			else
    			{
    			}
    		}
    	}
     
    	public class ButtonListener implements ActionListener{
    		public void actionPerformed(ActionEvent event){
    			Object source = event.getSource();
     
    			for (int j = 7; j > 0; j--){
    				if (source == buttons[playTurn][j]){
    					playBoard.moveBoard(playTurn, j);
    					actionRecordArea.append("Move:  " + moveCount + ".  Player:  " + playTurn + ".  Cup:  " + j + ".\n");
    					moveCount++;
     
    					if(playTurn == 1)
    						playTurn = 2;
    					else
    						playTurn = 1;
    				}
    				else {
    				}
     
    			}
    		}
    	}
     
    //	/*  Serializability/saving.  */
    //	public void setBoard(Board boardIn)
    //	{
    //		playBoard = boardIn;
    //	}
    //
    //	public Board getBoard()
    //	{
    //		return playBoard;
    //	}
     
    }
     
     
     
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
     
    /*	
    */
    public class Board implements Serializable {
    	private Cup[][] gameBoard = new Cup[3][8];
    	private Cup[] captured = new Cup[3];
    	private final int INITIAL_NUMBER_OF_PEBBLES = 10;
    	//private final int PLAYER1 = 1;
    	private JPanel[] cupPanels = new JPanel[3];
    	private JPanel[] capturedPanel = new JPanel[3];
    	private final JLabel player1Label1 = new JLabel("Player 1", JLabel.LEFT);
    	private final JLabel player1Label2 = new JLabel("Captured", JLabel.LEFT);
    	private final JLabel player2Label1 = new JLabel("Player 2", JLabel.LEFT);
    	private final JLabel player2Label2 = new JLabel("Captured", JLabel.LEFT);
     
    	public Board() {
    		captured[1] = new Cup(0, 1);
    		captured[2] = new Cup(0, 2);
    		capturedPanel[1] = new JPanel();
    		capturedPanel[2] = new JPanel();
    		cupPanels[1] = new JPanel();
    		cupPanels[2] = new JPanel();
     
     
    		//Captured cup panels contain a JTextField and JLabel
    		capturedPanel[1].setLayout(new GridLayout(3,1));
    		capturedPanel[2].setLayout(new GridLayout(3,1));
     
    		capturedPanel[1].add(player1Label1);
    		capturedPanel[1].add(captured[1].getSeedField());
    		capturedPanel[1].add(player1Label2);
     
    		capturedPanel[2].add(player2Label1);
    		capturedPanel[2].add(captured[2].getSeedField());
    		capturedPanel[2].add(player2Label2);
     
     
    		//2 cup panels (grid)
    		cupPanels[1].setLayout(new GridLayout(1,7));
    		cupPanels[2].setLayout(new GridLayout(1,7));
     
    		//Cup constructors and placement in cupPanels
    		for (int j = 7; j > 0; j--) {
                gameBoard[1][j] = new Cup(INITIAL_NUMBER_OF_PEBBLES, 1);
                cupPanels[1].add(gameBoard[1][j].getSeedField());
    		}
            for (int j = 1; j < 8; j++) {
                gameBoard[2][j] = new Cup(INITIAL_NUMBER_OF_PEBBLES, 2);
    			cupPanels[2].add(gameBoard[2][j].getSeedField());
            }
     
            //Cup linking
            for(int i = 6; i > 0; i--) {
    			gameBoard[1][i].setNextCup(gameBoard[1][i + 1]);
    			gameBoard[2][i].setNextCup(gameBoard[2][i + 1]);
    			gameBoard[1][i].setNextSeedField(gameBoard[1][i + 1].getSeedField());
    			gameBoard[2][i].setNextSeedField(gameBoard[2][i + 1].getSeedField());
    		}
    		gameBoard[1][7].setNextCup(gameBoard[2][1]);
    		gameBoard[2][7].setNextCup(gameBoard[1][1]);
    		gameBoard[1][7].setNextSeedField(gameBoard[2][1].getSeedField());
    		gameBoard[2][7].setNextSeedField(gameBoard[1][1].getSeedField());
    	}
     
    /*	For making a play using focus
    */	
    /*	public void moveBoard(Cup playCup) {
    		int handfull = playCup.takeSeeds();
     
    		Cup tempReference;
    		if (handfull == 1)
    			tempReference = playCup.getNextCup();
    		else
    		tempReference = playCup;
     
    		for(int i = handfull; i > 1; i--) {
    			tempReference.addOneSeed();
    			tempReference = tempReference.getNextCup();
    		}
     
    		if (tempReference.getWhoseCup() != playCup.getWhoseCup()){
    			if((tempReference.getSeedCount() % 2) == 0) {
    				captured[playCup.getWhoseCup()].addSomeSeeds(tempReference.takeSeeds() + 1);
    			}
    		}
    	}*/
     
    /*For making a play using key input or clicking on a button.	
     */
    	public void moveBoard(int whoseTurn, int whichCup) {
    		Cup playCup = gameBoard[whoseTurn][whichCup];
    		int handfull = playCup.takeSeeds();
     
    		Cup tempReference;
    		if (handfull == 1)
    			tempReference = playCup.getNextCup();
    		else
    		tempReference = playCup;
     
    		for(int i = handfull; i > 0; i--) {
    			tempReference.addOneSeed();
    			if (i != 1)
    				tempReference = tempReference.getNextCup();
    		}
     
    		if (tempReference.getWhoseCup() != playCup.getWhoseCup()){
    			if((tempReference.getSeedCount() % 2) == 0) {
    				captured[whoseTurn].addSomeSeeds(tempReference.takeSeeds());
    			}
    		}
    		else {
    		}
    	}
     
    	public int getCupNumber(Cup cupIn) {
    		int retval = 1;
    		for(int i = 1; i <= 9; i++)
    		{
    			if(gameBoard[1][i] == cupIn || gameBoard[2][i] == cupIn)
    			  retval = i;
    		}
    		return retval;
    	}
     
    	public JPanel getCapturedPanel(int player){
    		return capturedPanel[player];
    	}
     
    	public JPanel getCupPanel(int player){
    		return cupPanels[player];
    	}
     
    	public void resetCups(){
    		for (int j = 7; j > 0; j--) {
    			gameBoard[1][j].setSeedField(INITIAL_NUMBER_OF_PEBBLES);
    			gameBoard[2][j].setSeedField(INITIAL_NUMBER_OF_PEBBLES);
    		}
    		captured[1].setSeedField(0);
    		captured[2].setSeedField(0);
    	}
     
    	public int getSeedCount(int player, int cup){
    		return gameBoard[player][cup].getSeedCount();
    	}
     
    	public void setSeedCount(int player, int cup, int seeds){
    		gameBoard[player][cup].setSeedField(seeds);
    	}
     
    	public int getCapturedCount(int player){
    		return captured[player].getSeedCount();
    	}
     
    	public void setCapturedCount(int player, int seeds){
    		captured[player].setSeedField(seeds);
    	}
    }
     
     
     
     
     
     
     
     
     
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
     
     
    public class Cup implements Cloneable, Serializable {
    	private int whoseCup;
    	private Cup nextCup;
    	private JTextField nextSeedField;
    	private JTextField seedField;
     
     
     
     
    	public Cup(int seedCountIn, int whoseCupin)
    	{
    		whoseCup = whoseCupin;
    		nextCup = null;
    		nextSeedField = null;
    		seedField = new JTextField(Integer.toString(seedCountIn), 8);
     
    		/*
    		 * The following line of code is commented out because the assignment
    		 * requires that the text fields displaying the number of seeds in each
    		 * cup be able to pass focus to the next playcup.  Setting a false value
    		 * for setEditable() makes it unable to display a cursor and focus.  For
    		 * a practical version of the game you would not want the cups text 
    		 * fields to be editable.
    		 */		
    //		seedField.setEditable(false);
    		TextFieldListener seedFieldListener = new TextFieldListener();
    		seedField.addActionListener(seedFieldListener);
    	}
     
    	public int getSeedCount()
    	{
    		return Integer.parseInt(this.seedField.getText());
    	}
     
    	public void addOneSeed()
    	{
    		int temp = this.getSeedCount();
    		seedField.setText(Integer.toString(temp + 1));
    	}
     
    	public void addSomeSeeds(int handfullin)
    	{
    		int temp = this.getSeedCount();
    		temp = temp + handfullin;
    		seedField.setText(Integer.toString(temp));
    	}
     
    	public int getWhoseCup()
    	{
    		return whoseCup;
    	}
     
    	public Cup getNextCup()
    	{
    		return nextCup;
    	}
     
    	public JTextField getNextSeedField() {
    		return nextSeedField;
    	}
     
    	public void setNextCup(Cup nextCupin)
    	{
    		nextCup = nextCupin;
    	}
     
    	public void setNextSeedField(JTextField nextFieldIn) {
    		nextSeedField = nextFieldIn;
    	}
     
    	public JTextField getSeedField()
    	{
    		return this.seedField;
    	}
     
    	public int takeSeeds() {
    		int temp = this.getSeedCount();
    		this.seedField.setText("0");
    		return temp;
    	}
     
    	public void setSeedField(int newValue){
    		seedField.setText(Integer.toString(newValue));
    	}
     
    	private class TextFieldListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    			nextSeedField.requestFocusInWindow();
    		}
    	}
    }
    Last edited by copeg; April 25th, 2011 at 08:49 AM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Keystoke Problem :-(

    code tags == readable code. I've edited your post to use the code tags. It helps to post a shorter example with only the necessary items to demonstrate the problem (in other words an SSCCE). Based upon your description it sounds like whatever a KeyListener is registered looses focus. Use How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features) or call requestFocus on the component.