I have a JFrame with a JPanel inside.
MyFrame class:
public class MyFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new MyPanel();
setContentPane(contentPane);
}
}
MyPanel class:
public class MyPanel extends JPanel {
private String myVariable = "abc";
public MyPanel() {
}
public String getMyVariable() {
return myVariable;
}
public void setMyVariable(String myVariable) {
this.myVariable = myVariable;
}
}
I created a class called MyPanel that extends JPanel and added a private field called MyVariable. The getters and setters functions were added to manipulate that field.
When I do contentPane = new MyPanel()
I can't do contentPane.getMyVariable()
.
What I'm missing here? Where it differs from creating for exemple a Car object and access their puclic methods? The image below shows what I'm trying to do.
The variable contentPane
in your class MyFrame
has the type JPanel
. But this class does not include the method getMyVariable()
you try to call.
You have multiple options to resolve the issue, for example:
MyPanel contentPane
.((MyPanel)contentPane).getMyVariable();