Al Grant
Al Grant

Reputation: 2354

Netbeans Swing GUI

I have create a GUI in Netbeans using Swing and are having trouble understanding the best way to set a value of a text area in the GUI.

The netbeans class for this GUI is called JFrameTest and there is a public static void main method to display the GUI within this JFrameTestClass:

    public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new JFrameTest().setVisible(true);
        }
    });
}

Now from another class called GetFiles I want to display this GUI, and set a text area called JTextFiles to a string value.

The code to display the GUI from GetFiles is:

    JFrameTest newwindow = new JFrameTest();
    newwindow.setVisible(true);

This much I understand but I cant reference my text area newwindow.JTextFiles because netbeans set all the init components in:

private void iniComponents() 

to be private!

I can not understand why Netbeans designer makes the GUI so that you can not set the values of text fields etc from outside the class.

Whats the best way forward? Put the GUI in the GetFiles class or....?

Thanks

-AL

Like this:

    public String assigntext(String directorystring) {
    JTextFiles.setText(directorystring);
}

Upvotes: 0

Views: 193

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

I can not understand why Netbeans designer makes the GUI so that you can not set the values of text fields etc from outside the class.

For the same reason that when you create your own classes you should give them private fields that cannot be directly accessed and manipulated indiscriminately from outside classes. It's called information hiding or encapsulation, and is a pillar of object-oriented programming principles as it helps reduce code complexity and thus bugs. If you need to change the state of fields, do it in a controlled way via public methods -- something that you can do with your NetBeans generated GUI.

If you do use public methods, do so that exposes your class's fields the least. So for instance if you want an outside class to get the text from a JTextField, fooTextField, prefer this:

public String getFooTextFieldText() {
    return fooTextField.getText();
}

over this:

public JTextField getFooTextField {
    return fooTextField;
}

re your question about:

public String assigntext(String directorystring) {
    JTextFiles.setText(directorystring);
}

This is akin to a ssetter method, and since with setter type methods, you're changing the state of the instance but usually don't expect anything in return, you'd make this void:

// note the difference?
public void assigntext(String directorystring) {
    JTextFiles.setText(directorystring);
}

Upvotes: 2

Related Questions