Reputation: 445
I wrote class which contain simple JFrame and I want to add button from other class to this JFrame
When I'm trying to write
panel.add(new CancelButton())
I got an error: LoginWindow.java:29: error: no suitable method found for add(CancelButton)
Can you help me with it?
import javax.swing.*;
import java.awt.*;
public class LoginWindow {
public LoginWindow(){
//Login Window
JFrame frame = new JFrame("Movie date base");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//label
JLabel label = new JLabel("Welcom to Movie Date Base! ");
label.setFont(new Font("Verdana", Font.PLAIN, 18));
//panel
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel1 = new JPanel(new GridBagLayout());
//add panel to the frame
frame.add(panel);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(panel1, BorderLayout.SOUTH);
//Grid layout
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(100,10,10,10);
panel.add(label,c);
}
}
import javax.swing.*;
public class CancelButton {
public CancelButton(){
JButton cancel = new JButton("cancel");
}
}
Upvotes: 2
Views: 1030
Reputation: 1
If you'd like to keep it like it is, put the button into an array, and in the jframe, instantiate the cancel class and call from the array.
Upvotes: 0
Reputation: 42176
If you want to treat your CancelButton class as a JButton, then it has to extend JButton.
public class CancelButton extends JButton{
public CancelButton(){
//call the parent-level constructor
super("cancel");
}
}
Note that I've gotten rid of your cancel variable here, since your CancelButton class is-a JButton now. You can use it anywhere you can use a JButton.
However, if instead you want to use the cancel variable in other classes, then you need to create some kind of getter function for it:
public class CancelButton {
JButton cancel;
public CancelButton(){
cancel = new JButton("cancel");
}
public JButton getButton(){
return cancel;
}
}
Then you would call that getButton() function, like this:
panel.add(new CancelButton().getButton())
Which approach you take really depends on exactly what you're trying to do, and how you want to organize your code.
Upvotes: 5