将文本从一个 JFrame 传输到另一个(在代码中找不到我的错误) [英] Transfering text from one JFrame to another (Can't find my mistake in the code)

查看:31
本文介绍了将文本从一个 JFrame 传输到另一个(在代码中找不到我的错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个应用程序,我想传输"文本字段的内容,但我做错了什么,我不知道为什么..

I am building an app and I want to 'transfer' the content of a text field but I do something wrong and I can not find out why..

这是我的主 Frame 代码.当用户导航到 file-new-Actor 时,会弹出一个框架,用户必须在其中输入一些信息.我想将此信息(在这种情况下是文本文件中的文本)传输到我的主框架上的文本字段.

Here is my code for the main Frame . When the user navigates to file-new-Actor , a Frame pops up,where the user has to enter some info. I Want to transfer this info (In this case the text from a textfiel) to a text field on my main Frame.

public class GUI {

private JFrame frmGUI = new JFrame();
private JMenuItem mntmActor;
private JTextField gotText = new JTextField();
private NewActorFrame actorFrame = new NewActorFrame();
private JPanel panel = new JPanel();
private final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);

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

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

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    initComponents();
    createEvents();

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////// this method is for visualising all the components of the GUI such
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// as
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// buttons,
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// panels,
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// etc.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void initComponents() {
    // TODO Auto-generated method stub

    frmGUI.setTitle("Use Case Tool");
    frmGUI.setBounds(100, 100, 762, 621);
    frmGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmGUI.getContentPane().setLayout(new BorderLayout(0, 0));

    // add elements to the form
    frmGUI.getContentPane().add(panel, BorderLayout.SOUTH);
    frmGUI.getContentPane().add(tabbedPane, BorderLayout.CENTER);

    tabbedPane.addTab("New tab", null, gotText, null);
    gotText.setColumns(10);

    JTree tree = new JTree();
    tree.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            JPanel textView = new JPanel();
            tabbedPane.addTab("Text View", null, textView, null);

        }
    });
    tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Project \"Test\"") {
        {
            add(new DefaultMutableTreeNode("Use Cases"));
            add(new DefaultMutableTreeNode("Actors"));
        }
    }));
    frmGUI.getContentPane().add(tree, BorderLayout.WEST);

    JMenuBar menuBar = new JMenuBar();
    frmGUI.setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("FIle ");
    menuBar.add(mnFile);

    JMenu mnN = new JMenu("New");
    mnFile.add(mnN);

    JMenuItem mntmFolderInProject = new JMenuItem("Folder in Project");
    mnN.add(mntmFolderInProject);

    mntmActor = new JMenuItem("Actor");

    mnN.add(mntmActor);

    JMenuItem mntmUseCase = new JMenuItem("Use Case");
    mnN.add(mntmUseCase);

    JMenuItem mntmSystem = new JMenuItem("System");
    mnN.add(mntmSystem);

    JMenuItem mntmExport = new JMenuItem("Exit");
    mnFile.add(mntmExport);

    JMenu mnCreate = new JMenu("Help");
    menuBar.add(mnCreate);

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////// this method is for the events which are going to be triggered
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void createEvents() {

    mntmActor.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            System.out.println("Create a new actor");
            actorFrame.setVisible(true);
            gotText.setText(actorFrame.getFieldText());

        }
    });

}
}

这是主窗口的类,现在是另一个显示的类:

This is the class for the main window and now for the other one that shows up :

class NewActorFrame extends JFrame  implements  ItemListener

{
final String[] typeList = {"Human","Machine","System"};
public JTextField actorNameText = new JTextField();
private JButton btnCreateActor = new JButton("Create");
private  JLabel lblTypeOfActor = new JLabel("Type of actor");
private JComboBox typeOfActor = new JComboBox();
private JPanel topPanel = new JPanel();


public  NewActorFrame()
{

    setTitle( "Create a new actor" );
    setSize( 489, 414 );
    setBackground( Color.gray );
    getContentPane().setLayout( new BorderLayout() );


    topPanel.setLayout( null );
    getContentPane().add( topPanel, BorderLayout.CENTER );

    // Create a combobox where the user can choose the type of actor         to      be created  
    typeOfActor.setBounds( 140, 109, 260, 20 );
    topPanel.add( typeOfActor );

    // Populate the combobox list
    for( int countTypes = 0; countTypes < typeList.length; countTypes++ ){
     typeOfActor.addItem( typeList[countTypes] );
    }
    //  Disable edits - the user can not add other types of actors
    typeOfActor.setEditable( false);
    lblTypeOfActor.setBounds(12, 112, 121, 15);
    topPanel.add(lblTypeOfActor);

    JLabel lblNameOfActor = new JLabel("Name of Actor");
    lblNameOfActor.setBounds(12, 155, 121, 15);
    topPanel.add(lblNameOfActor);

    actorNameText.setBounds(140, 153, 225, 19);
    topPanel.add(actorNameText);
    actorNameText.setColumns(10);  

    btnCreateActor.setBounds(293, 229, 117, 25);
    topPanel.add(btnCreateActor);


    // Watch for changes
    typeOfActor.addItemListener( this );


    btnCreateActor.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           okButtonAction();
        }
     });



}




public void itemStateChanged( ItemEvent event )
{
    if( event.getSource() == typeOfActor
            && event.getStateChange() == ItemEvent.SELECTED )
    {
        System.out.println( "Change:"
                        + typeOfActor.getSelectedItem() );
    }
}

 public String getFieldText() {
      return actorNameText.getText();
   }

 private void okButtonAction() {

     System.out.println(getFieldText());
     System.out.println("Create pressed");
     this.dispose();
    }
 }

使用此代码,当我导航到菜单并选择新演员时,弹出窗口,我输入名称值,但按下按钮后没有显示任何文本.我注意到,如果我再次执行此创建操作,然后按菜单上的 Actor,我会从前一个文本字段中获取值.而这不是我想要的..

Using this code, when I navigate to the menu and choose new actor , the window pops up, I enter the name value ,but then after pressing the button no text is shown. I noticed that if I do this create action again, and press Actor on the menu I get the value from the previous text field. And this is not what I want..

感谢所有想提供帮助的人!

Thanks to all of you who are trying to help!

推荐答案

为什么要传输任何有用的信息?在用户有机会与第二个窗口进行交互以向其中输入信息之前,您要立即在第二个窗口的显示上请求信息.因此,您当前的行为(不传递任何数据)应该不足为奇.

Why should any useful information be transferred? You're requesting the information immediately on display of the second window, before the user has had any chance to interact with it, to input information into it. So your current behavior, that no data is passed, should come as no surprise.

如何解决这个问题?第二个窗口应该是 modal 对话框,例如模态 JDialog,而不是另一个 JFrame(正如 Andrew Thompson 在评论中告诉您的那样).这样,来自调用类的程序流停止,直到对话窗口被处理并且不再可见.

How to fix this? The 2nd window should be a modal dialog, such as a modal JDialog, and not another JFrame (as Andrew Thompson is telling you in comments). This way the program flow from the calling class halts until the dialog window has been dealt with and is no longer visible.

请注意,同样的问题会一次又一次地被问到,如果您稍微挖掘一下,您就会发现重复的问题和一次又一次得到的相同答案.

Note that this same question gets asked time and time again, and if you do just a little digging, you'll find the dups and the same answer that gets given time and again.

这篇关于将文本从一个 JFrame 传输到另一个(在代码中找不到我的错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆