[英]How do I load one Java class from another?
SEE THIS link for the solution to the problem 请参阅此链接以解决问题
I am doing a project where I have a drop down list, which when an option is selected on the list, it loads an applet with custom settings. 我正在做一个项目,其中有一个下拉列表,当在列表中选择一个选项时,它将加载具有自定义设置的applet。 The name of the main class of the applet is SteadyStateFusionDemo. 小程序的主要类的名称为SteadyStateFusionDemo。 I don't why I'm having so much trouble with this because I know that I have to use a ClassLoader, but quite frankly I don't know how to do this. 我不为什么会遇到这么多麻烦,因为我知道我必须使用ClassLoader,但是坦率地说,我不知道该怎么做。
Here is the code for my dropdown list. 这是我的下拉列表的代码。 I want to link from the option on the list to the other class. 我想从列表上的选项链接到另一个类。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.ClassLoader;
import ssfd.SteadyStateFusionDemo;
//**Creates Drop down Menu where choices show up in the box next to it//
//After one of these is selected, it loads the SteadyStateFusionDemo class//
//It also transmits a variable to the VariableStorage class, so that those//
//values can be used in operating the Tokamak.**//
public class ComboBox{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
ComboBox b = new ComboBox();
}
public ComboBox(){
String course[] = {"NSTX","LTX","ITER"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
//Where the ItemListener interprets the choice, and then loads the SteadyStateFusionDemo class.
if (str == "NSTX") {
txt.setText("A");
//loads SteadyStateFusionDemo, NSTX version
}
if (str == "ITER") {
txt.setText("B");
//loadsSteadyStateFusionDemo, ITER version
}
if (str == "LTX") {
txt.setText("C");
//loads SteadyStateFusionDemo, LTX version
}
There is more after this but it isn't relevant to the question. 此后还有更多,但与问题无关。
Can someone help me figure out how to link the two classes? 有人可以帮我弄清楚如何将两个班级联系起来吗? The second class is in a different package and it doesn't use a static method. 第二类位于不同的包中,并且不使用静态方法。 I have practically looked all over the Internet to find the solution, but alas no luck. 实际上,我已经在整个Internet上寻找解决方案,但是不幸的是。 :( :(
You can dynamically load classes by using Class.forName as in the following example, would this solve your problem? 您可以使用Class.forName来动态加载类,如以下示例所示,这是否可以解决您的问题?
Class<?> clazz = Class.forName("ssfd.SteadyStateFusionDemo");
SteadyStateFusionDemo ssfd = clazz.newInstance();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.