我试图根据.txt文件中的内容添加JComponent 例如
在Component.txt
中"[button]
buttonName
buttonText
Location(x,y)"
那么如何创建一个名为buttonName的JButton,在x&位置使用buttonText文本ÿ
这是我的代码:
private void btnRetrieveActionPerformed(java.awt.event.ActionEvent evt) {
String filename=txtFilename.getText()+".txt";
int x=1;
String text=null;
String bname=new String(),btxt;
double bsizex,bsizey,blocx,blocy;
try (BufferedReader fw = new BufferedReader(new FileReader(new File(filename))))
{
String s;
while((s = fw.readLine()) != null)
{
if(s.equals("[button]"))
{
String btnName = fw.readLine(); //read the next line after [a]
JButton button1=new JButton(btnName);
this.add(button1);
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
答案 0 :(得分:2)
您需要阅读预期标记之后的每一行,直到您阅读了所期望的所有内容。
获得所有有效信息后,您需要解析结果并构建按钮,例如......
try (BufferedReader fw = new BufferedReader(new FileReader(new File(filename)))) {
String s = null;
while((s = fw.readLine()) != null) {
if(s.equals("[button]")) {
String btnName = fw.readLine();
if (btnName != null) {
String btnText = fw.readLine();
if (btnText != null) {
String location = fw.readLine();
if (location != null) {
JButton button1=new JButton(btnText);
button1.setName(btnName);
//String xPos = location.substring(location.indexOf("(") + 1);
//String yPos = xPos.substring(xPos.indexOf(",") + 1);
//yPos = yPos.substring(0, yPos.indexOf(")"));
//xPos = xPos.substring(0, xPos.indexOf(","));
String parts[] = location.split(" ");
int x = Integer.parseInt(parts[0]);
int y = Integer.parseInt(parts[1]);
// Add this is where I tell you to use a layout manager...
this.add(button1);
}
} else {
break;
}
} else {
break;
}
}
}
}catch(IOException e) {
e.printStackTrace();
}
坦率地说,这种事情更适合XML