简体   繁体   English

在另一个类的jTextArea中显示类的数据时出现问题

[英]Issues displaying data from a class in a jTextArea in a different class

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. 我是Java的新手,所以如果我使用了错误的术语,请多多包涵。

I have two files, MainJFrame and Class1. 我有两个文件,MainJFrame和Class1。 I need to use a given Display() method to display the parameters of Class1 in a jTextArea in MainJFrame. 我需要使用给定的Display()方法在MainJFrame的jTextArea中显示Class1的参数。 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. 这听起来很简单,因为我应该能够从MainJFrame调用Class1的Display()方法(在MainJFrame中建立Class1的实例之后)并以这种方式显示它,但是问题是给定的Display()方法无效功能。 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? 有什么方法可以提取此信息,以便我可以在MainJFrame中使用它,而不必求助于将其保存到文件或修改代码? 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. 从我经验不足的角度来看,这似乎是不可能的,并且每次我尝试修改此代码以例如将String返回MainJFrame时,它都被我的老师拒绝。 I'm really running out of ideas. 我的想法真的耗尽了。

I appreciate your input. 感谢您的投入。

but the issue is that the Display() method given is a void function 但是问题是给定的Display()方法是一个无效函数

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是可变的,而Java是按值传递,因此您可以从MainFrame类中简单地执行以下操作:

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. 并且class1将负责根据需要设置文本。 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 建议阅读: 可变和不可变的对象以及值传递

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM