gpt4 book ai didi

java - 制作一个可以从另一个类打印的文本区域

转载 作者:行者123 更新时间:2023-11-30 03:13:49 25 4
gpt4 key购买 nike

我正在尝试使用程序的输出文本区域 UI 元素来打印程序的进度和更新,而不是使用 Eclipse 内部的控制台输出。我可以这样说:

System.out.println(string);

但不是打印到控制台,而是打印到 UI 上我自己的文本区域。我的代码看起来有点像这样(我删除了其他面板元素以更多地关注这一点):

这是我的 MainPanel 类,我在其中创建要打印到的元素:

public class MainPanel extends JPanel{

private JTextArea consoleOutput;
private JButton submitButton;

public MainPanel(){

setLayout(null);
Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
Font f1 = new Font("Arial", Font.PLAIN, 14);

consoleOutput = new JTextArea();
consoleOutput.setBounds(199, 122, 375 , 210);
consoleOutput.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(3, 4, 0, 0)));
consoleOutput.setEditable(false);
consoleOutput.setFont(f1);

submitButton = new JButton("Get Cards");
submitButton.setBounds(35, 285, 107, 49);
submitButton.setFont(f2);

submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String username = "HenryJeff";
String password = "Password";
Cards cards = new Cards();
cards.openTabs(username,password);
}
});
add(consoleOutput);
add(submitButton);
}
}

这是我的Cards 类:

public class Cards{

public void openTabs(String username, String password){
System.out.println(username + ", " + password);
}

如何替换 System.out.println(); 以打印到我的文本区域?我尝试让我的 Cards 类扩展我的 JPanel 并在其中创建控制台文本区域,然后添加一个写入文本的写入方法区,但没用。任何帮助表示赞赏!

最佳答案

在您的 MainPanel 类中

cards.openTabs(username,password,this);

并将您的 consoleOutput 指定为非 private 某些默认值。

更改您的Cards

public class Cards{

public void openTabs(String username, String password, MainPanel panel){
panel.consoleOutput.setText(username + ", " + password);
//now both user name and password will be displayed in text area of MainPanel class.
}

关于java - 制作一个可以从另一个类打印的文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com