2014-01-23 57 views
0

我正在设计一个简单的GUI(在Eclipse中使用WindowBuilder Pro),该按钮只在按下按钮(测试)后在textArea之后显示“Hello World”按钮不会显示文本区域中的文本

http://i.stack.imgur.com/PbYo8.jpg

然而,当我按下按钮,它不会在文本区域显示出来!有人可以调整代码或至少告诉我该怎么做?

public class TextA { 

private JFrame frame; 


/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       TextA window = new TextA(); 
       window.frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the application. 
*/ 
public TextA() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    frame = new JFrame(); 
    frame.setBounds(100, 100, 450, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 

    JTextArea textArea = new JTextArea(); 
    textArea.setBounds(113, 44, 226, 96); 
    frame.getContentPane().add(textArea); 

    JButton btnTesting = new JButton("Testing"); 
    btnTesting.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 

      JTextArea textArea = new JTextArea(); 
      textArea.setText("Hello World!"); 


     } 
    }); 
    btnTesting.setBounds(168, 167, 117, 29); 
    frame.getContentPane().add(btnTesting); 
} 
} 
+3

您正在动作侦听器内部创建一个新的'JTextArea',并在其上设置文本。这与您添加到“JFrame”中的文本区域不同。 – crush

+2

Java GUI可能需要在多种平台上工作,使用不同的屏幕分辨率并使用不同的PLAF。因此,它们不利于组件的准确放置。为了组织强大的图形用户界面,请使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556)以及[空格]的布局填充和边框(http: //stackoverflow.com/q/17874717/418556)。 –

+0

或者,使用JavaFX,您可以制作更丰富,更精确的GUI。 – SnakeDoc

回答

1

您正在处理错误的JTextArea对象。它应该看起来像这样:

final JTextArea textArea = new JTextArea(); // final added here 
textArea.setBounds(113, 44, 226, 96); 
frame.getContentPane().add(textArea); 

JButton btnTesting = new JButton("Testing"); 
btnTesting.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 

      //JTextArea textArea = new JTextArea(); this should be removed. 
      textArea.setText("Hello World!"); 


     } 
    }); 
+0

是的,它的工作!非常感谢你 – Mike

3

将您的代码更改为像这样的东西。

final JTextArea textArea = new JTextArea(); 
frame.getContentPane().add(textArea); 
btnTesting.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      textArea.setText("Hello World!"); 
     } 
    }); 

您在里面创建一个新的实例actionListener你想引用您要添加到帧的对象。而作为@AndrewThompson总是劝告不使用null布局的原因:

Java的图形用户界面可能需要在多个平台上工作,使用不同PLAFs不同 屏幕分辨率&。因此,他们不是 有利于组件的准确放置。要组织可靠的GUI组件 ,请改为使用布局管理器或它们的组合,以及用于空白区域的布局填充&边框。

0

您正在actionPerformed(ActionEvent e)中创建一个新的JTextArea对象。只需使用已经定义的文本区域对象并进行最终确定,因为它将用于动作事件方法。你可以在action事件方法中删除行JTextArea textArea = new JTextArea(),它应该可以工作。

+0

这就是我说的或至少尝试:)。也许我应该更清楚。 –