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

标签 java swing jframe jpanel jtextarea

我正在尝试使用程序的输出文本区域 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/

相关文章:

java - 为什么我的代码会抛出 ClassNotFoundException?

java - 如何在 Android 的 ExoPlayer 中播放 Youtube 视频?

java - 尝试最佳解决方案?

java |如何在 "forever"循环运行时关闭 JFrame?

java - 在 JPanel 之间切换

java - 什么是与 Math.floorMod() 完全相同但使用 float 而不是整数的方法?

java - 对于 (字符串 s : letters) {JAVA} How is this in php? 对于 ($string_l1 : $array){PHP}?

java - Java 游戏中的滚动 JFrame

java - 给 JEditorPane 一个像 JTextArea 一样的 append(...) 方法

java - 单击按钮打开一个新的 JTable