You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java按钮点击打开新窗口:两窗口关联实现技术求助

Hey there! Let's get those two windows talking to each other. I'll walk you through how to connect your Task_3 frame to open Task1GUI when the "Enter data" button is clicked, plus fix a couple of small issues in your existing code to make things run smoother.

Step 1: Modify Task_3 (Main Frame)

Your original Task_3 code was missing the click event for the "Enter data" button, and also needed some missing imports for event handling. Here's the updated version that triggers the child window:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // Required for event listeners

public class Task_3 extends JFrame {
    private Button btn1, btn2, btn3;

    public Task_3(){
        setLayout(new FlowLayout());
        btn1 = new Button("Enter data");
        
        // Add click listener to open Task1GUI
        btn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Task1GUI(); // Create and show the child window
            }
        });
        add(btn1);

        btn2 = new Button("Check who is going");
        add(btn2);

        btn3 = new Button("View costs");
        add(btn3);

        setTitle("Event Costs");
        setSize(280, 150);
        setVisible(true);

        // Close entire app when main window is closed
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose();
                System.exit(0);
            }
        });
    }

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

Step 2: Fix Task1GUI (Child Frame)

Your original Task1GUI had two key issues: closing it would shut down the entire program, and there was a small spelling error. I also added error handling for invalid user input to prevent crashes:

import java.awt.*;
import java.awt.event.*;

public class Task1GUI extends Frame implements ActionListener {
    private Label lblInput;
    private Label lblOutput;
    private TextField tfInput;
    private TextField tfOutput;
    private int sum = 0;

    public Task1GUI(){
        setLayout( new FlowLayout());
        lblInput = new Label("Enter number of students: ");
        add(lblInput);

        tfInput = new TextField(5);
        add(tfInput);
        tfInput.addActionListener(this);

        lblOutput = new Label("The cost per student is: ");
        add(lblOutput);

        tfOutput = new TextField(20);
        tfOutput.setEditable(false);
        add(tfOutput);

        setTitle("Task1GUI");
        setSize(350, 120);
        setVisible(true);

        // Only close this window, not the entire app
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose(); // Release this window's resources only
            }
        });
    }

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

    @Override
    public void actionPerformed(ActionEvent evt){
        try {
            int numOfStudents = Integer.parseInt(tfInput.getText());
            int coachCost = 550;
            int entryCost = 30;
            int totalCost;
            int numFree;
            int discount;
            int costPerPerson;

            if(numOfStudents < 45){
                totalCost = coachCost + (numOfStudents * entryCost);
                numFree = numOfStudents / 10;
                discount = numFree * entryCost;
                costPerPerson = (totalCost - discount) / numOfStudents;
                tfInput.setText("");
                tfOutput.setText(String.valueOf(costPerPerson));
            } else {
                tfOutput.setText("Too many students entered"); // Fixed spelling error
            }
        } catch (NumberFormatException ex) {
            // Handle non-numeric input gracefully
            tfOutput.setText("Please enter a valid number!");
            tfInput.setText("");
        }
    }
}

Key Changes Explained

  • Button Click Trigger: We added an ActionListener to the "Enter data" button in Task_3. When clicked, it creates a new instance of Task1GUI, which opens the child window.
  • Safe Window Closing: For Task1GUI, we replaced System.exit(0) with dispose() so closing the child window doesn't shut down the entire application—users can still interact with the main Task_3 window.
  • Error Handling: The try-catch block prevents the program from crashing if the user enters something that isn't a number, giving a friendly error message instead.
  • Code Cleanup: Fixed variable name consistency and a spelling error to make the code more readable and maintainable.

内容的提问来源于stack exchange,提问作者Alexander James Stephens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:34:45