我知道JList有带有Stringand的构造函数DefaultListModel。我想找到一种将列表与enum类型一起使用的方法,例如JList<SomeEnum> jlist。
有办法实现这一点吗?
这是一个小的运行示例:
import javax.swing.*;
import java.awt.*;
public class Example implements Runnable {
private JPanel jPanel;
private JFrame jFrame;
private JList<Algorithm> diagnosisList;
public static void main(String[] args) {
EventQueue.invokeLater(new Example());
}
@Override
public void run() {
jFrame = new JFrame();
jPanel = new JPanel();
jPanel.setLayout(new FlowLayout());
jFrame.getContentPane().add(jPanel);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jPanel.setPreferredSize(new Dimension(500, 300));
DefaultListModel defaultListModel = new DefaultListModel();
defaultListModel.add(0, "Decision Tree");
defaultListModel.add(1, "Random Forest");
diagnosisList = getJList(defaultListModel);
jPanel.add(diagnosisList);
jFrame.pack();
jFrame.setVisible(true);
}
// I want to use Algorithm enum for parameter instaed of DefaultListModel
private JList<Algorithm> getJList(DefaultListModel algorithms) {
JList<Algorithm> jlist = new JList<Algorithm>(algorithms);
return jlist;
}
enum Algorithm {
DECISION_TREE_CLASSIFIER_DIAGNOSTIC("Decision Tree Classifier (D)", "Diagnostic"),
RANDOM_FOREST_DIAGNOSTIC("Random Forest (D)", "Diagnostic"),
LOGISTIC_REGRESSION_DIAGNOSTIC("Logistic Regression (D)", "Diagnostic"),
K_MEANS_DIAGNOSTIC("KMeans (D)", "Diagnostic");
private final String name;
private final String type;
Algorithm(final String name, final String type) {
this.name = name;
this.type = type;
}
@Override public String toString() {
return name;
}
}
}
阿波罗的战车
相关分类