I'm trying to create a hangman game where dashes will display for the user and if they click on the correct button, a letter will replace the dashes. This worked when I was using the console to output all the data, but after I changed to GUI, it wouldn't work no matter what I tried. It seems that the JTextField won't accept a character array.
private static JTextField txtDashes;
static char [] dashes = {'-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'};
txtDashes = new JTextField();
txtDashes.setBackground(Color.GRAY);
txtDashes.setHorizontalAlignment(SwingConstants.CENTER);
txtDashes.setBorder(javax.swing.BorderFactory.createEmptyBorder());
txtDashes.setBounds(39, 207, 218, 46);
gameScreen.add(txtDashes);
txtDashes.setColumns(10);
for (int i = 0; i < dashes.length; i++){
txtDashes.setText(dashes[i]); //Error occurs here
} //End of for loop
I'm only experienced in about 5 months of java coding and can't seem to find a solution for this problem.
you should pass a String
to setText()
method dashes is a char
array.you can't set a char to a textfield .you have to convert char to String first
use
txtDashes.setText(String.valueOf(dashes[i]));
or
txtDashes.setText(dashes[i] + "");
edit
setText()
replace exiting text and set new text.if you want to show all array chars, first append it to a string throw a loop and from outside of loop setText()
like this
String s="";
for (int i = 0; i < dashes.length; i++){
s+=dashes[i];
}
txtDashes.setText(s);
note .string append inside a loop is not good you can use StringBuilder
for that
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments