2012-04-11 158 views
-1

我是Java新手,我想知道如何从主类中获取我的textarea?在Java中使用JFrame获取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上输出。什么是最好的解决方案呢?谢谢。

+0

我们的问题既不明确也不简洁 – ControlAltDel 2012-04-11 17:53:11

回答

1

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

修复?把它提供给所有其他的课程。

public static GuiManager animator = new GuiManager(); 

把那个地方你宣布该课程的所有其他变量,并采取了这是位于“createAndShowGUI()”方法之一。