我希望从其他类接收初始化对象而不创建此对象new或使用static。这可能吗?
我试着在飞行中做一个例子,不知道它是否有效:
package.display
public class Display extends JFrame{
public Display(){
initUI();
}
public void initUI(){
// initialize panel1
Panel1 panel1 = new Panel1();
// setting window adding panel1
this.setSize(400,400);
this.add(panel1);
this.setVisible(true);
}
public static void main(String[] args){
new Display();
}
}
package.panle1
public class Panel1 extends JPanel{
Canvas canvas;
public Display(){
initUI();
}
public void initUI(){
// initialize canvas and panel2
canvas = new Canvas();
canvas.setSize(new Dimension(200, 200);
Panel2 panel2 = new Panel2();
// adding canvas and panel2
this.add(canvas, BorderLayout.North);
this.add(panle2, BorderLayout.South);
}
public Canvas getCanvas(){
return canvas;
}
}
package.panle2
public class Panel2 extends JPanel{
public Display(){
initUI();
}
public void initUI(){
// just 1 button
JButton btn1 = new JButton();
btn1.addActionListener(new ActionListener() {
// create new JPanel and center on canvas
public void actionPerformed(ActionEvent arg0){
JPanel canvasPanel = new JPanel();
canvasPanel.setSize(100,100);
canvasPanel.setLocationRelativeTo(
// and here is my PROBLEM
// how i get this panel1 canvas object without creating new ?
// getter getCanvas() dont work with existing object instance
// i want exactly the object which is created when its called
// from display and not the way i have to make new Panel1
});
this.add(btn1);
}
}
(我的问题在代码的最后部分中描述)
我知道的唯一解决方案是静态的,并且工作正常。这个单词 静态非常好我会在整个地方使用它,因为它非常方便 访问所有人。 随着反射,我不知道。我只看到了一个例子,你必须创建一个对象的新实例,并且我想要它。
很快我想要进行3D编程并从OpenGL开始。在那里我读到你必须随身携带物品,不能像lwgl一样使用静态这个词。
这就是为什么我问这个问题,看看我有哪些可能解决这样的问题。我希望任何人都可以提供帮助和thx。
答案 0 :(得分:0)
另一种方法是创建 Panel1 的final
实例,这样您就可以在班级的任何地方访问该对象的getCanvas()
方法内部类:
public class Panel2 extends JPanel{
final Panel1 panel1=new Panel1();
public Display(){
initUI();
}
public void initUI(){
// just 1 button
JButton btn1 = new JButton();
btn1.addActionListener(new ActionListener() {
// create new JPanel and center on canvas
public void actionPerformed(ActionEvent arg0){
JPanel canvasPanel = new JPanel();
canvasPanel.setSize(100,100);
canvasPanel.setLocationRelativeTo(
// and here you have access to the canvas of panel1
});
this.add(btn1);
}
}