所以我需要做的是使用 JTextField 以字符串的形式获取用户输入,虽然我可以做这部分,但我无法从方法中获取字符串以在程序的其他地方进行分析,这就是我到目前为止:
import javax.swing.* ;
import java.awt.event.* ;
import java.util.* ;
class Games extends JFrame implements ActionListener
{
JPanel pnl = new JPanel() ;
JTextField input = new JTextField(38) ;
JTextArea output = new JTextArea(6, 37) ;
JScrollPane pane = new JScrollPane(output) ;
String inputString ;
public Games()
{
super("Text Based RPG") ;
setSize(600,200) ;
setDefaultCloseOperation(EXIT_ON_CLOSE) ;
output.setLineWrap(true) ;
output.setWrapStyleWord(true) ;
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) ;
output.setEditable(false) ;
pane.getVerticalScrollBar().setValue(100); //scrollbar always at bottom
input.requestFocus() ;
/*Edit: Should I call for the input string here, e.g. output.append(inputString)
i get the compilation error message:
Games.java:29: error: cannot find symbol
output.append(inputString) ;
^
symbol: variable inputString
location: class Games
*/
add(pnl) ;
pnl.add(pane) ;
pnl.add(input) ;
input.addActionListener(this) ;
setVisible(true) ;
}
public void actionPerformed(ActionEvent event)
{
inputString = input.getText() ;
input.setText("") ;
}
/*The string i need to analyse is inputString, but I cannot, get it out of this method
any help you guys can give me would be greatly appreciated. */
public static void main(String[] args)
{
Games gui = new Games() ;
}
}
**********************************
try
{
a = reader.readLine() ;
}
catch (IOException e )
{
System.out.println("An Input Error Has Occured") ;
}
if (a.indexOf("hide") != -1 ) switchvariable = 'b' ;
if ((a.indexOf("exit") != -1 ) || (a.indexOf("leave") != -1) || (a.indexOf("out") != -1)) switchvariable = 'a' ;
if ((a.indexOf("exit") == -1) && (a.indexOf("hide") == -1) && (a.indexOf("leave") == -1) && (a.indexOf("out") == -1)) switchvariable= 'c' ;
String outcome = "" ;
switch (switchvariable)
{
case 'a' : outcome = "You exit the tavern to be discovered by\na group of bandits!\n" ; i = -1 ; break ;
case 'b' : outcome = "You hide behind the bar for 10 minutes until\nyou can no longer hear the group." ; i = -1 ; break ;
case 'c' : outcome = "You must choose between the two given options, exit the tavern, or hide." ; break ; // the variable i will still be greater
//than 1 so the loop will continue until you reach an agreeable option, which in this case is either hiding, or addressing the group of people
}
System.out.println(outcome) ;
理想情况下我想做的是使用文本字段进行用户输入,所以我需要做的是将文本放在输出文本区域中,然后这应该根据用户输入进行更改,我想使用的代码示例显示在星号下方