Java 用 Enter 按钮中断 while 循环

标签 java swing if-statement break

问题是,我正在制作一个 JFrame,其文本显示几乎就像视觉小说一样。当 JLabel 中的文本完成后,底部会显示一个闪烁的箭头符号“>”。我已经讲到这里了,但是如果按 Enter 键,如何使“while”循环中断。网络上几乎所有的答案都是关于 JTextField 和 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;
}

编辑

所以经过一些混合后,我改变了程序......没有一个答案有效(或者我做了一些错误的事情......)

现在新代码是:

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

继续更改方法在这里(另一个类):

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

最后是新问题...我如何调用...

keyPressed(KeyEvent e)

...在 do 循环期间?

最佳答案

首先,您不需要使用 while (true) 循环。这是一个 Swing GUI,您可能面临在 Swing 事件线程上连续循环、卡住 GUI 的风险。相反,您需要以不同的方式思考,以事件驱动的方式思考,因为这是大多数 GUI(包括 Swing)的工作方式。

要使 JLabel 中的某些内容“闪烁”,请使用 Swing Timer 代替 while 循环,并在 Timer 的 ActionListener 中交替显示和不显示 JLabel 中的“>”字符。

要在按下 Enter 键时停止此操作,请使用按键绑定(bind)(而不是 KeyListener)。或者,如果 JTextField 具有焦点,则添加到 JTextField 的 ActionListener 将起作用。

<小时/>

例如,考虑尝试以下方法:

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

请注意,这里没有 while 或 do-while 循环,没有不必要的静态方法或字段,并且所有调用都在 Swing 事件线程上完成。

关于Java 用 Enter 按钮中断 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28731165/

相关文章:

ruby-on-rails - 为不同的事件运行两个不同的 after_create 语句

python - 如何测试多个变量与单个值的相等性?

Java、泛型和静态方法

java - 列表未更新的应用程序小部件 - 为什么会这样?

java - 第二个 JOptionPane 位于所有程序后面

java - 数字未显示在 JFrame 上

bash - 为什么 Bash 中 '[' 和 ']' 周围要有空格?

Java:从输入字符串数组生成 nCr 数组并返回它

c# - 如何让 J# 与 VS 2010 和 .NET 4 一起工作

Java Swing,遍历文本区域