我有一个项目处理三个使用jbuttons填充的面板。 jbuttons是从一个for循环创建的,我懒得重新创建一个jpanel填充了jbuttons的类,因为它与我的actionlisteners冲突。 可以说我有每个三块板填入代码:确定从for循环创建的数组中的对象
JPanel panel109 = new JPanel(); //113, 115 for the other two
roomPanel.add(panel109);
for(int j = 0; j < 6*28; j++) {
btn[j] = new JButton();
btn[j].setName("a" + j);
btn[j].setBackground(Color.white);
btn[j].setText("");
btn[j].setPreferredSize(new Dimension(35,9));
btn[j].addActionListener(this);
panel109.add(btn[j]);
}
对于每个面板,如何识别每个BTN []创造的呢?我想在用户指定数据以更改按钮颜色,工具提示文本等之后序列化每个按钮。我几乎只想知道如何访问我创建的按钮,因为三个面板使用相同的循环。 所有按钮的序列化来自“存储”按钮,然后“恢复”如果我想从它创建的文件恢复。
店内码:
JButton btnStore = new JButton("Store");
btnStore.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream (new FileOutputStream("myFile"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
for (int i=0;i<6*28;i++){
//deregister
btn[i].removeActionListener(this);//Heres my problem,
//serialize //I Don't know how to access
try { //the buttons created from the
out.writeObject(btn[i]); //three loops.
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
//register
btn[i].addActionListener(this);
}
}
});
首先你应该http://stackoverflow.com/mcve你的例子,第二如果你使用单选按钮,然后使用JRadioButton()...你也可以使用https://docs.oracle.com/javase /tutorial/uiswing/examples/components/index.html#ListDialog作为一个开始的例子,因为你正在挑选整个按钮主机 –
哎呀,我搞砸了什么类型的按钮 – kfloresmx5
@ kfloresmx5你正在访问'JButton [] btn'在ActionListener里面,我们猜它是一个类成员(还是一个“final”局部变量)?除非为每个容器创建一个新数组,否则不能将同一对象添加到多个容器('JPanel')。这些变量的范围很重要,特别是当你想要将它们检索到别处时... – Matthieu