【问题标题】:Can you convert string.split array into JButtons您可以将 string.split 数组转换为 JButtons
【发布时间】:2016-04-02 17:01:24
【问题描述】:

我想制作它以便它可以制作按钮 例如,如果 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");

        }   
    });

【问题讨论】:

  • 您提供的 sn-p 究竟有什么问题?它是否因异常而失败?产生错误的结果?
  • 它只是说 jbutton[] 不能转换为 string[]
  • 你应该把board[i] = lineRead.split(" ");换成board[i] = new JButton(lineRead[i]);这一行

标签: java swing split jbutton


【解决方案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......
    }

【讨论】:

  • 您将使用 setText(),而不是 setName() 将“*”添加到按钮。
  • 是的,这很好,但要制作不同的按钮,我们还需要提供名称。因此我们可以使用该名称检索按钮。
  • 不,您不需要为按钮命名。在任何情况下,如果您为按钮提供相同的名称,这将不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 2014-04-26
  • 2011-07-12
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
相关资源
最近更新 更多