简体   繁体   中英

Java Break a while loop with enter button

the thing is that I'm making a JFrame with text shown almost lik an visual novel. And when the text in the JLabel is done, a blinking arrow symbol ">" is shown at the bottom. I get this far, but how to I make the 'while' loop break if I press the enter key. Allmost all answers on the web was about JTextField and Console...

public static void nextSymbol(boolean blink) {  
    ImageIcon nextIcon = null;
    boolean blinked = false;
    if(blink) {
        nextIcon = new ImageIcon("res/image/next.gif");
        while(blink){
            if (/* When ENTER is pressed */){
                System.out.println("Disabled");
                blink = false;
            }
            pause(0.01);
        }   
        blinked = true;
    }
    if(!blink && blinked)
        vnGame.nextSymbolIcon.setIcon(null);
    else
        ;
    blinked = false;
}

EDIT

So after some mixing I changed the program... none of the answers worked (or I did somethign wrong idk...)

Well the new code is now:

public static void nextSymbol() {   
    ImageIcon nextIcon = null;
    nextIcon = new ImageIcon("res/image/next.gif");
    vnGame.nextSymbolIcon.setIcon(nextIcon);
    boolean next = false;
    Continue = 0;

    do {
        vnGame.contentPane.requestFocus();
        switch(Continue) {
            case 1:{
                next = true;
                break;
            }
            default:break;
        }
    }while(!next);
    SysPrint("Continue!");nl();
}

The continue change method is here (another class):

public void keyPressed(KeyEvent e) {
    if (e.getKeyChar() == 's') {
        VONGINE.SysPrint("S");
        VONGINE.Continue = 1;
    }
} 

And finally the new problem question... How do I call the...

keyPressed(KeyEvent e)

...during the do loop?

First and foremost, you need to not use a while (true) loop. This is a Swing GUI and you risk looping continuously on the Swing event thread, freezing your GUI. Instead you need to think differently, to think in an event-driven way since that is how most GUI's, including Swing works.

To make something "blink" in a JLabel, use a Swing Timer in place of your while loop, and alternate in your Timer's ActionListener showing and not showing the ">" character in the JLabel.

To stop this when enter is pressed, use Key Bindings (not a KeyListener). Or if a JTextField has focus, then an ActionListener added to the JTextField will work.


For example consider trying something along these lines:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.*;

@SuppressWarnings("serial")
public class SwappingLabel extends JPanel {
   public static final String IMG_PATH = "http://www.guitarchordsmagic.com/images/arrow.gif";
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private JLabel nextSymbolIcon = new JLabel("", SwingConstants.CENTER);
   private Icon nextIcon;

   public SwappingLabel() throws MalformedURLException {
      // Create our ImageIcon from online (or local) source
      nextIcon = getOnlineIcon(IMG_PATH);

      // add icon to JLabel
      nextSymbolIcon.setIcon(nextIcon);

      // set up key binding to recognize enter key press
      setupKeyBinding();

      // add the JLabel to the bottom of the GUI
      setBackground(Color.white);
      JPanel southPanel = new JPanel();
      southPanel.setOpaque(false);
      southPanel.add(nextSymbolIcon);
      setLayout(new BorderLayout());
      add(southPanel, BorderLayout.PAGE_END);
   }

   private Icon getOnlineIcon(String path) throws MalformedURLException {
      URL imgUrl = new URL(path);
      return new ImageIcon(imgUrl);
   }

   private void setupKeyBinding() {
      int condition = WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();
      KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);

      // the action that will be called when enter is pressed
      Action action = new EnterAction();

      // bind the key press to the component to the action
      inputMap.put(enterKey, enterKey.toString());
      actionMap.put(enterKey.toString(), action);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class EnterAction extends AbstractAction {
      @Override
      public void actionPerformed(ActionEvent e) {
         nextSymbolIcon.setIcon(null);
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Blinking Label");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      try {
         frame.getContentPane().add(new SwappingLabel());
      } catch (MalformedURLException e) {
         e.printStackTrace();
         System.exit(-1);
      }
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Note that there are no while or do-while loops here, no unnecessary static methods or fields, and all calls are done on the Swing event thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM