Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (491)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (555)
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  
  Unusual interaction between keyListener and JMenu  (Read 1205 times)
0 Members and 1 Guest are viewing this topic.
Offline mellowyellow

Junior Newbie





« Posted 2005-11-26 05:49:50 »

I'm working on a simple sokoban game.  I am using a JMenu which has 3 options: Reset board, Load board, and quit.  Once the board is loaded the user should be able to use the keyboard to move around the game board.  However, after the game is loaded, the keys do not work until I click the "Reset board" option on the menu (which is currently unimplemented and does nothing except a print statement).  I can't figure out what's causing this strange behavior.  Portions of the code are below.  The Board class, which I've not included, implements the character movement functions. 

Just to reiterate, if I "Load board" -> "Reset board", the keys work fine, but I shouldn't have to "Reset board" to get the keys to work.

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  
 
public class Sokoban extends JFrame implements ActionListener {

Board b;
boolean boardLoaded = false;


   public class View extends JComponent {

      int xVal, yVal;
      ImageIcon manIcon;
      ImageIcon ballIcon;
      Image man, ball;
      int cellHeight, cellWidth;
      int initialW = 500;
      int initialH = 300;
      Color floorColor;
     
      public View()  {
         // ImageIcon code snipped
 
         
         // Set the mouse listener
        addMouseListener(new MouseAdapter() {
            public void mouseClicked (MouseEvent event) {
               xVal = event.getX();
               yVal = event.getY();
            }
         });

         // Set the key listener
        addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
               if(boardLoaded) {
                  char c = e.getKeyChar();
                  if(c == 'h') b.moveLeft();
                  if(c == 'l') b.moveRight();
                  if(c == 'j') b.moveDown();
                  if(c == 'k') b.moveUp();
               }
            }
            public void keyPressed(KeyEvent e) {
               if(boardLoaded) {
                  int code = e.getKeyCode();
                  if(code == KeyEvent.VK_LEFT) b.moveLeft();
                  if(code == KeyEvent.VK_RIGHT) b.moveRight();
                  if(code == KeyEvent.VK_UP) b.moveUp();
                  if(code == KeyEvent.VK_DOWN) b.moveDown();
               }
            }
            public void keyReleased(KeyEvent e) {}
         });
      }

      public void paintComponent(Graphics g) {
         Graphics2D g2 = (Graphics2D) g;
         if(!boardLoaded) {
            //Draw Splash Screen
        }
         else {
            // Code to draw board snipped
                                                                }
      }

      public Dimension getPreferredSize() {
         return new Dimension(initialW, initialH);
      }

   }

public static void main(String[] args)  {
      javax.swing.SwingUtilities.invokeLater(new Runnable()   {
         public void run()  {
            Sokoban s = new Sokoban();
         }
      });
}

////////// Constructor
public Sokoban() {
   showGUI();
}

////////// Sets up JFrame
private void showGUI() {

      // Set up frame
     JFrame.setDefaultLookAndFeelDecorated(true);
      JFrame frame = new JFrame("Sokoban");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Create content
     Container content = frame.getContentPane();
                                           BorderLayout layout = new BorderLayout();
      content.setLayout(layout);  

      // Set up board
     View view = new View();
      view.setFocusable(true);
      content.add(view, BorderLayout.CENTER);

      // Set up menu
     JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Actions");
      menuBar.add(menu);
      JMenuItem reset = new JMenuItem("Reset game");
      JMenuItem load = new JMenuItem("Load board");
      JMenuItem quit = new JMenuItem("Quit");
      load.addActionListener(this);
      load.setActionCommand("load");
      reset.addActionListener(this);
      reset.setActionCommand("reset");
      quit.addActionListener(this);
      quit.setActionCommand("quit");
      menu.add(reset);
      menu.add(load);
      menu.add(quit);
      frame.setJMenuBar(menuBar);

      //Display the window
     frame.pack();
      frame.setVisible(true);

   }

   //// Actions for menu selections
  public void actionPerformed(ActionEvent e) {
      if(e.getActionCommand().equals("load")) {
         LinkedList<String> boardList = new LinkedList<String>();
         int rows = 0;
         int cols = 0;

         FileDialog fd = new FileDialog(this, "Choose level file");
         fd.setVisible(true);
         FileInputStream fin;
         String line;
         try {
            fin = new FileInputStream(fd.getDirectory()+fd.getFile());
            BufferedReader br = new BufferedReader(new InputStreamReader(fin));
            while((line = br.readLine()) != null) {
               //System.out.println(line);
              boardList.add(line);
               if(line.length() > cols) cols = line.length();
            }
            fin.close();
         }
         catch (IOException io) {
            System.err.println("Unable to read from file");
         }
         rows = boardList.size();

         b = new Board(rows, cols);
         b.getBoard(boardList);
         boardLoaded = true;
      }
      if(e.getActionCommand().equals("quit")) {
         System.exit(0);
      }
      if(e.getActionCommand().equals("reset")) {
         System.out.println("not implemented yet");
      }
   }
}
Offline Vorax

Senior Member


Projects: 1


System shutting down in 5..4..3...


« Reply #1 - Posted 2005-11-26 06:08:16 »

I would try adding a request focus after you make the frame visible - like:

1  
2  
3  
4  
5  
  //Display the window
frame.pack();
frame.setVisible(true);

view .requestFocus();



Offline mellowyellow

Junior Newbie





« Reply #2 - Posted 2005-11-26 06:15:32 »


1  
2  
3  
4  
5  
  //Display the window
frame.pack();
frame.setVisible(true);

view .requestFocus();




Thanks!  I tried this, but it didn't fix it.  Any other suggestions?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Vorax

Senior Member


Projects: 1


System shutting down in 5..4..3...


« Reply #3 - Posted 2005-11-26 06:37:58 »

Hmmm...  Try the brute force way with:

view.grabFocus() ;

Swing focus is always confusing.

Offline oNyx

JGO Coder


Medals: 2


pixels! :x


« Reply #4 - Posted 2005-11-26 07:32:47 »

You can try this:
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/KeyEventPostProcessor.html

Or setFocusable(false) everywhere.

弾幕 ☆ @mahonnaiseblog
Offline Ask_Hjorth_Larsen

Junior Member




Java games rock!


« Reply #5 - Posted 2005-11-27 15:25:13 »

RequestFocusInWindow is nicer, considering that other programs may be running.
Offline mellowyellow

Junior Newbie





« Reply #6 - Posted 2005-11-30 23:48:43 »

Adding a view.grabFocus() after loading the game board fixed the problem.  Thanks for all the possible solutions!
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.

Nickropheliac (15 views)
2014-08-31 22:59:12

TehJavaDev (23 views)
2014-08-28 18:26:30

CopyableCougar4 (29 views)
2014-08-22 19:31:30

atombrot (41 views)
2014-08-19 09:29:53

Tekkerue (38 views)
2014-08-16 06:45:27

Tekkerue (35 views)
2014-08-16 06:22:17

Tekkerue (24 views)
2014-08-16 06:20:21

Tekkerue (34 views)
2014-08-16 06:12:11

Rayexar (72 views)
2014-08-11 02:49:23

BurntPizza (48 views)
2014-08-09 21:09:32
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!