从文件中读取按钮名称

时间:2014-05-18 15:34:27

标签: java swing file jbutton

我有3个按钮,我需要通过从文件中读取来设置它们的名称。这就是我到目前为止所拥有的:

BufferedReader inputFile = new BufferedReader (new FileReader ("ButtonNames.txt"));       
    String buttonName = "";
    int startLine = 1;
    int endLine = 3;
    for (int i = startLine; i < endLine + 1; i++)
    {
        buttonName = inputFile.readLine();
    }
    Button1 = new JButton(buttonName);
    buttonPanel.add(Button1, BorderLayout.LINE_START);

这只会将按钮名称设置为文件的最后一行。如何将button1的名称设置为第一行,将button2设置为第二行等。我认为您需要使用数组,但我不知道如何实现它。

3 个答案:

答案 0 :(得分:2)

将该代码放在for循环的 的底部。

for (int i = startLine; i < endLine + 1; i++)
{
    buttonName = inputFile.readLine();
    Button1 = new JButton(buttonName);
    buttonPanel.add(Button1, BorderLayout.LINE_START);
}

答案 1 :(得分:1)

使用数组:

JButton[] buttons = new JButton[3];
for (int i = startLine; i < endLine + 1; i++)
{
    String buttonName = inputFile.readLine();
    buttons[i-1] = new JButton(buttonName);
    buttonPanel.add(buttons[i-1], BorderLayout.LINE_START);
}

答案 2 :(得分:0)

这也很有效:

public Main() {
    Panel p = new Panel();
    String[] names = Names("res/ButtonNames.txt");
    for(int i = 0; i < names.length; i++) {
        p.add(new Button(names[i]));
    }
    frame.add(p);
}

private String[] Names(String filepath) {
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(filepath)));
        String[] split = br.readLine().split(",");
        br.close();
        return split;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}