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