Alert in JAVA FX

醉酒当歌 提交于 2019-12-31 03:44:08

问题


I want to display an alert when a file already exists when trying to create the file with same name . I have not completed the code fully. I want to retrieve the button value Yes/No from the UI .

Code:

This is how the controller is coded.

package application;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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.stage.Stage;

public class WarningController implements Initializable {
    @FXML
    public Button yes;

    @FXML
    public Button no;

    public static String type;

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

    }

     public String confirmSelection(ActionEvent event)throws IOException{
         Button button = (Button) event.getSource();
             type = button.getText();
            if(type.equals("Yes")){
                Stage stage = (Stage) yes.getScene().getWindow();
                stage.close();
                //System.out.println("Yes");
                return type;
            }
            else{
                //System.out.println("No");
                Stage stage1 = (Stage) no.getScene().getWindow();
                stage1.close();
                return type;
            }

     }
/********************************************************************************/
     public void writesheet(String[][] result,String ComboValue,String[] heading) throws IOException{ 
            //Create blank workbook
            XSSFWorkbook workbook = new XSSFWorkbook(); 
            //Create a blank sheet
            XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");
            //Create row object
            XSSFRow row;

            String[][] towrite=result;
            int rows=towrite.length;
            //int cols=towrite[0].length;
           // System.out.println(rows +"    "+ cols);

            Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
            empinfo.put("0", heading);
            for(int i=1;i<=rows;i++){
                empinfo.put( Integer.toString(i),towrite[i-1]);
            }


            //Iterate over data and write to sheet
            Set < String > keyid = empinfo.keySet();
            int rowid = 0;
            for (String key : keyid)
            {
               row = spreadsheet.createRow(rowid++);
               Object [] objectArr = empinfo.get(key);
               int cellid = 0;
               for (Object obj : objectArr)
               {
                  Cell cell = row.createCell(cellid++);
                  //cell.setCellValue((String)obj);
                  cell.setCellValue(obj.toString());
               }
            }

            //Write the workbook in file system
            File f=new File(("C:\\"+ComboValue+".xlsx"));
            if(f.exists()){
                Stage primaryStage=new Stage();
                Parent root=FXMLLoader.load(getClass().getResource("/application/Warning.fxml"));
                Scene scene = new Scene(root,350,150);
                scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                primaryStage.setScene(scene);
                primaryStage.show();
                System.out.println(type);
            }
            FileOutputStream out = new FileOutputStream(f);
            workbook.write(out);
            out.close();
            System.out.println(ComboValue+"  "+"Excel document written successfully" );
            workbook.close();
            }


}

I want to use button value(stored in String type) in writesheet function. Now it is returning NULL.

Please suggest if there is any other way to show warning.I am using two fxml files and this is the second excel file.

  [1]: http://i.stack.imgur.com/ZK6UC.jpg

回答1:


Simply use the Alert class. It provides functionality for most yes/no dialogs that you ever need.

Alert alert = new Alert(AlertType.WARNING, 
                        "File already exists. Do you want to override?", 
                        ButtonType.YES, ButtonType.NO);

Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
    // ... user chose YES
} else {
    // ... user chose NO or closed the dialog
}

Also here is a good tutorial.




回答2:


I usually make a method, and call it if certain conditions are not met. Ex:

if(condition)
      alert();



public void alert(){  //alert box

Alert alert = new Alert(AlertType.WARNING,"", ButtonType.YES, ButtonType.NO);  //new alert object
    alert.setTitle("Warning!");  //warning box title
    alert.setHeaderText("WARNING!!!");// Header
    alert.setContentText("File already exists. Overwrite?"); //Discription of warning
    alert.getDialogPane().setPrefSize(200, 100); //sets size of alert box 

    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.YES){
        // ... user chose YES
    } else {
        // ... user chose NO or closed the dialog
    }

}

I grabbed some code from Jhonny007, credit to him.



来源:https://stackoverflow.com/questions/39900229/alert-in-java-fx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!