Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

java - Transfering text from one JFrame to another (Can't find my mistake in the code)

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..

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();
    }
 }

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...