2012-04-08 28 views
2

此代码编译并运行,但不会从文本字段复制文本,然后将其放入文本区域。使用按钮将文本从文本字段移至文本区

import java.awt.*; 
import javax.swing.*; 
import java.awt.event.*; 

public class NameGameFrame extends JFrame 
{ 

    static JTextField textfield = new JTextField(20); 
    static JTextArea textarea = new JTextArea(30,30); 

    public static void main(String[] args) 
    { 

     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setTitle("Name Game"); 
     frame.setLocation(500,400); 
     frame.setSize(800,800); 

     JPanel panel = new JPanel(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 

     JLabel label = new JLabel("Enter the Name or Partial Name to search:"); 
     c.gridx = 0; 
     c.gridy = 0; 
     c.insets = new Insets(2,2,2,2); 

     panel.add(label,c); 

     c.gridx = 0; 
     c.gridy = 1; 
     panel.add(textarea,c); 

     JButton button = new JButton("Search"); 
     c.gridx = 1; 
     c.gridy = 1; 
     panel.add(button,c); 

     c.gridx = 1; 
     c.gridy = 0; 
     panel.add(textfield,c); 

     frame.getContentPane().add(panel, BorderLayout.NORTH); 
     frame.pack(); 
     frame.setVisible(true); 

    } 
     static class Action implements ActionListener 
     { 
     public void actionPerformed(ActionEvent e) 
     { 

      //This is the code that should perform the task 
      String name = textfield.getText(); 
      textarea.append(name); 
     } 
    } 
} 

我是Java编程新手,如果我的问题很简单,我很抱歉。

+1

你忘了'Action'添加到您的按钮? – 2012-04-08 02:59:30

回答

0

Appen下面的代码到您的程序之后,它的声明按钮
即。 JButton buuton = new JButton("Search");

button.addActionListener(new ActionAdapter() 
{ 
    public void actionPerformed(ActionEvent ae) 
    { 
      textarea.setText(textfield.getText()); 
    } 
}); 
+0

感谢您的帮助。当我将ActionListener作为参数应用到ActionAdapter时,它非常完美。感谢您的帮助。 – 2012-04-08 03:26:54