ledinhhoangson ledinhhoangson - 2 years ago 87
Java Question

Update jTextField in another swing gui class

My problem is to update jTextField1 (update province) in class Province.java.
The first GUI showing up is AddAddress which contains 4 fields ( jTextField ) to be filled in : province ( jTextField1), district(2), ward(3) . Each time double-click on jTextField1 or 2 or 3 or 4 a new JFrame appears showing province, district or ward list. After clicking, it returns back to the first GUI and the province/district/ward clicked is updated.

Answer Source

Do not use JFrame in situations like that. Actually using multiple frames in one application is a bad practice. Please read here: The Use of Multiple JFrames: Good or Bad Practice?.

I suggest you to use a JDialog to select province etc.

Here is a simple example:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;

public class JDialogDemo extends JFrame {

    public JDialogDemo() {

        final MyDialog dialog = new MyDialog(this);

        final JTextField provinceField = new JTextField(10);

        JButton button = new JButton("Show Dialog");
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {



        setLayout(new FlowLayout());

        setSize(400, 400);

    public static void main(String[] args) {
        new JDialogDemo();

class MyDialog extends JDialog {

    private String selectedProvince;

    public MyDialog(Frame owner) {
        super(owner, true);


        final JList<String> list = new JList<String>(new String[]{"province1", "province2", "province3"});

        JButton okButton = new JButton("Ok");
        okButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                selectedProvince = list.getSelectedValue();

        add(okButton, BorderLayout.SOUTH);

    public String getSelectedProvince() {
        return selectedProvince;



Edit your jTextField1MouseClicked method

private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField1MouseClicked
        // TODO add your handling code here:
      if(evt.getClickCount() == 2){
            AddProvince provinceDialog = new AddProvince();

Then make AddProvince extends from JDialog. And add a method which return the selected province.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download