-1

I'm a beginner in java so sorry if the question seems a bit stupid

I have this simple code but I do not understand some of the coding.

I know that the keyword this refers to this class but i still dont understand exactly why is needed at that point .

For example :

public class SquareSimp
{


    public static void main( String[] args )
    {
        FilledFrame frame = new FilledFrame();

        frame.setVisible( true );
    }
}

class FilledFrame extends JFrame
{
    int size = 400;

    public FilledFrame()
    {
        JButton butSmall   = new JButton("Small");
        JButton butMedium  = new JButton("Medium");
        JButton butLarge   = new JButton("Large");
        JButton butMessage = new JButton("Say Hi!");

        SquarePanel panel = new SquarePanel(this); WHERE DOES (THIS) REFER TO 
                                                   AND WHY DO WE NEED IT?
        JPanel butPanel = new JPanel();

        butPanel.add(butSmall);
        butPanel.add(butMedium);
        butPanel.add(butLarge);
        butPanel.add(butMessage);
        add(butPanel, BorderLayout.NORTH);
        add(panel, BorderLayout.CENTER);

        setSize( size+100, size+100 );
    }

}

class SquarePanel extends JPanel
{
    FilledFrame theApp; // WHY DO WE CREATE A VARIABLE OF A TYPE CLASS? HERE?

    SquarePanel(FilledFrame app)
    {
        theApp = app;
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.green);
        g.fillRect(20, 20, theApp.size, theApp.size);
    }
}
Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
R AND B
  • 51
  • 2
  • 9
  • Somewhat unrelated to the question in itself, but considering @phflack's comment, it might be better to only pass the filled frame's size, instead of the whole object (**assuming the sample contains all of the SquarePanel's code**). – Prometheos II Oct 13 '19 at 11:58

2 Answers2

0

In FilledFrame constructor we want to create an instance of SquarePanel but the thing is SquarePanel constructor requires a FilledFrame instance, so, because we already were creating FilledFrame in the first place we can send the current FilledFrame instance which is under construction as input to SquarePanel constructor.

Hadi Moloodi
  • 639
  • 7
  • 12
0

WHERE DOES (THIS) REFER AND WHY DO WE NEED IT?

this represents the current instance of the class. In this example, JPanel's constructor needs an instance of the FilledFrame class; thus we pass that instance, which in this example is this (created in the main method).

WHY DO WE CREATE A VARIABLE OF A TYPE CLASS? HERE?

With your design, the SquarePanel class depends on the FilledFrame class, so we have to inject a FilledFrame instance. In your case, you pass it in argument to your SquarePanel constructor.

i think this is bad design anyway

Community
  • 1
  • 1
hossein rasekhi
  • 209
  • 1
  • 13