I've been looking through this site pretty thoroughly trying to find an answer to my problem, but I haven't been able to find it anywhere. I'm a novice at Java, so please bear with me if I use incorrect terminologies.
I have two files, MainJFrame and Class1. I need to use a given Display() method to display the parameters of Class1 in a jTextArea in MainJFrame. It sounds easy enough, since I should simply be able to call Class1's Display() method from MainJFrame (after establishing an instance of Class1 in MainJFrame) and display it that way, but the issue is that the Display() method given is a void function. Here's the given code:
public void Display(JList list)
{
DefaultListModel model = new DefaultListModel();
model.add(0, item1 + " " + item2 + " " + item3);
list.setModel(model);
}
Is there any way to extract this information so that I can use it in my MainJFrame without resorting to saving it to a file or modifying the code? From my inexperienced standpoint, this doesn't look possible, and every time I've tried to modify this code to, for example, return a String to MainJFrame, it's been rejected by my instructor. I'm really running out of ideas.
I appreciate your input.
but the issue is that the Display() method given is a void function
There is no issue in returning void. Since JTextArea
is mutable and Java is Pass-by-Value, you can simply do the following from your MainFrame
class:
JTextArea textArea = new JTextArea(5, 30);
Class1 class1 = new Class1();
class1.display(textArea);
getContentPane().add(new JScrollPane(textArea));
And class1
will be responsible of setting the text as needed. For instance:
public void display(JTextArea textArea){
textArea.setText("I'm setting text from a Class1's object!");
}
I think your instructor is trying to emphasize that there is no need to return any value to do this.
Suggested read: Mutable and Immutable Objects and Pass-by-Value Please