Могу ли я использовать текстовое значение для selectToggle ()? - PullRequest
0 голосов
/ 13 октября 2019

Я использую текстовый файл для загрузки информации в графический интерфейс javafx. Есть ли способ, которым я могу использовать текстовое значение там, чтобы выбрать переключатель в группе переключателей.

Я думаю '' 'toggleGroup.selectedValue (значение переключателя)' '' - это нужная мне функция, но она не принимает строку. Есть ли способ преобразовать строку в значение переключателя, косвенно?

Следующее не работает, потому что '' 'selectToggle ()' '' принимает переключатель, а не текстовое значение, и кажется, что неявное или явное приведение '' (toggle) '' 'не работает.

tgrpSex.selectToggle(read.nextLine());

Это должно быть воспроизводимо:

package programmingassignment1;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.*;
//import javafx.scene.layout.StackPane;
//import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.*; //input/output
import java.util.Scanner;
//import java.util.*; //scanner, user input
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
//import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;

public class Address extends Application {


    RadioButton rbMale = new RadioButton("Male");
    RadioButton rbFemale = new RadioButton("Female");
    ToggleGroup tgrpSex = new ToggleGroup();


    GridPane rootPane = new GridPane();


    @Override
    public void start(Stage primaryStage){

//Setting an action for the Open Contact  button       
        Button btOpenContact = new Button("Open Contact");
        File file = new File("AddressBook.txt");

        btOpenContact.setOnAction(event -> {
            try {
                openContact(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
//Setting an action for the Save button        
        Button btSave = new Button("Save");

        btSave.setOnAction(
            new EventHandler<ActionEvent>(){
                @Override
                public void handle(ActionEvent e){
                    try{saveContact(file);}
                    catch(Exception f){f.getMessage();}
        }});



        //associate radio buttons with a toggle group
        rbMale.setToggleGroup(tgrpSex);
        rbFemale.setToggleGroup(tgrpSex);

        rbMale.setOnAction(e -> {
            if(rbMale.isSelected()){int maleContact = 1;}
        });
        rbFemale.setOnAction(e -> {
            if(rbFemale.isSelected()){int maleContact = 0;}
        });

      rootPane.add(new Label("Sex"), 3, 1);
        rootPane.add(rbFemale, 3, 2);
        rootPane.add(rbMale, 3, 3);       

        rootPane.add(btOpenContact, 1, 13);

        Scene scene = new Scene(rootPane, 1000, 500);

        primaryStage.setTitle("Address Book");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public static void main(String[] args) {
            launch(args);
    }

 public void saveContact(File file) throws FileNotFoundException, Exception{ //declaration
                //this code might cause a FileNotFoundException
                //if it does it creates an exception object of the above type
        try{
                    //PrintWriter output = new PrintWriter (file);
                    PrintStream output = new PrintStream(file);
                    output.println(tfContactFirst.getText());
                    output.println(tfContactLast.getText());
                    output.println(tfSpouseFirst.getText());
                    output.println(tfSpouseLast.getText());
                    output.println(cboWorkHome.getValue());
                    output.println(tfStreet.getText());
                    output.println(tfCity.getText());
                    output.println(tfState.getText());
                    output.println(tfZip.getText());
                    output.close();
                }
                //what do do with exception
                //here the catch clause with create another exception
                //that is passed the result of the getMessage() method from the original exception
        catch(FileNotFoundException e){
                    throw new Exception(e.getMessage());
                }
    }

//read same text file you save too
    public void openContact(File file) throws FileNotFoundException, Exception{
        try{
            Scanner read = new Scanner(file);     
            while(read.hasNextLine()){
                //how do I save the imageFileName
                 tfContactFirst.setText(read.nextLine());
                 tfContactLast.setText(read.nextLine());
                 tgrpSex.selectToggle(read.nextLine());
                 tfSpouseFirst.setText(read.nextLine());
                 tfSpouseLast.setText(read.nextLine());
                 //tfSpouseGender.setText(read.nextLine());
                 cboWorkHome.setValue(read.nextLine());
                 tfStreet.setText(read.nextLine());
                 tfCity.setText(read.nextLine());
                 tfState.setText(read.nextLine());
                 tfZip.setText(read.nextLine());
                 //taNotes.setText(read.nextLine());
            }
        }
        catch(FileNotFoundException e){
                    throw new Exception(e.getMessage());
        }
    }
}

Нет результатов <- синтаксическая ошибка </p>

1 Ответ

1 голос
/ 13 октября 2019

Извините. Я получил ответ. Я не знал, что такое объект типа переключения. Я посмотрел примеры selectToggle () и узнал, что вы можете передать ему объект переключателя. Так что я поместил это в утверждение if then. if(read.nextLine().equals("Male")){tgrpSex.selectToggle(rbMale);} else{tgrpSex.selectToggle(rbFemale);}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...