2016-04-02 3 views
1

ボタンを作成するようにしたい たとえば、txtファイルが:* * * * * * の場合は、スペースを削除します***** その後、このような何かを試してみてくださいstring.split配列をJButtonに変換できますか

独自のボタンに*
 //loads file and removes the spaces and stores it in an array 
     public static void loadFile(JButton[][] board, String fileName) throws IOException { 
     BufferedReader inputStream = null; 

    try { 
     inputStream = new BufferedReader(new FileReader(fileName)); 
     String lineRead = inputStream.readLine(); 
     while (lineRead != null) { 
      String[] splited = lineRead.split(" "); 
      for(int i = 0; i < board.length; i++){ 
       board[i] = lineRead.split(" "); 
      } 
    System.out.print(lineRead); 
     } 
      lineRead = inputStream.readLine(); 
    } 
    catch (FileNotFoundException exception) { 
     System.out.println("Error opening file"); 
    } 
    finally {  
     if (inputStream != null) 
      inputStream.close(); 
    } 
} 
//a button that opens the fileselector and then calls the loadfile method 
JButton file1 = new JButton("Player File"); 
    file1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) { 
     JFileChooser open = new JFileChooser(); 
     open.showOpenDialog(null); 
     loadFile(buttonPlayer, "CPU.txt"); 

     } 
    }); 
+2

あなたが提供するスニペットの問題は、正確には何ですか?それは例外で失敗しますか?間違った結果を生む? – Mureinik

+0

jbutton []は文字列に変換できません。 – kina

+0

この行の 'board [i] = new JButton(lineRead [i])]行を' board [i] = lineRead.split( ""); ' ); ' – guleryuz

答えて

1

をそれぞれを置く: -

JButton jButton; 
    String yourText=" * * * * * "; 
    String btnNames[]=yourText.split(" "); 
    System.out.println(yourText); 
    for(String btnName:btnNames){ 
     System.out.print(btnName); 
     jButton=new JButton(); 
     jButton.setName(btnName.trim()); 

     // ......you can put your other stuff here...... 
    } 
+0

setName()ではなくsetText()を使用して、ボタンに「*」を追加します。 – camickr

+0

はい、それは良いですが、私たちも名前を与える必要が別のボタンを作る。その名前を使用してボタンを取得できます。 –

+0

いいえ、ボタンに名前を付ける必要はありません。いずれにしても、ボタンに同じ名前を付けると、これは機能しません。 – camickr

関連する問題