Hi I am trying to add an object for example a JLabel from a main class to a secondary class that inherits the attributes of a JPanel.I have created a basic example that shows what I was trying to do but it dosen't work.Here is my code:
您好我正在尝试将一个对象(例如JLabel)从主类添加到继承JPanel属性的辅助类。我创建了一个基本示例,显示了我尝试做的但是它不起作用。这里。这里是我的代码:
public class main extends JFrame{
public main(){
this.setVisible(true);
this.setSize(600, 600);
panel nou = new panel(new JLabel("a mers"));
}
public static void main (String[] args){
new main();
}
}
public class panel extends JPanel{
public panel(JLabel nou){
this.add(nou);
}
}
My original code has to add some images from an external class and I tried the same aproach but it dosen't work.How can I achive this?
我的原始代码必须添加一些来自外部类的图像,我尝试了同样的方法,但它不起作用。我怎么能得到这个?
EDIT:This is just an example I need to add this component from an external class
编辑:这只是我需要从外部类添加此组件的示例
2 个解决方案
#1
1
Use Container#add(Component). You can use it the same way within the constructor as you can outside of it (without the this).
使用Container#add(Component)。你可以在构造函数中以相同的方式使用它,就像在它之外一样(没有这个)。
nou.add(new JLabel("trees"));
#2
1
You are making the JPanel
instance, but not adding to the JFrame
.
您正在创建JPanel实例,但不添加到JFrame。
Also please use the convention of Capital Camel Case for class names.
另请使用Capital Camel Case的惯例作为类名。
#1
1
Use Container#add(Component). You can use it the same way within the constructor as you can outside of it (without the this).
使用Container#add(Component)。你可以在构造函数中以相同的方式使用它,就像在它之外一样(没有这个)。
nou.add(new JLabel("trees"));
#2
1
You are making the JPanel
instance, but not adding to the JFrame
.
您正在创建JPanel实例,但不添加到JFrame。
Also please use the convention of Capital Camel Case for class names.
另请使用Capital Camel Case的惯例作为类名。