我试图插入我的代码到我的GUI此刻我无法找到一种方法来调用ActionListener中的文本与打破我的代码我知道有一些findAndReplace()我会需要努力让它在我的GUI中工作......但目前我只是想要说明ActionListener。在ActionListener中调用
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.*;
public class HangmanPanel extends JPanel {
static Boolean FOUND;
private static final long serialVersionUID = -5793357804828609325L;
public static String answerKey() {
//get random array element
String array[] = new String[10];
array[0] = "hamlet";
array[1] = "mysts of avalon";
array[2] = "the iliad";
array[3] = "tales from edger allan poe";
array[4] = "the children of hurin";
array[5] = "the red badge of courage";
array[6] = "of mice and men";
array[7] = "utopia";
array[8] = "chariots of the gods";
array[9] = "a brief history of time";
ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
Collections.shuffle(list);
String s = list.get(0);
return s;
}
public StringBuilder dashReplace(String s) {
//replace non-white space char with dashes and creates StringBuilder Object
String tW = s.replaceAll("\\S", "-");
System.out.print(tW + "\n");
StringBuilder AnswerKey = new StringBuilder(tW);
return AnswerKey;
}
public HangmanPanel(){
this.setLayout(null);
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//get input
Button.addActionListener(new input());
JLabel tfLable = new JLabel("Please Enter a Letter:");
JLabel AnswerKey = new JLabel(dashReplace(answerKey()).toString());
JTextField text = new JTextField(10);
heading.setSize(200, 50);
tfLable.setSize(150, 50);
text.setSize(50, 30);
Button.setSize(60, 20);
AnswerKey.setSize(200, 100);
heading.setLocation(300, 10);
tfLable.setLocation(50, 40);
text.setLocation(50, 80);
Button.setLocation(100, 85);
AnswerKey.setLocation(100,85);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
this.add(AnswerKey);
}
public class input implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// can't access text
sc = text.getText();
char ch = sc.charAt(0);
findAndReplace(s, AnswerKey, input, ch);
}
}
public static int findAndReplace(String s, StringBuilder AnswerKey, String sc,
char ch) {
//find position of user input and replace
int pos = -1;
FOUND = false;
while(true){
pos = s.indexOf(sc, pos+1);
if(pos < 0){
break;
}else{
FOUND = true;
AnswerKey.setCharAt(pos, ch);
}
}
System.out.println(AnswerKey);
return pos;
}
}
1)请学会共同[:
马克
text
才能访问它在匿名类变量,最终Java命名约定](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307)(具体用于名称的情况),用于类,方法和属性名称&一致地使用它们。 2)Java GUI可能需要在多种平台上工作,使用不同的屏幕分辨率并使用不同的PLAF。因此,它们不利于组件的准确放置。对于可靠的GUI,改为使用布局管理或它们的组合,以及用于空白的布局填充和边框来组织组件。 3)一行空格就足够了。 – 2013-05-09 13:36:29