I am trying to figure out how the Swing based Hello World application works. This is the code I have:
import java.awt.*;
import javax.swing.*;
public class HelloWorldSwing extends JFrame {
JTextArea m_resultArea = new JTextArea(6, 30);
//====================================================== constructor
public HelloWorldSwing() {
//... Set initial text, scrolling, and border.
m_resultArea.setText("Enter more text to see scrollbars");
JScrollPane scrollingArea = new JScrollPane(m_resultArea);
scrollingArea.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
// Get the content pane, set layout, add to center
Container content = this.getContentPane();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
this.pack();
}
//============================================================= main
public static void main(String[] args) {
JFrame win = new HelloWorldSwing();
win.setTitle("TextAreaDemo");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
}
The code was taken from here (I slightly modified it). I have two main questions about the example but if you answer at leas one of them would appreciate it a lot. Here are my questions:
1. As far as I understand the "main" method is run automatically. In this method we instantiate a "win" object and, as a consequence the constructor of the class will be executed. But when the first line of the class is executed (JTextArea m_resultArea = new JTextArea(6, 30));.
2. Is there a good reason to instantiate the text area (m_resultArea) outside the constructor and then set its parameters (setText) within the constructor. Why we cannot instantiate the text area in the constructor? Why we cannot set the parameters of the text area beyond the constructor? (Just for the sake of consistency).