Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (498)
Games in Android Showcase (117)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  KeyPressed  (Read 1933 times)
0 Members and 1 Guest are viewing this topic.
Offline ENC

Junior Member





« Posted 2006-05-17 04:30:29 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
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.
Offline Kova

Senior Member





« Reply #1 - Posted 2006-05-17 09:53:21 »

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!
When you say minimize, do you mean iconify or without game logic?
Offline Jamison

Junior Member




We're all idiots in one way or another.


« Reply #2 - Posted 2006-05-17 12:42:42 »

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!).

I don't like you. Check out my site Smiley www.gamedevforums.com
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ENC

Junior Member





« Reply #3 - Posted 2006-05-18 01:34:58 »

Cut from above lines of codes


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("");
               }
           }
       }
   }


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!
Offline Kova

Senior Member





« Reply #4 - Posted 2006-05-18 15:15:33 »

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?
Offline ENC

Junior Member





« Reply #5 - Posted 2006-05-19 01:32:59 »

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.
Offline Kova

Senior Member





« Reply #6 - Posted 2006-05-19 14:16:35 »

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.
Offline modelsmith

Senior Newbie




"Never stop three feet short."


« Reply #7 - Posted 2006-05-19 22:57:27 »

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:
1  
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);


and then:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
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
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

radar3301 (12 views)
2014-09-21 23:33:17

BurntPizza (31 views)
2014-09-21 02:42:18

BurntPizza (22 views)
2014-09-21 01:30:30

moogie (20 views)
2014-09-21 00:26:15

UprightPath (29 views)
2014-09-20 20:14:06

BurntPizza (33 views)
2014-09-19 03:14:18

Dwinin (48 views)
2014-09-12 09:08:26

Norakomi (74 views)
2014-09-10 13:57:51

TehJavaDev (103 views)
2014-09-10 06:39:09

Tekkerue (51 views)
2014-09-09 02:24:56
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!