当前位置: 首页 > 知识库问答 >
问题:

在JavaFX中从组合框中选择项时,如何在TextField上显示不同的文本?

益承颜
2023-03-14
public class Details {

    private final StringProperty ministryOfWater ;
    private final StringProperty ministyOfLands;

    public Details(String ministryOfWater, String ministyOfLands) {
        this.ministryOfWater = new SimpleStringProperty(ministryOfWater);
        this.ministyOfLands = new SimpleStringProperty(ministyOfLands);
    }

    public String getMinistryOfWater() {
        return ministryOfWater.get();
    }

    public void setMinistryOfWater(String ministryOfWater) {
        this.ministryOfWater.set(ministryOfWater);
    }

    public StringProperty ministryOfWaterProperty() {
        return ministryOfWater;
    }
    //finished  ministry of water

    public String getMinistyOfLands() {
        return ministyOfLands.get();
    }

    public void setMinistyOfLands(String ministyOfLands) {
        this.ministyOfLands.set(ministyOfLands);
    }

    public StringProperty ministyOfLandsProperty() {
        return ministyOfLands;
    }

    //finished with the ministry of lands 

    @Override
    public String toString() {
        return getMinistryOfWater() + " " + getMinistyOfLands();
    }

}

这是我的全部代码

package application;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

public class SafeguardTrackingToolController  implements Initializable {

    @FXML
    private TextField txtActivity;
    @FXML
    private TextArea txtComments;
    /*@FXML
    private ComboBox<String> cmbComponent;*/

    @FXML
    private ComboBox<Details> cmbComponent;
    private ObservableList<Details> cmbComponentData = FXCollections.observableArrayList();

    @FXML
    private TableColumn 
     tblComponent,
    tblActivity,
    tableColumnForTor,
     tblContract,
    tblfirst,
     tblFinal ,
    tblBank,
     tblDisclosure,
    tblNema,
    tblBudgetRe,
     tblBudgetPro,
     tblBegin,
     tblComments;

    @FXML
    private TableView<Items> tableViewForExcel;

        @FXML
        private DatePicker
     dateTor,
    dateContract,
    dateFirstDraft,
     dateFinalDraft,
     dateBank,
   dateDisclosure,
     dateNema,
   dateBudget,
    dateProvided,
    dateImplementation;

    @FXML
    private Button btnAdd,btnReset
    ,btnCreateAnotherSheet
   ,btnExcel
     ,btnDelete;


    private final ObservableList<Items> data=FXCollections.observableArrayList(new Items(null, null, null, null, null, null, null, null, null, null, null, null, null));


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub

        tblComponent.setCellValueFactory(new PropertyValueFactory("Component"));
        tblActivity.setCellValueFactory(new PropertyValueFactory("Activity"));
        tableColumnForTor.setCellValueFactory(new PropertyValueFactory("Torr"));
        tblContract.setCellValueFactory(new PropertyValueFactory("Contract"));
        tblfirst.setCellValueFactory(new PropertyValueFactory("FirstDraft"));
        tblFinal.setCellValueFactory(new PropertyValueFactory("FinalDraft"));
        tblBank.setCellValueFactory(new PropertyValueFactory("Bank"));
        tblDisclosure.setCellValueFactory(new PropertyValueFactory("Disclosure"));
        tblNema.setCellValueFactory(new PropertyValueFactory("Nema"));
        tblBudgetRe.setCellValueFactory(new PropertyValueFactory("Budget"));
        tblBudgetPro.setCellValueFactory(new PropertyValueFactory("Provided"));
        tblBegin.setCellValueFactory(new PropertyValueFactory("Implementation"));
        tblComments.setCellValueFactory(new PropertyValueFactory("Comment"));


        cmbComponentData.add(new Details("Ministry of Water",""));
        cmbComponentData.add(new Details("Ministry of Lands",""));
        cmbComponentData.add(new Details("Ministry of Minerals", ""));
        cmbComponentData.add(new Details("Ministry of ManKind", ""));

        if(cmbComponent.getSelectionModel().getSelectedItem().equals("Ministry of Water")){
            txtActivity.setText("1.0.0");

        } 

        cmbComponent.setItems(cmbComponentData);





        tableViewForExcel.getItems().setAll(this.data);
        tableViewForExcel.setEditable(true);
    }


public static class Items{
        //the setters and getters should be of the same name with the simple string property

        private final SimpleStringProperty Component;
        private final SimpleStringProperty Activity;
        private final SimpleStringProperty Torr;
        private final SimpleStringProperty Contract;
        private final SimpleStringProperty FirstDraft;
        private final SimpleStringProperty FinalDraft;
        private final SimpleStringProperty Bank;
        private final SimpleStringProperty Disclosure;
        private final SimpleStringProperty Nema;
        private final SimpleStringProperty Budget;
        private final SimpleStringProperty Provided;
        private final SimpleStringProperty Implementation;
        private final SimpleStringProperty Comment;

        private Items(String Comp, String Act,
                String Tor, String Co,
                String FDraft, String FinalDra, 
                String Ban, String Dis, String Nem, 
                String Bud,String Pro, String Im,String Comm) {



            this.Component = new SimpleStringProperty(Comp);
            this.Activity = new SimpleStringProperty(Act);
            this.Torr= new SimpleStringProperty(Tor);
            this.Contract= new SimpleStringProperty(Co);
            this.FirstDraft = new SimpleStringProperty(FDraft);
            this.FinalDraft = new SimpleStringProperty(FinalDra);
            this.Bank = new SimpleStringProperty(Ban);
            this.Disclosure = new SimpleStringProperty(Dis);
            this.Nema= new SimpleStringProperty(Nem);
            this.Budget = new SimpleStringProperty(Bud);
            this.Provided = new SimpleStringProperty(Pro);
            this.Implementation= new SimpleStringProperty(Im);
            this.Comment = new SimpleStringProperty(Comm);

        }

        public String getComponent() {
            return Component.get();
        }

        public void setComponent(String Comp) {
            Component.set(Comp);
        }


        public String getActivity() {
            return Activity.get();
        }

        public void setAcivity(String Act) {
            Activity.set(Act);
        }


        public String getTorr() {
            return Torr.get();
        }

        public void setTorr(String Tor) {
            Torr.set(Tor);
        }


        public String getContract() {
            return Contract.get();
        }

        public void setContract(String Co) {
            Contract.set(Co);
        }


        public String getFirstDraft() {
            return FirstDraft.get();
        }

        public void setFirstDraft(String FDraft) {
            FirstDraft.set(FDraft);
        }


        public String getFinalDraft() {
            return FinalDraft.get();
        }

        public void setFinalDraft(String FinalDra) {
            FinalDraft.set(FinalDra);
        }


        public String getBank() {
            return Bank.get();
        }

        public void setBank(String Ban) {
            Bank.set(Ban);
        }


        public String getDisclosure() {
            return Disclosure.get();
        }

        public void setDisclosure(String Dis) {
            Disclosure.set(Dis);
        }


        public String getNema() {
            return Nema.get();
        }

        public void setNema(String Nem) {
            Nema.set(Nem);
        }

        public String getBudget() {
            return Budget.get();
        }

        public void setBudget(String Bud) {
            Budget.set(Bud);
        }


        public String getProvided() {
            return Provided.get();
        }

        public void setProvide(String Pro) {
            Provided.set(Pro);
        }



        public String getImplementation() {
            return Implementation.get();
        }

        public void setImplementation(String Im) {
            Implementation.set(Im);
        }


        public String getComment() {
            return Comment.get();
        }

        public void setComment(String Comm) {
            Comment.set(Comm);
        } 

    }


private void write() throws FileNotFoundException, IOException{


    try {


        File myFile=new File("example.xlsx");
        final XSSFWorkbook workbook;
        if (myFile.exists() == false) {
              System.out.println("Creating a new workbook '" + myFile + "'");
         workbook = new XSSFWorkbook();

        }else{
            System.out.println("Appending to existing workbook '" + myFile + "'");
              final InputStream is = new FileInputStream(myFile);
              try {
                  workbook = new XSSFWorkbook(is);
              } finally {
                is.close();
              }

        }
        int sheetIndex = 1;
        while (workbook.getSheet("sample" + sheetIndex) != null) {
          sheetIndex++;
        }

        XSSFSheet spreadsheet = workbook.createSheet("sample");

        XSSFRow row  =null;
        XSSFCell cell=null;

        row= spreadsheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("Component");

        cell = row.createCell(1);
        cell.setCellValue("Activity");

        cell = row.createCell(2);
        cell.setCellValue("TOR");

        cell = row.createCell(3);
        cell.setCellValue("Contract");

        cell = row.createCell(4);
        cell.setCellValue("First Draft");

        cell = row.createCell(5);
        cell.setCellValue("Final Draft");

        cell = row.createCell(6);
        cell.setCellValue("Bank Clearance");

        cell = row.createCell(7);
        cell.setCellValue("Disclosure");

        cell = row.createCell(8);
        cell.setCellValue("NEMA Licence");

        cell = row.createCell(9);
        cell.setCellValue("Budget Request & Prepared");

        cell = row.createCell(10);
        cell.setCellValue("Budget Provided");

        cell = row.createCell(11);
        cell.setCellValue("Begin & Implementation");

        cell = row.createCell(12);
        cell.setCellValue("Comments");



        int i=1;
        for(Items item: tableViewForExcel.getItems()){
                row= spreadsheet.createRow(i);
               // row.createCell(0).setCellValue(item.getComponent());

                cell = row.createCell(0);
                cell.setCellValue(tblComponent.getCellData(1).toString());

                cell = row.createCell(1);
                cell.setCellValue(tblActivity.getCellData(1).toString());

                cell = row.createCell(2);
                cell.setCellValue(tableColumnForTor.getCellData(1).toString());

                cell = row.createCell(3);
                cell.setCellValue(tblContract.getCellData(1).toString());

                cell = row.createCell(4);
                cell.setCellValue(tblfirst.getCellData(1).toString());

                cell = row.createCell(5);
                cell.setCellValue(tblFinal.getCellData(1).toString());

                cell = row.createCell(6);
                cell.setCellValue(tblBank.getCellData(1).toString());

                cell = row.createCell(7);
                cell.setCellValue(tblDisclosure.getCellData(1).toString());

                cell = row.createCell(8);
                cell.setCellValue(tblNema.getCellData(1).toString());

                cell = row.createCell(9);
                cell.setCellValue(tblBudgetRe .getCellData(1).toString());

                cell = row.createCell(10);
                cell.setCellValue(tblBudgetPro.getCellData(1).toString());

                cell = row.createCell(11);
                cell.setCellValue(tblBegin.getCellData(1).toString());

                cell = row.createCell(12);
                cell.setCellValue(tblComments.getCellData(1).toString());

                //.... add other column data as well
                i++;
        }

        FileOutputStream out = new FileOutputStream(myFile);
        workbook.write(out);
        out.close();
        System.out.println("Data is wrtten Successfully");
    } catch (Exception e) {
        e.printStackTrace();
    }

} 


@FXML
private void onClickToAddOntheTable (ActionEvent event){
            tableViewForExcel.getItems().add(new Items(  
            cmbComponent.getValue().toString(), 
            txtActivity.getText(),
            dateTor.getValue().toString(),
            dateContract.getValue().toString(),
            dateFirstDraft.getValue().toString(),
            dateFinalDraft.getValue().toString(),
            dateBank.getValue().toString(),
            dateDisclosure.getValue().toString(),
            dateNema.getValue().toString(),
            dateBudget.getValue().toString(),
            dateProvided.getValue().toString(),
            dateImplementation.getValue().toString(),

           txtComments.getText()));

            onClickToReset(event);



}

@FXML
private void onClickToSaveInExcel (ActionEvent event){
    try {
        write();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@FXML
private void onClickToReset (ActionEvent event){
    cmbComponent.setValue(null);
    txtActivity.clear();
    dateTor.setValue(null);;
    dateContract.setValue(null);
    dateFirstDraft.setValue(null);
    dateFinalDraft.setValue(null);
    dateBank.setValue(null);
    dateDisclosure.setValue(null);
    dateNema.setValue(null);
    dateBudget.setValue(null);
    dateProvided.setValue(null);
    dateImplementation.setValue(null);
    txtComments.clear();
}



@FXML
private void onClickToResetTable (ActionEvent event){
    tableViewForExcel.getItems().clear();
}


@FXML
private void onClickToCreateAnotherSheet (ActionEvent event){
    LoadAnotherSheet();

}

private void LoadAnotherSheet() {
    Parent root = null;
    try {
        root = FXMLLoader.load(getClass().getResource("SafeguardTrackingToolNewSheetUI.fxml"));
        Scene scene = new Scene(root);
        Stage nStage = new Stage();
        nStage.setScene(scene);
        //nStage.setMaximized(true);
        nStage.setTitle("Another Sheet");
        nStage.show();
        Stage stage = (Stage) btnCreateAnotherSheet.getScene().getWindow();
        stage.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}



public class Details {

    private final StringProperty ministryOfWater ;
    private final StringProperty ministyOfLands;

    public Details(String ministryOfWater, String ministyOfLands) {
        this.ministryOfWater = new SimpleStringProperty(ministryOfWater);
        this.ministyOfLands = new SimpleStringProperty(ministyOfLands);
    }

    public String getMinistryOfWater() {
        return ministryOfWater.get();
    }

    public void setMinistryOfWater(String ministryOfWater) {
        this.ministryOfWater.set(ministryOfWater);
    }

    public StringProperty ministryOfWaterProperty() {
        return ministryOfWater;
    }
    //finished  ministry of water

    public String getMinistyOfLands() {
        return ministyOfLands.get();
    }

    public void setMinistyOfLands(String ministyOfLands) {
        this.ministyOfLands.set(ministyOfLands);
    }

    public StringProperty ministyOfLandsProperty() {
        return ministyOfLands;
    }

    //finished with the ministry of lands 

    @Override
    public String toString() {
        return getMinistryOfWater() + " " + getMinistyOfLands();
    }

}

}

如何将所选组合框中的不同文本显示到声明为

TextField txtActivity

if(cmbComponent.getSelectionModel().getSelectedItem().equals("Ministry of Water")){
            txtActivity.setText("1.0.0");

        } 

共有1个答案

邹普松
2023-03-14

根据您的需要,您可以:

cmbComponent.valueProperty().addListener((observable, oldValue, newValue) -> {
    txtActivity.setText(newValue == null ? null : newValue.toString());
});

这样,textfield在选择项目后将保持可编辑状态。

txtActivity.textProperty().bind(Bindings.createStringBinding(() -> {
    Details d = cmbComponent.getValue();
    return d == null ? null : d.toString();
}, cmbComponent.valueProperty()));

这样textfield就不再是可编辑的了。

TextFormatter<Details> formatter = new TextFormatter<>(new StringConverter<Details>() {

    @Override
    public String toString(Details object) {
        return object == null ? "" : object.toString();
    }

    @Override
    public Details fromString(String string) {
        // Return Details object based on String input in TextField
        return string == null || string.isEmpty() ? null : cmbComponent.getItems().stream().filter(d -> string.equals(d.toString())).findAny().orElse(null);
    }

});

txtActivity.setTextFormatter(formatter);

cmbComponent.valueProperty().bindBidirectional(formatter.valueProperty());
 类似资料:
  • 所以,我有一个奇怪的问题,我从组合框列表中选择一个项目,为了填充第二个组合框,我必须首先从第一个组合框中再次选择单词,而不是从项目列表中,而是单词本身。只有这样,代码才会注册我选择了该项目。我拥有的代码是简单的$variable.SelectedItem。参见下面的代码; 我想做的就是从下拉列表中选择位置“医院”,然后第二个名为“$ComboBox_Printer”的组合框填充我服务器中的打印机名

  • 我正在开发一些学术性的JavaFX桌面应用程序。在创建注册表单时,我需要使用combobox/choicebox,但在这一步中我遇到了几个问题。组合框没有显示任何项目。我尝试了许多在堆栈溢出上找到的修复方法,但似乎都不起作用。我在分享我的主要观点。java控制器代码和我的FXML代码放在一边。 Main.java Controller.java FXML文件

  • 我创建了一个 (JavaFX) 组合框,我正在填充一个由 HBoxes 制成的可观察列表,以便我可以在每个列表单元格中显示带有一些文本的图像。 这显示得很好,除了每当您选择列表中的一个项目时,它都会消失。一旦您选择了每个项目,它根本不会呈现任何项目。(您仍然可以通过单击它们之前所在的空间来选择它们。 你知道我该怎么纠正吗? 我的部分代码显示如下: 提前感谢您的帮助!

  • 我已经实现了,这样我的船舶列表就会根据国家和船舶类型进行更改,但问题是我无法选择任何船舶。 你知道我哪里出了问题吗? 上面是Controller类中的。 上面是视图类中的setter。

  • 我有一个ComboBox,我正在用Sheet对象值填充它。 我设置了一个单元格工厂,以便在下拉列表中显示工作表的名称。它工作正常(似乎如此)。 问题是,选择项目(“单元格”)后,框中显示的值不是列表中显示的值。 这是相关的代码部分:

  • 我有一个奇怪的问题。我在JavaFX中使用了一个ComboBox,其中每一项都是一个HBox,是一个图像和一个标签的组合。 是字符串的数组列表。只是一个