我希望在代码运行时在JavaFX组合框中添加新组件。例如,我注意到我不能做这样的事情:
import javafx.scene.control.ComboBox;
import javafx.scene.text.Text;
ComboBox<Text> combobox = new ComboBox<Text>();
combobox.getItems().setAll(new Text("Test 1"));
combobox.getItems().setAll(new Text("Test 2"));
新标签会覆盖旧标签。有没有解决这个问题的方法?
答案 0 :(得分:3)
您可以使用oberservable列表的add()
如,
ComboBox<Text> combobox = new ComboBox<Text>();
combobox.getItems().add(<your new item>);
或强>
combobox.getItems.add(combobox.getItems().size(), <your new item>);
要从组合框中删除项目,您已获得该对象并使用
combo.getItems().remove(object)
尝试样品。请看看,
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.JFXPanel;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javax.swing.JFrame;
/**
* @author JayaPrasad
*
*/
public class JavaFxSwing {
public static void main(String[] args) {
ObservableList<String> data = FXCollections.observableArrayList(
new String("test"), new String("name"));
ObservableList<Text> textData = FXCollections.observableArrayList(new Text("item1"), new Text("item2"));
final JFrame frame = new JFrame();
final JFXPanel jfxPanel = new JFXPanel();
final ComboBox<String> combo = new ComboBox<String>();
combo.setItems(data);
final ComboBox<Text> comboText = new ComboBox<Text>();
comboText.setItems(textData);
Button btn = new Button("add");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
combo.getItems().add(combo.getItems().size(),
new String("new item"));
comboText.getItems().add(comboText.getItems().size(),
new Text("item 3"));
}
});
final HBox hbox = new HBox();
hbox.setSpacing(20);
hbox.setPadding(new Insets(20, 0, 0, 40));
hbox.getChildren().addAll(combo, comboText, btn);
Platform.runLater(new Runnable() {
@Override
public void run() {
Scene scene = new Scene(hbox);
jfxPanel.setScene(scene);
frame.add(jfxPanel);
frame.setSize(400, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}