有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在按下按钮后检查文本框中的文本是否与字符串匹配

我想创建一个程序,用户按下一个按钮,必须在文本框中输入一个单词,一旦他们输入了文本,他们必须按下enter按钮,他们输入的单词将根据另一个字符串进行检查。我可以让它检查他们输入的字符串,但我不确定如何操作,因此用户必须先选择一个按钮,然后输入文本,然后按enter按钮

将有多个按钮供用户选择,这些按钮将显示图像,用户需要在文本框中写入这些图像,以检查单词是否正确。他们将按下另一个按钮进行检查

例如,在bag{}{}{}上有四个图像按钮。用户选择一个按钮,然后需要使用文本框拼写单词,然后按enter键检查文本框中的文本是否与某个字符串匹配

谢谢

以下是我尝试过的:

 public class Textb extends JPanel{

 JFrame frame =new JFrame();
 JPanel panel =new JPanel();
 JButton enter =new JButton("Enter");
 JButton wordBtn =new JButton("Cat");
 JTextField tb =new JTextField();

public Textb() {

    // Panel and button layout 

    panel.setLayout(null);
    panel.setBackground(Color.WHITE);
    panel.setCursor( new Cursor(Cursor.HAND_CURSOR) ); // set the cursor to a hand 

    Insets insets = panel.getInsets();

    tb.setVisible(true);
    tb.setBounds(200 + insets.left, 5 + insets.top, 110,60);
    tb.setBackground(Color.YELLOW);


    enter.setLayout(null);
    enter.setBounds(10 + insets.left, 5 + insets.top, 110,60);
    enter.setBackground(Color.WHITE);
    enter.setBorder(BorderFactory.createEmptyBorder());
    enter.setFocusPainted( false );

    wordBtn.setLayout(null);
    wordBtn.setBounds(10 + insets.left, 70 + insets.top, 110,60);
    wordBtn.setBackground(Color.WHITE);
    wordBtn.setBorder(BorderFactory.createEmptyBorder());
    wordBtn.setFocusPainted( false );


    panel.add(tb);
    panel.add(enter);
    panel.add(wordBtn);
    frame.add(panel);
    frame.setTitle("Matching");
    frame.setSize(800, 600);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); 
    frame.setVisible(true);



    // This is where i did the action listener
    enter.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae)
        {
            if( ae.getSource().equals(wordBtn) )
            {
                if(tb.getText().equals("cat")){
                    tb.setText("Correct");
                }
            }
        }
    });
}


public static void main(String[] args) {
    new Textb();
}
}

共 (3) 个答案

  1. # 1 楼答案

    一个简单的flag变量应该可以工作:

    enter image description here

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    
    public class TestingCat extends JPanel{
    
    
    JFrame frame =new JFrame();
    JPanel panel =new JPanel();
    private int flag=0;
    
    
    
    JButton enter =new JButton("Enter");
    JButton wordBtn =new JButton("Cat");
    
    JTextField tb =new JTextField();
    
    
    
    
    public TestingCat() {
    
    
    // Panel and button layout
    
    panel.setLayout(null);
    panel.setBackground(Color.WHITE);
    panel.setCursor( new Cursor(Cursor.HAND_CURSOR) ); // set the cursor to a hand
    
    Insets insets = panel.getInsets();
    
    tb.setVisible(true);
    tb.setBounds(200 + insets.left, 5 + insets.top, 110,60);
    tb.setBackground(Color.YELLOW);
    
    
    enter.setLayout(null);
    enter.setBounds(10 + insets.left, 5 + insets.top, 110,60);
    enter.setBackground(Color.WHITE);
    enter.setBorder(BorderFactory.createEmptyBorder());
    enter.setFocusPainted( false );
    
    wordBtn.setLayout(null);
    wordBtn.setBounds(10 + insets.left, 70 + insets.top, 110,60);
    wordBtn.setBackground(Color.WHITE);
    wordBtn.setBorder(BorderFactory.createEmptyBorder());
    wordBtn.setFocusPainted( false );
    
    
    panel.add(tb);
    panel.add(enter);
    panel.add(wordBtn);
    frame.add(panel);
    frame.setTitle("Matching");
    frame.setSize(800, 600);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
    frame.setVisible(true);
    
    
    
     // This is where i did the action listener
     wordBtn.addActionListener(new ActionListener(){
    
    public void actionPerformed(ActionEvent ae)
    
    {
    flag=1;
    }
    
    } );
    
     enter.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent ae)
    {
    
    JFrame f=new JFrame();
    if( ae.getSource().equals(enter) )
        {
          if(flag==1) 
           {
              flag=0;
       if(tb.getText().equals("cat")){
                 tb.setText("Correct");
           }
       }
          else
              JOptionPane.showMessageDialog(f,"enter cat 1st");
    }
    
    }
    });
    
    
    }
    
    
    public static void main(String[] args) {
    new TestingCat();
    }
    }
    
  2. # 2 楼答案

    我不确定你到底想做什么,但我认为你的代码的这一部分不起作用

     enter.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent ae)
    {
    
    if( ae.getSource().equals(wordBtn) )
        {
        if(tb.getText().equals("cat")){
             tb.setText("Correct");
     }
    
    }
    
     }
    });
    

    您正在添加一个ActionListener来输入,然后检查是否单击了wordBtn。并不是说你内心的if语句永远不会运行

    这是一个我认为你正在尝试做的例子

    public class textb extends JPanel {
    
        int counter = 0;
    
        public textb() {
            JButton enter = new JButton("Enter");
            JButton wordBtn = new JButton("Cat");
    
            enter.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    counter++;
                }
            });
    
           wordBtn.addActionListener(new ActionListener() {
               if (counter > 0) {
                   //insert your code to check the String here, because the
                   //only way to increment counter is by pressing the enter button
                   //this code will not run unless enter has been pressed at least once
                   //to make counter greater than zero, you could also use a boolean
                   //set it to true when enter is pressed and check to see if its true
                   //instead of checking if counter is greater than zero
               }
           });
        }
    }
    
  3. # 3 楼答案

    下面是一个针对字符串测试输入并将输出附加到JTextArea的简单示例。它甚至使用了LayoutManager,这比null布局有用1000倍(至少)

    enter image description here

    public class Test {
        private static String ENTER = "Enter";
        static JButton enterButton;
        public static JTextArea output;
        public static JTextField input;
        static JFrame frame;
        static JPanel panel;
        public static String testString = "test";
    
        public static void main(String... args)
        {
            try
            {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception ex)
            {
                ex.printStackTrace();
            }
            createFrame();
        }
    
        public static void createFrame()
        {
            frame = new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            panel.setOpaque(true);
            ButtonListener buttonListener = new ButtonListener();
            output = new JTextArea(15, 50);
            output.setWrapStyleWord(true);
            output.setEditable(false);
            JScrollPane scroller = new JScrollPane(output);
            scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            JPanel inputpanel = new JPanel();
            inputpanel.setLayout(new FlowLayout());
            input = new JTextField(20);
            enterButton = new JButton("Enter");
            enterButton.setActionCommand(ENTER);
            enterButton.addActionListener(buttonListener);
            // enterButton.setEnabled(false);
            input.setActionCommand(ENTER);
            input.addActionListener(buttonListener);
            DefaultCaret caret = (DefaultCaret) output.getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
            panel.add(scroller);
            inputpanel.add(input);
            inputpanel.add(enterButton);
            panel.add(inputpanel);
            frame.getContentPane().add(BorderLayout.CENTER, panel);
            frame.pack();
            frame.setLocationByPlatform(true);
            // Center of screen
            // frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            frame.setResizable(false);
            input.requestFocus();
        }
    
        public static class ButtonListener implements ActionListener
        {
    
            public void actionPerformed(final ActionEvent ev)
            {
                Thread thread = new Thread()
                {
    
                    public void run()
                    {
                        if (!input.getText().trim().equals(""))
                        {
                            String cmd = ev.getActionCommand();
                            if (ENTER.equals(cmd))
                            {
                                output.append(input.getText());
                                if (input.getText().trim().equals(testString)) output.append(" = " + testString);
                                else output.append(" != " + testString);
                                output.append("\n");
                            }
                        }
                        input.setText("");
                        input.requestFocus();
                    }
                };
                thread.start();
            }
        }
    }