Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

GUI application using JavaFX with a button and a textarea When the button is clicked the HTML from a website should be retrieved and output into the textarea

Write a GUI application using JavaFX with a button and a textarea. When the
button is clicked, the HTML from www.allTestAnswers.com should be
retrieved using the URL class and output into the textarea. Use Java 8’s functional
programming paradigm to implement the action listener for the button.

Answer:


/**
* Link JavaFX with the URL class and lambda expression
* to handle the action listener
*/
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Question14 extends Application
{
	public void start(Stage primaryStage)
	{
		TextArea txt = new TextArea();
		Button btn = new Button();
		txt.setText("");
		btn.setText("Get HTML");

		// Lambda Expression to set the action
		// for the button click
btn.setOnAction(e ->
		{
			// Read the URL into the string html
			String html = "";
			try
			{
				URL website = new
 URL("http://www.</span>allTestAnswers<span style="color: #000000;">.com");
				Scanner inputStream = new Scanner(new InputStreamReader(
					website.openStream()));
				while (inputStream.hasNextLine())
				{
				  String s = inputStream.nextLine();
				  html = html + s + "\n";
				}
				inputStream.close();
				txt.setText(html);	// Put HTML into the textarea
			}
			catch (Exception ex)
			{
				System.out.println(ex.toString());
			}
        });

		// Use a vertical layout
        VBox root = new VBox();
        root.getChildren().add(txt);
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 500, 300);

        primaryStage.setTitle("JavaFX URL and Lambda Exercise");
        primaryStage.setScene(scene);
        primaryStage.show();
	}
}


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!