【问题标题】:Get a textarea in java using JFrame使用JFrame在java中获取文本区域
【发布时间】:2012-04-11 17:46:34
【问题描述】:

我是 Java 新手,我想知道如何从主类获取我的 textarea??

这是我的代码:

public static void main(String[] args) {
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();

        }
    });
}



private static void createAndShowGUI() {
    frame = new JFrame("Frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    GuiManager animator = new GuiManager();

    frame.add(animator, BorderLayout.CENTER);

    // Display the window.
    frame.pack();
    frame.setSize(800, 500);
    frame.setVisible(true);
}

和 GuiManager:

public GuiManager() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

       // .............

    // Create Scrolling Text Area in Swing
    JPanel panelLabel = new JPanel(); 
    panelLabel.setLayout(new FlowLayout());     // No content pane for JPanel.
    JPanel panel = new JPanel(); 
    panel.setLayout(new FlowLayout());     // No content pane for JPanel.


    JLabel ta1Label = new JLabel("Label One", JLabel.LEFT);
    ta1Label.setAlignmentX(Component.LEFT_ALIGNMENT);

    JTextArea ta = new JTextArea("", 10, 30);
    ta.setLineWrap(true);
    JScrollPane sbrText = new JScrollPane(ta);
    sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    JLabel ta2Label = new JLabel("Label2", JLabel.RIGHT);
    ta2Label.setAlignmentX(Component.RIGHT_ALIGNMENT);

    JTextArea ta2 = new JTextArea("", 10, 30);
    ta2.setLineWrap(true);
    JScrollPane sbrText2 = new JScrollPane(ta2);
    sbrText2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    panelLabel.add(ta1Label);
    panelLabel.add(ta2Label);
    panel.add(sbrText);
    panel.add(sbrText2);



    // Put everything together.
    add(panelLabel);
    add(panel);
    setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

}

我的目标是将输出重定向到这些 textarea,对于某些输出我需要重定向到左侧的 textarea,但有时我需要在右侧的 textarea 上输出。这样做的最佳解决方案是什么?谢谢。

【问题讨论】:

  • 你的问题既不清晰也不简洁

标签: java swing textarea jframe jtextarea


【解决方案1】:

您想要访问的所有内容似乎都在 GuiManager 中。但是,您将它的声明放在一个方法中。这意味着它成为一个局部变量。一旦方法完成了它的代码,变量就消失了,不能再访问了。

解决办法?只需将其提供给所有其他类即可。

public static GuiManager animator = new GuiManager();

把它放在你为那个类声明所有其他变量的地方,然后取出位于'createAndShowGUI()'方法中的那个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2012-07-21
    相关资源
    最近更新 更多