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

如何将字符串传递给另一个类?Setter/Getter使用遇阻求助

How to Pass ComboBox Selected Value Between Two Java Classes Using Setters & Getters

Hey there, let's work through this step by step—setters and getters are way simpler than they might feel right now, and we’ll get your value passed over in no time!

First, let’s nail down the core idea:

  • A setter is a method that lets another class assign a value to a private property in your class (think of it as handing FruitDetails the selected fruit name).
  • A getter is a method that lets other classes retrieve that value later if you need to use it elsewhere.

Step 1: Update FruitDetails.java with Setter & Getter

We’ll add a private property to store the selected fruit, plus the setter and getter methods to safely access it:

public class FruitDetails {
    // Private property to hold the selected fruit (can't be accessed directly from outside)
    private String selectedFruit;

    // Setter method: Lets external classes set the selected fruit value
    public void setSelectedFruit(String fruit) {
        this.selectedFruit = fruit;
    }

    // Getter method: Lets external classes retrieve the selected fruit value
    public String getSelectedFruit() {
        return this.selectedFruit;
    }

    // Optional: A test method to verify we're getting the value correctly
    public void displayFruitInfo() {
        System.out.println("Selected fruit: " + selectedFruit);
    }
}

Step 2: Modify Fruits.java to Pass the ComboBox Value

In your Fruits class, we’ll listen for changes to the ComboBox, grab the selected value, and use the setter to pass it to FruitDetails:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Fruits {
    public static void main(String[] args) {
        // Set up the basic UI
        JFrame frame = new JFrame("Fruit Selector");
        String[] fruitOptions = {"Apple", "Banana", "Orange", "Mango"};
        JComboBox<String> fruitComboBox = new JComboBox<>(fruitOptions);

        // Create an instance of FruitDetails (we need this to pass values to it)
        FruitDetails fruitDetails = new FruitDetails();

        // Add a listener to detect when the ComboBox selection changes
        fruitComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Get the currently selected item from the ComboBox
                String chosenFruit = (String) fruitComboBox.getSelectedItem();
                
                // Use the setter to pass this value to FruitDetails
                fruitDetails.setSelectedFruit(chosenFruit);
                
                // Test it out by calling our display method in FruitDetails
                fruitDetails.displayFruitInfo();
            }
        });

        // Finalize the frame setup
        frame.add(fruitComboBox);
        frame.setSize(350, 120);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

How This All Comes Together

  1. When you select an item in the ComboBox, the actionPerformed method triggers automatically.
  2. We grab the selected item as a String.
  3. We call fruitDetails.setSelectedFruit(chosenFruit)—this pushes the value into the selectedFruit property of our FruitDetails instance.
  4. If you need to use that value later in FruitDetails or another class, just call getSelectedFruit() to retrieve it.

For example, if you wanted to pull the value back from FruitDetails elsewhere, you’d do:

String currentSelectedFruit = fruitDetails.getSelectedFruit();

Setters and getters are just simple, safe ways to share data between classes without exposing private properties directly—you’ve got this!

内容的提问来源于stack exchange,提问作者Governator

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:11:29