2013-10-11 13 views
0

我遇到了一個小問題,佔用了我幾個小時。播放器輸入JFrame

我希望玩家在遊戲中進行輸入,然後我將進一步使用。但我不知道該怎麼做...

試過JOptionPaneJTextFieldScannerScanner工作,但我希望它無需使用控制檯:我

所以,這裏是我的代碼:

窗口:

package Main; 

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class Window 
{ 
    public static JFrame frame = new JFrame("Z-Stories"); 
    public static JLabel Label = new JLabel ("<html></html>", JLabel.CENTER); 
    public static String LabelText; 

    public Window() 
    { 
     Label.setVerticalAlignment(JLabel.TOP); 
     frame.setSize(1920, 1080); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(Label, BorderLayout.CENTER); 
     frame.setIconImage(new ImageIcon(getImage()).getImage()); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    protected static Image getImage() 
    { 
     java.net.URL imgURL = Window.class.getResource("Logo32.png"); 

     if (imgURL != null) 
     { 
      return new ImageIcon(imgURL).getImage(); 
     } else 
     { 
      return null; 
     } 
    } 

    public static void addText(String Text) 
    { 
     LabelText = Label.getText(); 
     LabelText = LabelText.replace("</html>", ""); 
     if(Text != null) 
     { 
      Label.setText(LabelText + "<br/>" + Text + "</html>"); 
     }else 
     { 
      Label.setText(LabelText + "<br/><br/></html>"); 
     } 
     System.out.println(Label.getText()); 
     Label.validate(); 
    } 

    public static int InputInt() 
    { 
     //User Input here 
     //Maybe parse into Int 
     return output; 
    } 

    public static String InputText() 
    { 
     //User Input here 
     //Maybe convert to String 
     return outputText; 
    } 
} 

而且Game.java

... 
     public void StartGame() 
     { 
      ErstesSpiel = 1; 
      Window.addText("Wähle deine Sprache | Select your language"); 
      Window.addText(""); 
      Window.addText("Deutsch (1) | English (2)"); 
      Window.addText(""); 
      int var3 = Window.InputInt(); 
      Window.addText(""); 
    .... 
+0

你需要的是一個keyboardeventlistener。見http://www.edu4java.com/en/game/game4.html – hamon

+0

Doenst的工作...我想要的東西像scanner.nextInt()可以用於控制檯,但對於JFrame ... – Zweistein2

回答

0

您可以使用JTextField並在用戶通過使用actionlistener或JButton click按下輸入時獲取輸入

創建該對象

JTextField UserInputField = new JTextField(""); 

調用此方法時,用戶按下與動作偵聽器(more on Action Listeners

public static int InputInt() 
{ 
    String sInput = UserInputField.getText(); //Gets the string from the JTextField 

    int output = Integer.parseInt(sInput.trim()); //Parse string to int 

    return output; //Return as int 
} 

進入。如果你想要的是對的方法來自動運行,只要用戶輸入數字,你可以使用鍵盤監聽器 http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html