Java - Swing is a value in JOptionPane

Consider the following example:

import javax.swing.*;
import java.awt.event.*;

public class JavaWindow extends JFrame {

JButton button1;

public static void main(String[]args)
{
     new JavaWindow();
     // or JavaWindow Mwindow = new JavaWindow(); Question 1

}

public JavaWindow()
{   //setting window parameters etc. 
    this.setSize(500,500);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("My window");
      JPanel thePanel = new JPanel();
      button1 = new JButton("Get answer");
      ListenForButton lForButton = new ListenForButton();
      button1.addActionListener(lForButton);
      thePanel.add(button1);
      this.add(thePanel);
      this.setVisible(true);



}

private class ListenForButton implements ActionListener
{

    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==button1)
        {
        JOptionPane.showMessageDialog(JavaWindow.this, "Hello!"); //JavaWindow.this - Question 2
        }
    }

}

}

Question 1: In most examples on the Internet, an object is created, which should be, the window is made in this way "new JavaWindow ();" but right? equal to creating an object and naming it at the same time when we create / create it, but replace "new JavaWindow ()"; for example, "JavaWindow MyWindow = new JavaWindow ();"

2. : "JOptionPane.showMessageDialog(JavaWindow.this," Hello! ");". JavaWindow.this parentComponent. parentComponent: A) button1 - , ( , ), B) ( ) ListenForButton, /, actionPerformed, ( ) lForButton ( , ), C) , - (: new JavaWindow()); ( ), D) ???

+4
3

1:

new JavaWindow(); JavaWindow javaWindow = new JavaWindow(); , JavaWindow , . , . , new JavaWindow().methodName(), , , , JavaWindow.

, , , new JavaWindow().

2:

parentComponent - , JOptionPanel. JFrame JavaWindow. this yes JavaWindow.this , , this . JavaWindow.this JavaWindow.

+2

2:

JOptionPane.showMessageDialog(JavaWindow.this, "Hello!"); , ListenForButton, this ListenForButton. ActionListener, Component, JOptionPane.showMessageDialog().

ListenForButton JavaWindow, JavaWindow JavaWindow.this, C .

+1

1. You create an object using new JavaWindow();, but not saving it in a variable. In other words, you can say that the object you created is not stored in any reference variable as such.

2. This line simply says: Display a dialog box with the message Hello! in the current JFrame instance (JavaWindow.this) "

+1
source

All Articles