Reputation: 35
In my question, this is Refectoring Class
. In this class, i'm using JPanel
for adding button by a separate Method panel()
and Call in the RefectClass
Constactor.
public class RefectClass extends JFrame {
JButton btnHome,btnBack;
JPanel btnContainer;
public RefectClass(){
super("Title Here");
setSize(350,300);
add(this.panel(),BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void panel(){
btnContainer=new JPanel();
btnHome=new JButton("Home");
btnBack=new JButton("Back");
btnContainer.add(btnHome);
btnContainer.add(btnBack);
}
}
Now how to add panel to JFrame? it gives an error, when i try to use it. I'm unable use to the panel()
Mehtod.
Upvotes: 1
Views: 115
Reputation: 3899
Your panel() method returns void - it should return your newly created JPanel instead such that you can add it to the JFrame:
public JPanel panel(){
btnContainer=new JPanel();
btnHome=new JButton("Home");
btnBack=new JButton("Back");
btnContainer.add(btnHome);
btnContainer.add(btnBack);
return btnContainer;
}
Let me point out, though, that this is a very unusual approach. You shouldn't have to initialize a member in a public method that returns the newly initialized member when the method is actually just needed inside the class. Imagine a client calling the panel method multiple times from outside (since it is public). BtnContainer, btnHOme and BtnBack would be overriden but they wouldn't appear on the screen.
The method seems fairy simply - why not just include it directly in your constructor?
Or at least make the method private
.
Upvotes: 2
Reputation: 8718
Your panel() method doesn't return anything so you can't write
add(this.panel(),BorderLayout.CENTER);
try
this.panel();
add(this.btnContainer,BorderLayout.CENTER);
Upvotes: 1