I have a program in which a JPanel is added to a JFrame:
public class Test{
Test2 test = new Test2();
JFrame frame = new JFrame();
Test(){
...
frame.setLayout(new BorderLayout());
frame.add(test, BorderLayout.CENTER);
...
}
//main
...
}
public class Test2{
JPanel test2 = new JPanel();
Test2(){
...
}
}
I get an error asking me to change type of 'panel' to 'component'. I do I fix this error?
It wants me to do: Component panel = new Component();
public class Test{
Test2 test = new Test2();
JFrame frame = new JFrame();
Test(){
...
frame.setLayout(new BorderLayout());
frame.add(test, BorderLayout.CENTER);
...
}
//main
...
}
//public class Test2{
public class Test2 extends JPanel {
//JPanel test2 = new JPanel();
Test2(){
...
}
do it simply
public class Test{
public Test(){
design();
}//end Test()
public void design(){
JFame f = new JFrame();
f.setSize(int w, int h);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
JPanel p = new JPanel();
f.getContentPane().add(p);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
new Test();
}catch(Exception e){
e.printStackTrace();
}
}
);
}
}
Instead of having your Test2 class contain a JPanel, you should have it subclass JPanel:
public class Test2 extends JPanel {
Test2(){
...
}
More details:
JPanel is a subclass of Component, so any method that takes a Component as an argument can also take a JPanel as an argument.
Older versions didn't let you add directly to a JFrame; you had to use JFrame.getContentPane().add(Component). If you're using an older version, this might also be an issue. Newer versions of Java do let you call JFrame.add(Component) directly.
Test2 test = new Test2();
...
frame.add(test, BorderLayout.CENTER);
Are you sure of this? test
is NOT a component!
To do what you're trying to do you should let Test2
extend JPanel
!
Your Test2
class is not a Component
, it has a Component
which is a difference.
Either you do something like
frame.add(test.getPanel() );
after you introduced a getter for the panel in your class, or you make sure your Test2
class becomes a Component
(e.g. by extending a JPanel
)