【问题标题】:Alert in JAVA FXJAVAFX 中的警报
【发布时间】:2016-10-06 15:37:49
【问题描述】:

我想在尝试创建同名文件时在文件已存在时显示警报。我还没有完全完成代码。我想从 UI 中检索按钮值 Yes/No 。

代码:

这就是控制器的编码方式。

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();
            }


}

我想在 writesheet 函数中使用按钮值(以字符串类型存储)。现在它返回 NULL。

请建议是否有任何其他方式显示警告。我正在使用两个 fxml 文件,这是第二个 excel 文件。

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

【问题讨论】:

标签: javafx openjfx


【解决方案1】:

只需使用Alert 类。它为您需要的大多数是/否对话框提供了功能。

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
}

另外here 也是一个很好的教程。

【讨论】:

  • 请注意,如果用户在没有按下按钮的情况下关闭对话框(例如使用原生窗口关闭按钮),那么result.get() 将抛出异常。
  • 不,不会。我测试了它。即使我从任务栏关闭它,它也会始终返回ButtonType [text=No, buttonData=NO](除非我单击是)。
  • 你是对的。那很有意思。原生关闭按钮的解释不同,具体取决于显示的按钮组合。
  • @James_D 有意思,那为什么返回类型是Optional
  • 可选来自超类Dialog,如果在其他地方实现,它可以为null。更有趣的是,如果您只有“积极”按钮,您将无法使用窗口控件关闭窗口,但不会抛出异常。
【解决方案2】:

我通常会做一个方法,如果某些条件不满足就调用它。 例如:

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
    }

}

我从 Jhonny007 那里获取了一些代码,感谢他。

【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2015-05-10
    • 2018-10-13
    • 2016-08-10
    相关资源
    最近更新 更多