2016-10-06 4 views
1

Я хочу показать предупреждение, когда файл уже существует при попытке создать файл с тем же именем. Я не полностью выполнил код. Я хочу получить значение кнопки Yes/No из пользовательского интерфейса.Предупреждение в JAVA FX

Код:

Это, как кодируется контроллер.

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


} 

Я хочу использовать значение кнопки (сохраненное в строковом типе) в функции записи. Теперь он возвращает NULL.

Просьба указать, есть ли другой способ показать предупреждение. Я использую два файла fxml, и это второй файл excel.

enter image description here

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

Почему бы не использовать существующий класс '' Alert' '(http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html)? –

ответ

3

Просто используйте 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 - хороший учебник.

+0

Обратите внимание, что если пользователь закрывает диалоговое окно, не нажимая кнопку (например, использует закрытую кнопку закрытия окна), тогда 'result.get()' генерирует исключение. –

+0

Нет, не будет. Я протестировал его. Он всегда будет возвращать 'ButtonType [text = No, buttonData = NO]' (кроме того, что я нажимаю yes) Даже если я закрою его из TaskBar. – Jhonny007

+0

Вы правы. Это интересно. Кнопка родного закрытия интерпретируется по-разному, в зависимости от комбинации отображаемых кнопок. –

0

Обычно я делаю метод и называю его, если определенные условия не выполняются. 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 
    } 

} 

enter image description here

Я схватил какой-то код от Jhonny007, кредит ему.