1

I'm new to Java and have an issue I'm stuck with. I have created a class with a Swing UI in it which contains a jTextArea called 'jTextAreaConsole'.:

public class converterUI extends javax.swing.JFrame {

This class imports another class called 'dbConverter':

package my.converterui;
import dbToExcel.dbConverter;

dbConverter is a simple class with one method:

public class dbConverter extends common{

public static void convert(String sourceDB, String sourceQry, String destination, String objectName){
    dbConverter converter = new dbConverter();
    Connection con = converter.getConnection(sourceDB);
    String sql = sourceQry;
    ResultSet result = converter.runQuery1(con,sql);
    converter.writeOut(result, objectName, destination);
    closeConnection(con);
}
public static void main(String[] args) {
}
}

the runQuery and writeOut methods are detailed in the 'common' class extended by this class. What I want to do is in the common class reference the jTextAreaConsole object to append text to it. I've already tried using super.jTextAreaConsole.append(str) and this runs but doesn't do anything.

Edit: Basic example here:

package myproject;

public class MyProject extends mainForm{

    public static void main(String[] args) {
        mainForm.main(null);
    }

    public void clickAction(){
        passText();
    }
}


package myproject;
class mainForm extends javax.swing.JFrame {

    public void passText(){
        jTextArea1.append("This is a test");
    }

    public mainForm() {
        initComponents();
    }



    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Click me");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(42, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(162, 162, 162))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addComponent(jButton1)
                .addGap(27, 27, 27)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }                       

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    }                                        

      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new mainForm().setVisible(true);
            }
        });
    }


    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;

}

Thanks,

  • What class is the text area declared in? – user1803551 Jan 26 '16 at 09:37
  • 1
    Looks like you are confusing referencing with inheriting. I suggest you go over [the basic tutorial](http://docs.oracle.com/javase/tutorial/java/index.html). If you want to solve this specific issue the post an [MCVE](http://stackoverflow.com/help/mcve). Be sure to copy-paste your code to a *new project* and make sure it compiles and runs before posting it here. – user1803551 Jan 26 '16 at 09:56
  • I think my problem is in importing the class rather than extending to inherit it. The problem is I can't extend multiple classes as currently the UI class already extends the swing framework. – user1320453 Jan 26 '16 at 12:23
  • Your sentence makes no sense - you don't extend the "*swing framework*". In any case, multiple inheritances is not your problem and importing is done by the IDE for you as long as there is visibility. I still suggest that you do the tutorial and post a [mcve]. – user1803551 Jan 26 '16 at 12:28
  • Edit your question with the code. Make sure it doesn't contain unnecessary parts. – user1803551 Jan 26 '16 at 13:03
  • Updated with simple example. – user1320453 Jan 26 '16 at 13:29
  • This may help: http://stackoverflow.com/questions/629315/dynamically-refresh-jtextarea-as-processing-occurs – PeterMmm Jan 26 '16 at 13:35
  • You have 2 `main`s, please stick to 1. Currently, your problem is that the method `jButton1ActionPerformed` which is called when the button is pressed is empty. Also, `clickAction` is never called. Maybe call `passText` directly from `actionPerformed`? – user1803551 Jan 26 '16 at 13:54
  • No, because that invalidates my example. What I really want to do is call clickAction from ActionPerformed. – user1320453 Jan 26 '16 at 14:11
  • Then what is `jButton1ActionPerformed` for? – user1803551 Jan 26 '16 at 14:13
  • It's an example. I want jButton1ActionPerformed to call a method from the other class and for that method to append text to the textarea in this class. – user1320453 Jan 26 '16 at 14:19

1 Answers1

1

Depending on your design, you have 2 choices:

  1. Create an instance of the MyProject, let's call it mp. Then in your actionPerformed (or your jButton1ActionPerformed, still not sure why you need it) call mp.clickAction().
  2. Make clickAction static, then call MyProject.clickAction().

The fact that MyProject extends mainForm (which should be renamed to MainForm) already tells me that you're probably doing something wrong in your design.

Edit:

Here, I wrote the code for you. Just don't be surprised if you later need to expand on it and it's not easy to do because the design is bad.

import java.awt.EventQueue;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

import static javax.swing.GroupLayout.*;
import static javax.swing.GroupLayout.Alignment.*;

public class MyProject {

    private static MainForm gui = new MainForm();

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> gui.setVisible(true));
    }

    public static void clickAction() {

        gui.passText();
    }
}

class MainForm extends JFrame {

    private JTextArea jTextArea1 = new JTextArea();

    public MainForm() {

        initComponents();
    }

    private void initComponents() {

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JScrollPane jScrollPane1 = new JScrollPane();
        JButton jButton1 = new JButton();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Click me");
        jButton1.addActionListener(e -> MyProject.clickAction());

        //@formatter:off
        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jScrollPane1, PREFERRED_SIZE, 318, PREFERRED_SIZE)
                .addContainerGap(42, Short.MAX_VALUE))
            .addGroup(TRAILING, layout.createSequentialGroup()
                .addContainerGap(DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(162, 162, 162))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addComponent(jButton1)
                .addGap(27, 27, 27)
                .addComponent(jScrollPane1, PREFERRED_SIZE, 179, PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );
        //@formatter:on

        pack();
    }

    public void passText() {

        jTextArea1.append("This is a test");
    }
}

What I did:

  • MyProjext is not a subclass of MainForm anymore because it doesn't make sense for it to be.
  • The program has just 1 main now because it should have only 1 main. I chose MyProjext to be the entry point.
  • MyProjext holds a reference to the GUI (MainForm) so it can invoke its methods. In my point 1 I suggested the other way around: have the GUI hold a reference to MyProjext. It still can be a better choice depending on the design.
  • MyProjext's clickAction is now static as I suggested in my point 2. Again, it's a blind design choice.
  • I made the code more readable because the GUI-builder code is not as friendly. I suggest that after you finish learning the basics of OO (not only relevant to Java) you learn how to write a GUI and not use a builder.
user1803551
  • 12,965
  • 5
  • 47
  • 74
  • Neither works. 1) Gives me a null pointer exception. 2) gives me a 'passText() cannot be referenced in a static context' exception. – user1320453 Jan 26 '16 at 15:24
  • @user1320453 (1) Did you initialize the reference? (2) The error makes no sense. – user1803551 Jan 26 '16 at 15:55
  • 1) I did MyProject mp; 2) Full error is "non-static method passText() cannot be referenced from a static context" – user1320453 Jan 26 '16 at 16:25
  • @user1320453 1) Then initialize it. 2) Same problem, either make that method static or hold a reference to the object. You have to do the tutorial from the beginning, no way around it. You don't understand the most basic OO concepts and syntax. You shouldn't be coding programs at this stage, you should be learning the basics. – user1803551 Jan 26 '16 at 17:37
  • Thanks. I didn't realise Java was so fragile. – user1320453 Jan 26 '16 at 18:33
  • @user1320453 What do you mean by "*fragile*"? – user1803551 Jan 26 '16 at 18:37
  • A small thing like this makes it fall apart. Also I didn't realise the user community was quite so hostile. – user1320453 Jan 26 '16 at 18:40
  • @user1320453 Small thing? You are trying to call a method of an object you did not create, this is OO 101. In any language where I delete 1 character in a keyword it cause everything to break - that's syntax. As a strongly typed language, Java restricts you to correct usage and eliminates a lot of bugs. – user1803551 Jan 26 '16 at 18:52
  • @user1320453 Also, I don't see any hostility, I have actually taken more time than anyone else here to guide you through the most basic troubleshooting. Without an MCVE your question would have been long closed. You can flag for a moderator if you think otherwise. – user1803551 Jan 26 '16 at 18:53
  • Thanks for your help anyway. I will try to find out the reason it doesn't work from the tutorial but I have already completed the codecademy tutorial which didn't mention this. – user1320453 Jan 26 '16 at 19:20
  • @user1320453 I already told you why it doesn't work and also 2 ways to fix it. The tutorial won't tell you otherwise, but it will help you to understand *why* it works this way. Good luck! – user1803551 Jan 26 '16 at 19:29
  • Well I've been through the tutorial last night but still cannot see where I'm going wrong. I've tried a re-design of the code but still no luck, I can only think i'm hitting a limitation of Java in that it cannot reference two classes. – user1320453 Jan 27 '16 at 08:18
  • @user1320453 Limitation of Java? You can't be serious, it's the most basic OO concepts. Why won't you post the code of your attempt to fix it according to my 1st way because for me it works well and I don't know what your code looks like. – user1803551 Jan 27 '16 at 14:53
  • @user1320453 And please add what it is you are trying to achieve eventually so I can post a proper design solution. What is the *MyProject* class supposed to do and why does it need to extend `mainForm`. If this is just an experiment it's also fine. – user1803551 Jan 27 '16 at 15:10
  • I want to create a class that houses the UI. Then have another class (MyProject) that contains all of the processing methods that can also modify the textarea in the UI class. – user1320453 Jan 27 '16 at 21:10
  • I think the only way around this is to add everything to one giant class but that really seems stupid to me. – user1320453 Jan 27 '16 at 22:01
  • @user1320453 Why do you keep suggesting that this is not solvable after I already told you how to solve it? Do I need to write the program for you without knowing how it is intended to work? – user1803551 Jan 27 '16 at 22:43
  • @user1320453 I wrote the code for you. Don't think it will help you much in the future though. – user1803551 Jan 27 '16 at 23:18
  • Thanks a lot for your help. I have been working through some more examples and I think I have resolved it, though slightly different to your example. My biggest problems were that the class was in a different package (which I think is why I was trying to reference it) and I hadn't instantiated the class. Resolving these two problems has made it work. Thanks for your patience. – user1320453 Jan 28 '16 at 12:58