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

时间:2013-04-14 18:20:05

标签: java swing jbutton actionlistener

我想创建一个程序,其中用户按下按钮并且必须在文本框中输入单词,一旦他们输入文本,他们必须按下回车按钮,他们输入的单词将被检查对另一个串。我可以让它检查他们输入的字符串,但我不知道我会怎么做,所以用户必须先选择一个按钮,然后输入文本然后按回车键。

用户可以选择多个按钮,他们将打开图像,用户需要在文本框中写下这些图像的内容,以检查单词是否正确,按下另一个按钮检查。

例如,bag cat house lamp post上有图片的四个按钮,用户选择一个按钮,然后他们需要使用文本框来拼写单词并按下输入以检查文本框中的文本是否与某个字符串匹配。

由于

以下是我的尝试:

 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 个答案:

答案 0 :(得分:2)

以下是针对字符串测试输入并将输出附加到JTextArea的简单示例。它甚至使用LayoutManager,你会发现 1000 次(至少)比null布局更有用。

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

答案 1 :(得分:1)

我不确定你要做的是什么,但我不认为你的代码中的这部分会起作用......

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

答案 2 :(得分: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();
}
}