java在按下按钮后检查文本框中的文本是否与字符串匹配
我想创建一个程序,用户按下一个按钮,必须在文本框中输入一个单词,一旦他们输入了文本,他们必须按下enter按钮,他们输入的单词将根据另一个字符串进行检查。我可以让它检查他们输入的字符串,但我不确定如何操作,因此用户必须先选择一个按钮,然后输入文本,然后按enter按钮
将有多个按钮供用户选择,这些按钮将显示图像,用户需要在文本框中写入这些图像,以检查单词是否正确。他们将按下另一个按钮进行检查
例如,在bag
{
谢谢
以下是我尝试过的:
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();
}
}
# 1 楼答案
一个简单的
flag
变量应该可以工作:# 2 楼答案
我不确定你到底想做什么,但我认为你的代码的这一部分不起作用
您正在添加一个
ActionListener
来输入,然后检查是否单击了wordBtn。并不是说你内心的if语句永远不会运行这是一个我认为你正在尝试做的例子
# 3 楼答案
下面是一个针对字符串测试输入并将输出附加到
JTextArea
的简单示例。它甚至使用了LayoutManager
,这比null
布局有用1000倍(至少)