Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default Need help making a GUI

    I've taken a year of programming classes at college, but sadly I don't have access to my old code, and some of the stuff I want to do wasn't covered in the courses.

    I want to make a GUI for a computer game I'm designing, but I'm still unfamiliar with some of the tasks involved and I'm having a hard time understanding the available tutorials. The main thing I need help with right now is the controls.

    The game is a turn-based strategy, so this is pretty simple - I plan to use keyboard input, making use of the arrow keys, a "conform" key, and a "cancel" key. These will need to be activated/deactivated and do different things, depending on whether the player is playing or navigating a menu. What's the easiest way to do this?

    Thanks in advance for any help.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I sincerely doubt that any of us will be able to present information on how to do this any better than the Sun Swing tutorials, and so I think that the key to your progress in this is to get a better understanding of those very same tutorials. It is a truism that the more you use and study these tutorials, the easier they'll be to use. So don't give up and keep up the hard effort. Also, you'll likely want to read in particular the section on key binding as this will be the best route to respond to a select number of keys.

    Much luck and welcome to the Java-Forums!

  3. #3
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Trail: Creating a GUI With JFC/Swing (The Java™ Tutorials)

    Use the swing tutorials like fubarable said and write small simple programs to get the basics down on how it works.

  4. #4
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    Thanks for the help! Looking more closely at the tutorials, I realized that NetBeans automates a lot of the stuff for the user, which makes my job easier.

    However, NetBeans isn't recognizing my Java classes from my workspace, and I haven't had any success with the "import" command. How do I get it to recognize these classes without manually copying them all into my NetBeans project folder?

  5. #5
    mangstadt is offline Member
    Join Date
    Jun 2010
    Location
    USA
    Posts
    19
    Rep Power
    0

    Default

    Are you moving from Eclipse to NetBeans? I would just take the time to manually copy everything...you'll be less likely to run into additional IDE-related problems down the road.

  6. #6
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    Yeah, I'm moving from Eclipse to NetBeans but this is weird...all my classes are listed as .class, and Netbeans is only taking .java files. I've been able to import classes into NetBeans before without trouble, though.

  7. #7
    mangstadt is offline Member
    Join Date
    Jun 2010
    Location
    USA
    Posts
    19
    Rep Power
    0

    Default

    You're copying the compiled .class files instead of the source files. Copy the files from the "src" directory of your Eclipse project.

  8. #8
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    Thanks again for the help. I've got enough coding done to start first-stage testing, but when I try to launch the program in NetBeans, it says it can't find a "Main" class in the project, and it said no main classes were found for me to select. This is despite me having my main(String[] args) method in my main GUI class. How can I fix this?

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    The name of the class: Main and the name of the method: main(String[] args) are not related.
    in my main GUI class
    Also Java is case sensitive: Main and main would be different.

  10. #10
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    I think I've just about got the keyboard stuff worked out, but for some reason the keystrokes aren't being recognized (with a bit of detective work, I discovered that the keyReleased method wasn't even being activated.) I used the NetBeans design window to make a keyRelease method for the graphics window, called "gamedisplay", and came up with this:

    Java Code:
        private void gamedisplayKeyReleased(java.awt.event.KeyEvent evt) {                                    
           System.out.println("Keystroke sent");
    ...
    }
    Wasn't really sure what to do after this, so I looked thorugh the Java tutorials and ended up adding this to the GUI constructor:

    Java Code:
            gamedisplay.setFocusable(true);
            gamedisplay.grabFocus();
    The compiler doesn't complain, but when I try running the code it gives me a null pointer exception for some reason. I'm not sure what I'm supposed to do to get the program to receive keystrokes.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Getting keystrokes can be tricky. If you aren't trying to capture the entire keyboard but a few keys such as the arrow keys and such, then you are likely better off using key bindings rather than a KeyListener.

    By the way, your NullPointerException is possibly due to your gamedisplay variable not holding a reference to an object, but that's just a guess on my part. Do you know where you set this variable up to refer to something such as with the = operator?

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    it gives me a null pointer exception
    Can you post the error message. Look at the error message for the source file line number and post that if you don't know why it generates a NPE.

  13. #13
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    Turns out I never actually instantiated the game display. The good news is that when I made this the first line in my constructor:

    Java Code:
            gamedisplay = new javax.swing.JPanel();
    The bad news is that it's still not recognizing any keystrokes. How would I go about using keybindings?

  14. #14
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

  15. #15
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    Thanks again for the help, I'm a lot closer to understanding this, but there's still a bit that's confusing me...

    It looks like I need to add actions to GameDisplay's actionMap that correspond with the pressed keys, but I can't instantiate any Actions because it's an abstract class.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Have you ever made an anonymous inner class? If not, now's the time to do it. I'd create an AbstractAction object, e.g.,
    Java Code:
    class CascadingGui extends JPanel {
      private static final String ESCAPE = "Escape";
      private Window superWindow;
    
      public CascadingGui(Window superWindow) {
        this.superWindow = superWindow;
        int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
        InputMap inMap = getInputMap(condition);
        inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), ESCAPE);
    
        // *** below I have the anonymous inner AbstractActionclass ***
        getActionMap().put(ESCAPE, new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            escapeAction();
          }
        });
      }
    
      public void escapeAction() {
        if (superWindow != null) {
          Window thisWin = SwingUtilities.getWindowAncestor(this);
          thisWin.setVisible(false);
          superWindow.setVisible(true);
        }
      }
    
    }

  17. #17
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    Sorry, still no luck...Here's the relevant parts of the code I'm using to test, the "It works" line should be printed when the left arrow is pressed:

    Java Code:
    In the GUI constructor:
    
            gamedisplay.setFocusable(true);
            gamedisplay.grabFocus();
            gamedisplay.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
    
    ***Snip***
    
            gamedisplay.getActionMap().put("left", new AbstractAction() {
              public void actionPerformed(ActionEvent e) {
              actionTest();
             }
            });
    
    ***Snip***
    
    This is with the other methods:
    
        public void actionTest() {
            System.out.println("It works!");
        }

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You may be getting the wrong input map as there are three of them. Try getting the one associated with JComponent.WHEN_IN_FOCUSED_WINDOW, i.e.,

    Java Code:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    
    import javax.swing.*;
    
    public class GameDisplayTest {
       private static void createAndShowUI() {
          JFrame frame = new JFrame("GameDisplayTest");
          frame.getContentPane().add(new GameDisplay().getGameDisplay());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    class GameDisplay {
       JPanel gamedisplay = new JPanel();
       
       public GameDisplay() {
          gamedisplay.setPreferredSize(new Dimension(400, 300));
          gamedisplay.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
          gamedisplay.getActionMap().put("left", new AbstractAction() {
             public void actionPerformed(ActionEvent arg0) {
                actionTest();
             }
          });
       }
       
       private void actionTest() {
          System.out.println("it works!");
       }
    
       public JPanel getGameDisplay() {
          return gamedisplay;
       }
    }

  19. #19
    DrKilljoy is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    Hey, thanks, it worked!

    The first thing I tried was replacing this line:

    Java Code:
    gamedisplay.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
    with this:

    Java Code:
    gamedisplay.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
    When that did nothing, I tried copying your code into an entirely new class and that did the trick. Here's the original GUI code with irrelevant/unused bits removed, would you mind taking a quick look and telling me where I went wrong?

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeSupport;
    import javax.swing.AbstractAction;
    import javax.swing.JComponent;
    import javax.swing.KeyStroke;
    
    public class tbsinterface extends javax.swing.JFrame {
    
        /** Creates new form tbsinterface */
    
        public tbsinterface() {
    
            gamedisplay = new javax.swing.JPanel();
            gamedisplay.setFocusable(true);
            gamedisplay.grabFocus();
            gamedisplay.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");        
            gamedisplay.getActionMap().put("left", new AbstractAction() {
              public void actionPerformed(ActionEvent e) {
              actionTest();
             }
            });
            initComponents();
    
    
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            gamedisplay = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            debugwindow = new javax.swing.JTextArea();
            resetbutton = new javax.swing.JButton();
            endturnbutton = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
        public void actionTest() {
            System.out.println("It works!");
        }                                       
    
        /**
        * @param args the commvand line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new tbsinterface().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify
        private javax.swing.JTextArea debugwindow;
        private javax.swing.JButton endturnbutton;
        private javax.swing.JPanel gamedisplay;
        private javax.swing.JButton resetbutton;
        // End of variables declaration
    
    }

  20. #20
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You have two different JPanels that were assigned to the gamedisplay variable, one you've added the key bindings to and was not displayed, the other object was displayed in the Jframe and does not have key bindings attached to it.

Page 1 of 2 12 LastLast

Similar Threads

  1. Need help making .jar
    By yoodidoo in forum Eclipse
    Replies: 4
    Last Post: 08-03-2009, 08:57 PM
  2. Replies: 3
    Last Post: 07-15-2009, 06:10 AM
  3. Making Documentation
    By Adam Cruge in forum New To Java
    Replies: 6
    Last Post: 04-11-2009, 07:02 PM
  4. Help making table
    By jls7168 in forum New To Java
    Replies: 2
    Last Post: 01-26-2009, 03:53 PM
  5. Help with making this algorithm better
    By RLRExtra in forum New To Java
    Replies: 6
    Last Post: 01-17-2008, 04:11 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •