Java:在add方法中创建对象的副本?
在java中,使用add命令创建您添加的对象的副本时是否可能 我得到了这个物体:Java:在add方法中创建对象的副本?,java,object,copy,Java,Object,Copy,在java中,使用add命令创建您添加的对象的副本时是否可能 我得到了这个物体: JLabel seperator = new JLabel (EMPTY_LABEL_TEXT); 我补充说: add (seperator,WEST); 如果我想添加几个这种类型的对象,我想我必须复制它们,在add()方法中有没有这样做的方法,如果没有,创建对象副本的最简单方法是什么?我只需要3个,所以我不想要任何循环 JLabel separator2 = new JLabel(EMPTY_LABEL_
JLabel seperator = new JLabel (EMPTY_LABEL_TEXT);
我补充说:
add (seperator,WEST);
如果我想添加几个这种类型的对象,我想我必须复制它们,在add()方法中有没有这样做的方法,如果没有,创建对象副本的最简单方法是什么?我只需要3个,所以我不想要任何循环
JLabel separator2 = new JLabel(EMPTY_LABEL_TEXT);
JLabel separator3 = new JLabel(EMPTY_LABEL_TEXT);
这是你能做的最好的了。如果要在两个副本上都具有标签的许多不同属性,请使用方法创建三个标签,以避免将同一代码重复三次:
JLabel separator = createLabelWithLotsOfProperties();
JLabel separator2 = createLabelWithLotsOfProperties();
JLabel separator3 = createLabelWithLotsOfProperties();
我认为Swing组件通常不实现
Cloneable
接口,所以您必须自己制作一个副本,或者定义自己的MySeparator
类,您将与add(new MySeparator())一起使用代码>不直接在add()方法中,无需任何帮助。
Swing组件是可序列化的,因此编写使用ObjectOutputStream和ObjectInputStream复制组件的帮助器方法应该相当容易
编辑:一个快速示例:
public static JComponent cloneComponent(JComponent component) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bos);
oout.writeObject(component);
oout.flush();
ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
return (JComponent) oin.readObject();
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
JLabel label1 = new JLabel("Label 1");
JLabel label2 = (JLabel) cloneComponent(label1);
label2.setText("Label 2");
System.out.println(label1.getText());
System.out.println(label2.getText());
}
我添加了一个如何使用Swing的序列化特性克隆JComponent的快速示例。