gpt4 book ai didi

java - 查找单词中的字符。字符是单击的按钮

转载 作者:行者123 更新时间:2023-12-01 05:10:10 24 4
gpt4 key购买 nike

来自 stackoverflow 的人帮助我编写了按钮代码,为我提供了更合适的正确代码...但问题是我想在 Hangman 程序中使用此代码,当有人单击按钮时它必须扫描一个单词并打印“是,该字母在该单词中”或“否,该字母不在该单词中”

我在 stackoverflow 中遇到了一些可以做到这一点的代码,但我不知道如何使该人的代码适应我的按钮代码

创建按钮的代码(据我所知):

public CharSearch(){

super(BoxLayout.Y_AXIS);
for(char i = 'A'; i <= 'Z'; i++){
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
add(button);
}
}

public JButton getButton(final String text){
final JButton button = new JButton(text);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have clicked: "+text);
//If you want to do something with the button:
button.setText("Clicked"); // (can access button because it's marked as final)
}
});
return button

然后是我找到的代码(我也会发布链接):

if(original.indexOf(button)!=-1){
JOptionPane.showConfirmDialog(panel, "Your word does contain" + button );
}
else{
JOptionPane.showConfirmDialog(panel, "There is no" + button );
}

How can I check if a single character appears in a string?

问题是如何使这两个代码一起工作,我尝试将它们融合,但随后我在

处的 indexOf 处出现错误
if(original.indexOf(button)!=-1){

我还将发布我的完整代码:

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

public final class CharSearch extends Box{
int i =0;
int error = 0;
static JPanel panel;
String original = "Dinosaur";
JLabel label = new JLabel();
String secret = new String(new char[original.length()]).replace('\0', '-');

public CharSearch(){

super(BoxLayout.Y_AXIS);
for(char i = 'A'; i <= 'Z'; i++){
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
add(button);
}
}

public JButton getButton(final String text){
final JButton button = new JButton(text);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have clicked: "+text);
//If you want to do something with the button:
button.setText("Clicked"); // (can access button because it's marked as final)
}
});
return button;

if(original.indexOf(button)!=-1){
JOptionPane.showConfirmDialog(panel, "Your word does contain" + button );
}
else{
JOptionPane.showConfirmDialog(panel, "There is no" + button );
}

}

public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame frame=new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(new CharSearch());
frame.pack();
frame.setVisible(true);
new CharSearch();
}
});
}
}

最佳答案

将按钮更改为button.getText()(假设按钮的文本就像b或c),或者可能是getName,如果您将它们全部按其字符命名(这可能会更好,因为它允许您使用不同的名称)按钮显示的文本内容,例如按钮可以是“选择 c”,但名称为“c”,并且它仍然有效)

关于java - 查找单词中的字符。字符是单击的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com