简体   繁体   中英

Data transfer between JFrames

I have JFrame 1 which shows JLabel "Balance" - my bank account balance and 2 JButton components (Add income; Add expenses). By clicking one of these buttons I hide main frame and open income of expenses frame where I add the data.

After I input amounts into JTextField components and click "Save" button, in dialog field I can see that my record was saved, but when I click "Back" button, the "Balance" label stays 0 as if nothing was entered.

Could somebody help me? My code is a mess now so I doubt it would be helpful.

Here is an easy example where I tried to rebuild your program:

public class Class {
    public static void main(String[] args) {
        Frame1 frame1 = new Frame1();
        Frame2 frame2 = new Frame2();

        frame1.setChildWindow(frame2);
        frame2.setParentWindow(frame1);
    }
}

Frame1:

import javax.swing.*;

class Frame1 extends JFrame {
    private int balance = 0;
    private JLabel balanceLabel = new JLabel(String.valueOf(balance));
    private Frame2 childWindow;

    Frame1() {
        JPanel panel = new JPanel();
        panel.add(new JLabel("Balance:"));
        panel.add(balanceLabel);
        JButton balanceButton = new JButton("Balance");
        balanceButton.addActionListener(e -> {
            childWindow.setVisible(true);
            setVisible(false);
        });
        panel.add(balanceButton);
        getContentPane().add(panel);
        pack();
        setVisible(true);
    }

    void setChildWindow(Frame2 childWindow) {
        this.childWindow = childWindow;
    }

    void addBalance(int balance) {
        this.balance+=balance;
        balanceLabel.setText(String.valueOf(this.balance));
    }
 }

Frame2:

import javax.swing.*;

class Frame2 extends JFrame {
    private Frame1 parentWindow;

    Frame2() {
        JComboBox<Integer> comboBox = new JComboBox<>(new Integer[] {1,2,3,4,5,6,7,8,9});
        JButton addButton = new JButton("add");

        addButton.addActionListener(e -> {
            parentWindow.addBalance((Integer)comboBox.getSelectedItem());
            parentWindow.setVisible(true);
            setVisible(false);
        });

        JPanel panel = new JPanel();
        panel.add(comboBox);
        panel.add(addButton);
        getContentPane().add(panel);
        pack();
    }

    void setParentWindow(Frame1 parentWindow) {
        this.parentWindow = parentWindow;
    }
}

If you have any further questions, feel free to ask!

(But btw, in your next questions, post some code, so that other people can help you better. Even if it is a mess, other people could help you with that as well and give you hints what you could to better or how you could write your code cleaner ^^)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM