簡體   English   中英

按下按鈕后,檢查文本框中的文本是否與字符串匹配

[英]Checking if text in a textbox matches a string once a button has been pressed

我想創建一個程序,用戶按下按鈕並在文本框中輸入一個單詞,一旦他們輸入文本,他們必須按下回車按鈕,他們輸入的單詞將與另一個字符串進行核對。 我可以讓它檢查他們輸入的字符串,但我不知道我會怎么做,所以用戶必須先選擇一個按鈕,然后輸入文本,然后按enter按鈕。

將有多個按鈕,用戶可以選擇,他們將打開圖像,用戶需要在文本框中寫下這些圖像的內容,以檢查單詞是否正確,他們將按另一個按鈕進行檢查。

例如,四個按鈕上有圖片bag cat house lamp post ,用戶選擇一個按鈕,然后需要使用文本框拼寫單詞,然后按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();
}
}

下面是一個測試輸入字符串並將輸出附加到JTextArea的簡單示例。 它甚至使用LayoutManager ,你會發現1000次(至少)比null布局更有用。

在此輸入圖像描述

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

我不確定你要做的是什么,但我不認為你的代碼的這部分會起作用......

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

一個簡單的flag變量應該工作:

在此輸入圖像描述

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM