你能将string.split数组转换成JButtons吗?

时间:2016-04-02 17:01:25

标签: java swing split jbutton

我想制作它以便制作按钮 例如,如果txt文件是:* * * * * * 它将删除空格***** 然后将每个*放入自己的按钮

        //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");

        }   
    });

1 个答案:

答案 0 :(得分: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......
    }