1

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

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

如何检查单个字符是否出现在字符串中?

问题是我如何让这两个代码一起工作,我尝试过融合它们,但是我得到了 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();
        }
    });
}
}
4

1 回答 1

0

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

于 2012-08-26T16:43:50.080 回答