Java:跨类传递变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1346392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Passing Variables across classes
提问by Myles
This is probably a really simple problem, but I can't figure out how to do it.
这可能是一个非常简单的问题,但我不知道如何去做。
I have a GUI class with a listener which takes variables from comboboxes and sliders. I need it to pass these variables into a method in another class which will run on an object in that class.
我有一个带有侦听器的 GUI 类,它从组合框和滑块中获取变量。我需要它将这些变量传递给另一个类中的方法,该方法将在该类中的对象上运行。
How can I do this?
我怎样才能做到这一点?
回答by Andreas Dolk
There are two common approaches. The simple one, often used for dialogs, makes the selected values (e.g. your combobox selection) available for other classes, the second one allows other classes to register on your object to receive update notifications.
有两种常见的方法。简单的一个,通常用于对话框,使选定的值(例如您的组合框选择)可用于其他类,第二个允许其他类在您的对象上注册以接收更新通知。
First approach
第一种方法
- store the actual selections of your GUI elements in (private) member variables (like:
private String currentSelection). This is done by the listener that you already implemented. - implement a method like
String getSelection() - When the dialog is done (like someone pressed the OK button), fetch the value by simply calling the
getSelection()method
- 将您的 GUI 元素的实际选择存储在(私有)成员变量(如:)中
private String currentSelection。这是由您已经实现的侦听器完成的。 - 实现一个方法,如
String getSelection() - 当对话框完成后(就像有人按下了 OK 按钮),通过简单地调用该
getSelection()方法来获取值
This can be used if you offer a dialog for a user to enter some values. The file chooser dialogs are a typical example. If you require 'real time' access to the current selection, then use the:
如果您提供一个对话框供用户输入某些值,则可以使用此选项。文件选择器对话框就是一个典型的例子。如果您需要“实时”访问当前选择,请使用:
Second approach
第二种方法
- Implement the Observer Pattern (Listener class, eventually an event class)
- 实现观察者模式(监听器类,最终是一个事件类)
The pattern is a bit too complex to explain it step by step and in detail, but there's a lot of documentation and examples around, if you're interested and really need this realtime access to changes.
该模式有点复杂,无法逐步详细解释它,但是如果您有兴趣并且确实需要这种实时访问更改的权限,那么这里有很多文档和示例。
回答by T.J. Crowder
A simple data class (ideally fronted by an interface, to minimize coupling) should do the trick. Or if the data member names and such vary at runtime, a java.util.Mapmay be appropriate.
一个简单的数据类(理想情况下是一个接口,以最小化耦合)应该可以解决问题。或者如果数据成员名称等在运行时发生变化,ajava.util.Map可能是合适的。
回答by Mickel
回答by Jason Orendorff
Use parameters.
使用参数。
otherObject.doStuff(comboBoxValue, slider1Value, slider2Value);
The method you're calling must be declared to accept the number of parameters you want to pass:
您调用的方法必须声明为接受您要传递的参数数量:
class OtherObject {
...
void doStuff(int value1, int value2, int value3);
}

