简体   繁体   English

如何扫描来自 jtextfield 的输入?

[英]How to scan for an input from a jtextfield?

import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;

@SuppressWarnings("unused")
public class Fun {
    @SuppressWarnings({"static-access", "resource"})
    public static void main(String[] args) {
        JFrame f = new JFrame("The Gamer Zone");
        //set size and location of frame
        f.setSize(390, 300);
        f.setLocation(100, 150);
        //make sure it quits when x is clicked
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //set look and feel
        f.setDefaultLookAndFeelDecorated(true);
        JLabel labelM = new JLabel("Are you an epic gamer? (true,false) ");
        labelM.setBounds(50, 50, 250, 30);
        JTextField Text = new JTextField();
        //set size of the text box
        Text.setBounds(50, 100, 200, 30);
        //add elements to the frame
        f.add(labelM);
        f.add(Text);
        f.setLayout(null);
        f.setVisible(true);
        String answer1 = Text.getText();
        Scanner sc = new Scanner(answer1);
        int x = 0;
        while (x < 1) {
            try {
                if (sc.next() == "true") {
                    f.remove(labelM);
                    x++;
                }
            } catch (Exception e) {
                System.out.println("Something went wrong");
            }
        }
    }
}

I am trying to get it to remove LabelM when the input in the jtext field is "true."LabelM字段中的输入为“true”时,我试图让它删除 LabelM。 I am just trying to learn how JFrame s work, and this is my first time working with one.我只是想了解JFrame的工作原理,这是我第一次使用它。 Is there a better way to scan from a JFrame ?有没有更好的方法从JFrame进行扫描?

You would want to use a DocumentListener which will fire off methods whenever the text of the field is changed.您可能希望使用DocumentListener ,只要字段的文本发生更改,它就会触发方法。 Currently your example gets the text once (after showing the JFrame and that will never change as well as you are using the wrong method/operator to compare string objects in java you should use equals , or a variant like contains etc see here or here for more.目前,您的示例获取文本一次(在显示JFrame之后,这将永远不会改变,以及您使用错误的方法/运算符来比较 java 中的string对象,您应该使用equalscontains等变体,请参见此处此处更多的。

Also some other points (I probably sound like a broken record):还有其他一些观点(我可能听起来像是破纪录):

  1. Don't use a null / AbsoluteLayout rather use an appropriate LayoutManager不要使用null / AbsoluteLayout而是使用适当的LayoutManager
  2. Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you不要在组件上调用setBounds()setSize() ,如果您使用正确的布局管理器,这将为您处理
  3. Call JFrame#pack() before setting the frame to visible when using a LayoutManager在使用LayoutManager时将框架设置为可见之前调用JFrame#pack()
  4. All Swing components should be called on the EDT via SwingUtilities.invokeLater应通过SwingUtilities.invokeLaterEDT上调用所有 Swing 组件

Here is an example which simply hides or shows the JLabel when the word true is found or not found regardless of case in the JTextField :这是一个示例,它在找到或未找到单词true时简单地隐藏或显示JLabel ,无论JTextField中的大小写如何:

在此处输入图像描述

TestApp.java: TestApp.java:

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class TestApp {

    public TestApp() {
        createAndShowGui();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TestApp::new);
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame("TestApp");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));
        JLabel labelM = new JLabel("Are you an epic gamer? (true,false) ");
        JTextField textField = new JTextField();
        
        textField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                checkForInput();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                checkForInput();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                checkForInput();
            }

            public void checkForInput() {
                if (textField.getText().toLowerCase().equals("true")) {
                    labelM.setVisible(false);
                } else {
                    labelM.setVisible(true);
                }
            }
        });

        panel.add(labelM, BorderLayout.NORTH);
        panel.add(textField, BorderLayout.CENTER);

        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

}

The magic happens in the checkForInput called by the DocumentListener which is attached to the JTextField魔术发生在被附加到JTextFieldDocumentListener调用的checkForInput

public void checkForInput() {
    if (textField.getText().toLowerCase().contains("true")) {
        labelM.setVisible(false);
    } else {
        labelM.setVisible(true);
    }
}

If you wanted to add or remove the label as opposed to setting its visibility simply switch it out with panel.remove(labelM) or panel.add(labelM) respectively如果您想添加或删除 label 而不是设置其可见性,只需分别使用panel.remove(labelM)panel.add(labelM)将其切换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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