There is a class MyFrame, which describes the creation of a frame, and in this class the JPanel component is created.

And there is a Example class in which a Button is created, and then I want to add this Button to a JPanel. But an error pops up: the panel cannot be resolved. Where is the mistake?

class MyFrame extends JFrame { public MyFrame() { setSize(300, 400); setTitle("Example"); JPanel panel = new JPanel(); panel.setBackground(Color.green); add(panel); } } class Example { public Example() { JButton Button = new JButton("oooooo"); panel.add(Button); //в этой строке показывает ошибку } } 
  • And how MyFrame Example class need to know about the local variable panel in the MyFrame constructor? - VladD

2 answers 2

The panel in the class Example is obtained by a local variable that has not been created before. I see such options: either pass a reference to the panel in the Example constructor and call it from the constructor of the MyFrame class (you can also make the getPanel () method in the MyFrame class, which will return a link to the panel, the panel itself will have to be made an object field), or add buttons in the constructor of the class MyFrame. Another option is to make Example an internal class MyFrame, and panel to make a field of MyFrame object. Then, if I am not mistaken, from the inner class there will be access to the panel object. Correct me if I am wrong or I don’t know of any other way.

  • one
    It's easier for the panel to be declared as a public static field in MyFrame. - lightcyber
  • Oh, did not think about it, thank you. I'm used to making private fields. - Yuri_Prime
  • @lightcyber, and how to declare it within my classes? - roman_ya111
  • A public static JPanel panel will appear before the constructor, and instead of the constructor, JPanel panel = new JPanel (); will this.panel = new JPanel (); And to address so: MyFrame.panel - Yuri_Prime
  • Yuri_Prime, before which designer? I add errors popping up - roman_ya111

Try this:

 class MyFrame extends JFrame{ public static final JPanel panel; public MyFrame(){ setSize(300, 400); setTitle("Example"); panel = new JPanel() panel.setBackground(Color.green); add(panel); } } class Example{ public Example(){ JButton Button = new JButton("oooooo"); MyFrame.panel.add(Button); } }