Results 1 to 8 of 8
  1. #1
    Codeless is offline Member
    Join Date
    Nov 2010
    Posts
    37
    Rep Power
    0

    Default Having trouble with my action listener

    I decided I want to hardcode a lot of facts into my brain... it would probably help me a lot in the long run, so I decided to make a tool to help me learn. basically I'm making a simple program that I can copy questions and answer in from my book and when I press enter it will show the answer or jump to another random question. this way I can keep adding questions and revise a little each day.

    anyway the problem I have is my listener doesn't appear to work... that is to say keyPressed is always false. why is this?

    Java Code:
    //class Frame
    
    package pkg;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class Frame extends JFrame
    {
    
    	public static String title = "Java";
    	public static Dimension size = new Dimension(700, 550);
    	Quiz quiz;
    	
    	public Frame()
    	{
    		setTitle(title);
    		setSize(size);
    		setResizable(false);
    		setLocationRelativeTo(null);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		setLayout(new GridLayout(1, 1, 0, 0));
    		quiz = new Quiz(this);
    		add(quiz);
    		setVisible(true);
    	}
    	
    	public static void main(String[] args)
    	{
    		Frame frame = new Frame();
    	}
    }
    
    //class Quiz
    package pkg;
    
    import java.awt.Color;
    import java.awt.Graphics;
    import java.util.ArrayList;
    import java.util.Random;
    import javax.swing.JPanel;
    
    public class Quiz extends JPanel implements Runnable
    {
    	Thread thread = new Thread(this);
    	Random random = new Random();
    	ArrayList<String> questions  = new ArrayList();
    	String question = getQuestion();
    	static boolean keyPressed = false;
    
    	public Quiz(Frame frame)
    	{
    		addKeyListener(new Listener());
    		thread.start();
    	}
    
    	public String getQuestion()
    	{
    		questions.add("1");
    		questions.add("2");
    		questions.add("3");
    
    
    		int randomNumber = random.nextInt(((questions.size() - 1) - 0 + 1) + 0);
    
    
    		return questions.get(randomNumber);
    	}
    
    	public void paintComponent(Graphics g)
    	{
    		g.setColor(new Color(0, 0, 0));		
    		g.fillRect(0, 0, getWidth(), getHeight());
    
    		g.setColor(new Color(255, 255, 255));
    		g.drawString(question, 25, 30);
    	}
    
    	public void run() 
    	{	
    		while(true)
    		{	
    			System.out.println("debug key " + keyPressed);
    			if(keyPressed)
    			{
    				question = getQuestion();
    				keyPressed = false;
    				repaint();
    			}
    			
    			try
    			{
    				Thread.sleep(1);
    			}
    			catch(Exception e)
    			{
    
    			}
    		}
    
    
    	}
    }
    //class Listener
    
    package pkg;
    
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    public class Listener implements KeyListener
    {
    
    	public void keyPressed(KeyEvent e) 
    	{
    System.out.println("This code is never reached");
    		int key = e.getKeyCode();
    		
    		switch(key)
    		{
    		case KeyEvent.VK_ENTER:
    			Quiz.keyPressed = true;
    			System.out.println("debug enter");
    			return;
    		}
    	}
    
    	@Override
    	public void keyReleased(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public void keyTyped(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    	
    
    }

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

    Default Re: Having trouble with my action listener

    Problems:
    • Your problem title mentions "problem with my action listener" but there are no ActionListeners involved with your code or question.
    • KeyListeners only work if the component being listened to is focusable and has the focus.
    • JPanels aren't focusable.
    • A kludge is to set the JPanel focusable and then call requestInWindow() on it.
    • If you do this, then yes, your KeyListener will likely work, but your overall design is not a good one.
    • You should strive to avoid use of KeyListeners for Swing applications as a general rule.
    • Your use of polling is, pardon the expression, atrocious. Just don't do this. Swing is event driven and rather than poll in a background thread, respond to events.
    • Consider using Key Bindings here instead. Google the tutorial as it will tell and show you most of what you need to know.
    Last edited by Fubarable; 12-24-2012 at 07:46 PM.

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

    Default Re: Having trouble with my action listener

    For example, with Key Bindings, you can add components that can steal the focus to the GUI, and even if the bound container doesn't have the focus, as long as it is still within the focused window, it will remain bound:

    Java Code:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class TrapEnter extends JPanel {
       private static final String ENTER_NOT_PRESSED = "Enter Not Pressed";
       private static final String ENTER_PRESSED = "Enter Pressed";
       private static final int PREF_W = 400;
       private static final int PREF_H = 300;
       private JLabel label = new JLabel(ENTER_NOT_PRESSED);
    
       public TrapEnter() {
          add(label);
    
          // add a component that steals the focus
          add(new JButton(new AbstractAction("This Has Stolen The Focus") {
    
             @Override
             public void actionPerformed(ActionEvent evt) {
                System.out.println("\"" + evt.getActionCommand() + "\" button was pressed");
             }
          }));
    
          int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
          InputMap inputMap = getInputMap(condition);
          ActionMap actionMap = getActionMap();
    
          inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
                ENTER_PRESSED);
          inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
                ENTER_NOT_PRESSED);
    
          actionMap.put(ENTER_PRESSED, new EnterAction(ENTER_PRESSED));
          actionMap.put(ENTER_NOT_PRESSED, new EnterAction(ENTER_NOT_PRESSED));
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private class EnterAction extends AbstractAction {
          public EnterAction(String text) {
             super(text);
             putValue(ACTION_COMMAND_KEY, text);
          }
    
          @Override
          public void actionPerformed(ActionEvent evt) {
             label.setText(evt.getActionCommand());
          }
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("TrapEnter Test");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new TrapEnter());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    
    }

  4. #4
    Codeless is offline Member
    Join Date
    Nov 2010
    Posts
    37
    Rep Power
    0

    Default Re: Having trouble with my action listener

    Haven't come across key bindings... well I guess that's what I'm gonna look at today.

    thanks for the response... oooo when I'm done I'll copy this advice for my finished app lol

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,236
    Rep Power
    19

    Default Re: Having trouble with my action listener

    Moved from New to Java

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    Codeless is offline Member
    Join Date
    Nov 2010
    Posts
    37
    Rep Power
    0

    Default Re: Having trouble with my action listener

    I have another gui issue...

    I decided to use JTextArea so I can wrap my text (I blended it in with my Jpanel colours) but I don't know how to reposition it. how can I tweek the y axis of the jtextarea relative to the Jpanel? the methods of jtextarea didn't have an affect. is it under the influence of the layoutmanager? but I would of thought that only applied to the panel as the jtextarea is on the panel.

    it's a little to close to the top of the window.

    since I posted I made it read in a file so I could use my app for other purposes, and made different style question formats depending on what key you press.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Having trouble with my action listener

    This should really have gone into a different thread.

    Yes, the text area will be positioned (and sized) by the layout manager of whatever is containing it. The text area can have borders, including empty ones, and perhaps this will help give it some space at the top. Alternatively the layout manager of whatever the text area is included in may allow for spaces to be set between the elements it contains - for example the common BorderLayout has a constructor (and setters) that allow you to set the horizontal and vertical spacing.

    (From a users point of view, many of us appreciate a little polish to user interfaces and spacing is an important - if subliminal - part of that. The layout manager's management of spacing is a good way of achieving a pleasing consistency.)

    If you continue having problems with placement of the component, post a simple example illustrating the problem. Ie remove all your application logic (which is irrelevant to this) and post something runnable and describe what's not good about the appearance. If you do start a new thread for this, post a link here to there.

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

    Default Re: Having trouble with my action listener

    1+ to the great advice that Pete gives in his post above.

    Also, while it's fun to try to tweak a GUI to be as pretty as possible, make sure that you spend some time tweaking your non-GUI logic classes. You should be thinking about what a Question class should look like for instance, and how your GUI's setQuestion(Question question) method would go about displaying the question, and how the GUI could test the answer by calling say question.testAnswer(String answer), or something similar.

Similar Threads

  1. action listener
    By skuskusas in forum New To Java
    Replies: 4
    Last Post: 09-04-2012, 07:13 PM
  2. Can anyone help me with an action listener?
    By mdCollins1 in forum New To Java
    Replies: 5
    Last Post: 03-21-2012, 04:07 AM
  3. Replies: 2
    Last Post: 12-11-2011, 10:44 PM
  4. Action Listener
    By greatmajestics in forum AWT / Swing
    Replies: 8
    Last Post: 03-25-2010, 05:39 PM
  5. Action Listener? how to use this?
    By jeffrey in forum New To Java
    Replies: 2
    Last Post: 10-12-2009, 08:51 AM

Posting Permissions

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