KeyPressed



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


public class GamePanel extends JPanel implements KeyListener {

	private JPanel commandPanel = null;
	private JPanel healthManaPanel = null;
	private JLabel hplbl = null;
	private JProgressBar healthPB = null;
	private JLabel mplbl = null;
	private JProgressBar manaPB = null;
	private JProgressBar experiencePB = null;
	private JPanel chatMenuPanel = null;
	private JPanel charUsePanel = null;

	private JPanel chatPanel = null;
	private JPanel menuPanel = null;
	private JButton btnStart = null;
	private JScrollPane chatAreaSP = null;
	private JTextField inputTF = null;
	private JTextArea chatAreaTA = null;

	public GamePanel() {
		super();
		initialize();
	}


	private  void initialize() {
	    this.setLayout(new BorderLayout());
		this.setSize(800,600);
		this.setOpaque(false);
		this.add(getCommandPanel(), java.awt.BorderLayout.SOUTH);
		this.setFocusable(true);
		this.addKeyListener(this);
	}


	public void keyPressed(KeyEvent e){
	    System.out.println("KeyPressed"+ e.getKeyCode());
	    int key = e.getKeyCode();
	    if(key == KeyEvent.VK_ENTER){
	        String text = inputTF.getText().trim();
	        if(inputTF.isVisible()&& text.equals("")){
	            inputTF.setVisible(false);
	            
	            repaint();
	        }
	        else{
	            if(!inputTF.isVisible()){
	                inputTF.setVisible(true);
	                repaint();
	            }
	            if(!text.trim().equals("")){
	                //To be send to the server to all clients
	                // This is a simulation
	                chatAreaTA.append("testuser: "+ text);
	                inputTF.setText("");
	            }
	        }
	    }
	}

	public void keyReleased(KeyEvent e){}
	public void keyTyped(KeyEvent e){}

	private JPanel getCommandPanel() {
		if (commandPanel == null) {
			commandPanel = new JPanel();
			commandPanel.setLayout(new BorderLayout());
			commandPanel.add(getChatMenuPanel(), java.awt.BorderLayout.EAST);
			commandPanel.add(getCharUsePanel(), java.awt.BorderLayout.CENTER);
		}
		return commandPanel;
	}

	private JPanel getHealthManaPanel() {
		if (healthManaPanel == null) {
			hplbl = new JLabel();
			mplbl = new JLabel();
			healthManaPanel = new JPanel();
			GridBagConstraints gbc = new GridBagConstraints();
			healthManaPanel.setLayout(new GridBagLayout());
			gbc.gridx = 0;
			gbc.gridy = 0;
			gbc.anchor = GridBagConstraints.CENTER;
			gbc.ipadx = 15;
			gbc.insets = new Insets(5,10,5,0);
			hplbl.setText("HP");
			mplbl.setText("MP");
			healthManaPanel.add(hplbl, gbc);
			gbc.gridx++;
			healthManaPanel.add(getHealthPB(), gbc);
			gbc.gridx = 0;
			gbc.gridy++;
			healthManaPanel.add(mplbl, gbc);
			gbc.gridx++;
			healthManaPanel.add(getManaPB(), gbc);
		}
		return healthManaPanel;
	}

	private JProgressBar getHealthPB() {
		if (healthPB == null) {
			healthPB = new JProgressBar();
			healthPB.setValue(75);
			healthPB.setString("Test");
			healthPB.setStringPainted(true);
		}
		return healthPB;
	}
   
	private JProgressBar getManaPB() {
		if (manaPB == null) {
			manaPB = new JProgressBar();
			manaPB.setString("test2");
			manaPB.setStringPainted(true);
			manaPB.setValue(65);
		}
		return manaPB;
	}

	private JProgressBar getExperiencePB() {
		if (experiencePB == null) {
			experiencePB = new JProgressBar();
			experiencePB.setStringPainted(true);
		}
		return experiencePB;
	}
  
	private JPanel getChatMenuPanel() {
		if (chatMenuPanel == null) {
			chatMenuPanel = new JPanel();
			chatMenuPanel.setLayout(new BorderLayout());
			chatMenuPanel.add(getChatPanel(), java.awt.BorderLayout.WEST);
			chatMenuPanel.add(getMenuPanel(), java.awt.BorderLayout.CENTER);
		}
		return chatMenuPanel;
	}
 
	private JPanel getCharUsePanel() {
		if (charUsePanel == null) {
			charUsePanel = new JPanel();
			charUsePanel.setLayout(new BorderLayout());
			charUsePanel.add(getExperiencePB(), java.awt.BorderLayout.NORTH);
			charUsePanel.add(getHealthManaPanel(), java.awt.BorderLayout.WEST);
		}
		return charUsePanel;
	}

	private JPanel getChatPanel() {
		if (chatPanel == null) {
			chatPanel = new JPanel();
			chatPanel.setLayout(new BorderLayout());
			chatPanel.add(getInputTF(), java.awt.BorderLayout.NORTH);
			chatPanel.add(getChatAreaSP(), java.awt.BorderLayout.CENTER);
		}
		return chatPanel;
	}
  
	private JPanel getMenuPanel() {
		if (menuPanel == null) {
			menuPanel = new JPanel();
			menuPanel.add(getBtnStart(), null);
		}
		return menuPanel;
	}
    
	private JButton getBtnStart() {
		if (btnStart == null) {
			btnStart = new JButton();
			btnStart.setText("Start");
			btnStart.addActionListener(new java.awt.event.ActionListener() { 
				public void actionPerformed(java.awt.event.ActionEvent e) {
					    System.exit(0);
				}
			});
		}
		return btnStart;
	}

	private JScrollPane getChatAreaSP() {
		if (chatAreaSP == null) {
			chatAreaSP = new JScrollPane();
			chatAreaSP.setViewportView(getChatAreaTA());
		}
		return chatAreaSP;
	}

	private JTextField getInputTF() {
		if (inputTF == null) {
			inputTF = new JTextField();
			inputTF.setVisible(false);
			inputTF.setColumns(15);
			inputTF.setDocument(new FixedSizePlainDocument(40));
		}
		return inputTF;
	}
	class FixedSizePlainDocument extends PlainDocument {
        int maxSize;
    
        public FixedSizePlainDocument(int limit) {
            maxSize = limit;
        }
    
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if ((getLength() + str.length()) <= maxSize) {
                super.insertString(offs, str, a);
            } else {
                throw new BadLocationException("Insertion exceeds max size of document", offs);
            }
        }
    }

	private JTextArea getChatAreaTA() {
		if (chatAreaTA == null) {
			chatAreaTA = new JTextArea();
			chatAreaTA.setEditable(false);
			chatAreaTA.setColumns(15);
			chatAreaTA.setLineWrap(true);
		}
		return chatAreaTA;
	}
}

Hi I would like to know how to implement the KeyPressed function… I have place in the code. But for some reason it does not work with the main application. I have to minimize the application, is then the KeyPressed would detect the KeyPressed. However once I place in the game logic for it. It just refuse to work!

Basically what I am trying to do is that upon the pressed of the Enter button (VK_ENTER) by the user the TextField would be setVisible(true). Then when the enter button is press again, the software would detect for any text within the field, if there is it would append into the text area just below the textfield. But if there are no text, then the textfield would be setVisible(false).

So I hope there is a solution for this… Many Thanks.

first, I’m not reading that bunch of code, how about cuting it to important stuff? Second learn to express yourself better in english.

Now to the problem… I see that it’s just a JPanel with keylistener on it. Make sure your JFrame dosen’t also have a keylistener or there will be conflict (happened to me once, basicly you need to have one key listener and process events to other parts of game).

[quote]I have to minimize the application, is then the KeyPressed would detect the KeyPressed. However once I place in the game logic for it. It just refuse to work!
[/quote]
When you say minimize, do you mean iconify or without game logic?

First of all, you’ve nested a JPanel in a JPanel. That means your keyboard focus is automaticly set to the second JPanel (the one which isn’t setFocusable(true) and which doesn’t have a KeyListener added). Try calling requestFocus(); in your initialise() method (only after setting the GamePanel focusable and after adding the KeyListener!).

Cut from above lines of codes

[b]
public void keyPressed(KeyEvent e){
System.out.println(“KeyPressed”+ e.getKeyCode());
int key = e.getKeyCode();
if(key == KeyEvent.VK_ENTER){
String text = inputTF.getText().trim();
if(inputTF.isVisible()&& text.equals("")){
inputTF.setVisible(false);

            repaint();
        }
        else{
            if(!inputTF.isVisible()){
                inputTF.setVisible(true);
                repaint();
            }
            if(!text.trim().equals("")){
                //To be send to the server to all clients
                // This is a simulation
                chatAreaTA.append("testuser: "+ text);
                inputTF.setText("");
            }
        }
    }
}

[/b]

My JFrame does not have a keyListener.

Minimize as in the program being iconify.

Forgive me for my english, my command of english is not that fantastic, so I just typed out whatever came to mind that I would say to a person.

Cheers!

if you really have jpanel inside jpanel then you have focus problems (as most of people who can’t get listener to work) as jamison said. You didn’t say anything about if jamison’s solution helped you… did it?

I only manage to see his post after i have replied to Kova’s post…

As for the solution for Jamison, it does work. However if I iconify the window again. The listener have seem to have stop its function. I have tried on other platforms and workstations. The same problems still araises. So I am worried if the user likes to iconify the window, then the problem would surface.

I am now trying to see if the problem could be the changing of panels from an event.

What I meant from the above statement is that my program have a login panel, if login is sucessful, the panel would change to the GamePanel as you can see from the codes in the first post. So I may suspect if the changing of panels might cause this problem. Reason being My GamePanel is the only panel that implements the interface KeyListener.

Any comments? Do you think my suspect might be wrong? I also do not know what to do? Quite Lost now.

Yeah it’s all about focus. If you have a JPanel with keylistener and a JTextField within it, when you click on JTextField it will steal the focus and all keys you type, but this is good since you want to type something within it.
In this example after you login then second JPanel steals the focus from first who has added keylistener. Also on minimize and restore, when you restore your application focus is given to JFrame (or it’s container, don’t know exactly).
I think best solution is adding keylistener in JFrame and then pass events to object that needs it. Second solution is to monitor minimze / restore and to give focus back to proper JPanel when restore (or whatever) happens. If you deceide for first solution then when you display the JPanel with animation in it you’ll have to give back focus to JFrame for it to be able to receive key events. Hope this is clear enough to get it working.

One way to get around focus, and ONLY if you so desire, you can add an AWTEvent listener to the windowing toolkit.

I use the code:

Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);

and then:

public void eventDispatched(AWTEvent awtEvent)
 {
  if (awtEvent instanceof KeyEvent && awtEvent.getID() == KeyEvent.KEY_PRESSED)
  {
   KeyEvent evt = (KeyEvent)awtEvent;

   boolean shift = evt.isShiftDown();
   boolean control = evt.isControlDown();
   int code = evt.getKeyCode();

   // Handle the event.
  }
  else
  {
   // DEBUG
   //System.out.println(",");
  }
 }

I use the above to handle a keypress from anywhere in the app, like Alt-X to exit the app from wherever I am in the focus.

I hope this helps and that It’s not incorrect. :wink: