首页 > > 详细

讲解Java、Java语言讲解留学生、辅导Java编程、Java设计辅导INFT1004 and INFT1006

Practical Exercise (INFT 104 Version .2 2 ndMay 2018)
Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
2
Instructions

In this practical exercise you will be developing a Post-It note application using JavaFX. Your major
asignment wil also use JavaFX so this exercise wil asist you with understanding some of the
available JavaFX components that are used to create Graphical User Interfaces. You should use the
Eclipse development environment and only use java and JavaFX (i.e. don’t use netbeans or other
tools). The practical is broken up into sections that increase in dificulty as you progress. You should
NOT consider this a step-by-step guide – as you progres the instructions will reduce in detail and
you should use you the skills you have developed to solve the steps. You should spend some time
researching and exploring the API in order to fuly implement al the requirements of the practical
exercise.

You will add source files to the default package as you progres through the exercise.



Presentation and Coments
All code should be carefuly commented using javadoc. You should clearly explain the code logic and
structure so someone who is unfamiliar with your code can quickly understand the logic and why
code choices have been selected.

JavaFX Exercises – Creating a “Post-it note” application



_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
3


_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
4
Task 0 – Setting Up JavaFX

To get started with JavaFX you can either create a new JavaFX Project or add the JavaFX library to the
project.

To create a JavaFX Project in Eclipse,
1. Select New
2. Select Other
3. Find and open the JavaFX folder
4. Select JavaFX Project
5. Step through the usual Eclipse project creation

If you cannot find the JavaFX folder in the dialog. Close the dialog and follow the steps found at:

htps:/ww.eclipse.org/efxclipse/instal.html#for-the-lazy

Once the instalation proces is complete, folow the steps above to create your JavaFX project.

Task 1 – Creating a JavaFX Application

We will start by writing a skeleton aplication. Our main window has to be derived from the JavaFX
stage class.

Let's start by creating the class PostItNote.java

Create a new java project in Eclipse called “01 Post-It Note” with Eclipse and create a file
PostItNote.java in the src directory.

This class should be:
• public
• extend Application
• have a single constructor
• have a 'main' method
• have a ‘start’ method

In the main method you should print the folowing lines to the console:

"Starting Post-It Note application..."
“Author: Dr Ros T. Smith” (Note you should use your own name here!)

Note: In order to launch the aplication you wil ned to ad the folowing code to the main method.

launch(args);

Write the skeleton code for this class, compile to check for syntax errors and run the application.

_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
5




_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
6
Task 2 – Creating the Stage and our Scene
The next step is to create the Stage where our Post-It note application comes to life. We will create a
new class called PostItNoteStage.

Create a new file called PostItNoteStage.java You should write code so your class has the following
properties:

• has a constructor with four parameters (double sizeX, double sizeY, double positionX, double
positionY)

Create a new Stage so we can add our scene to it and set the position of the stage.


stage = new Stage();


stage.setX();
stage.setY();

Next we ned to create a Scene that holds our GUI components. One way to think of the diference
betwen a Stage and a Scene is to imagine that the stage is our empty canvas, and a we paint a scene
on the canvas. When we ad new visual elements, we ad them into the scene, rather than the stage.



You may like to check the on-line documentation to read more about these methods at:

htps:/docs.oracle.com/javase/8/javafx/api/toc.htm

You do not ned to import anything to begin with, you can import the JavaFX components as neded.

Note: Some JavaFX components share a name with Java Swing components. You must ensure you are
importing the corect component from the javafx.* library.

To create a new Scene we need to set it’s layout and its size.
For now e’l create a simply ad a Pane layout to our Scene and set its size using the parameters we
passed through in the constructor.

Scene scene = new Scene(new Pane(), sizeX, sizeY);

Add the scene to our stage

stage.setScene(scene);

_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
7
Now compile your code and remove any syntax erors.


_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
8
Task 3 – Making the Stage visible

The next step is to instantiate your new PostItNoteStage clas from the PostItNote aplication and
make your PostItNoteStage visible.

In your PostItNote.java file you should add to the constructor a line to instantiate the first
PostItNoteStage. You should create a class variable in the PostItNote clas caled “mainWindow” and
instantiate it in the start method.

//Create the main window for our first post it note
mainWindow = new PostItNoteStage(200, 200, 0, 0);

In PostItNoteStage you also need to make the stage visible.

//Make stage visible
stage.show()



_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
9
Task 4 – Planing the layout
Now that you have prepared the basic skeleton aplication it is time to give some thought to the
layout of the application. Your Post-It note application will have two buttons (create new note and
delete note) at the top and a large text area at the botom. This simple design is easily represented
with a BorderPane layout using the Center and Top locations. One technique I find very useful to help
you understand exactly what the layout manager is doing is to create a Pane for each of the main
sections and change its colour so you can see the regions it is creating.

Create the following two class variable and instantiate them in the constructor of PostItNoteStage

BorderPane content;
BorderPane buttonArea;

Instantiate each in your constructor

Let’s change our code so that our new layout is added to the scene instead of the default we set earlier.
You should set it to use the BorderPane you have created

Scene scene = new Scene(content,sizeX,sizeY);

You should also set the color of “butonArea” to red and “content” to blue. To do this we will need to
use some CS code.

content.setStyle("-fx-background-color: blue");
buttonArea.setStyle("-fx-background-color: red");


Finaly you should add the butonArea BorderPane to the content pane.

content.setTop(buttonArea)

At the moment you wil not be able to se the butonArea because there is nothing in it.






_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
10



_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
11
Task 5 – Adding Butons

Next you will add the two butons add (+) and delete (x) to the buton area you just created. For this
you can use the Button class which provides all the functionality you need.

Create two class variables

Button newPostItNote;
Button deletePostItNote;

Instantiate them in your constructor and ad them to the butonArea BorderPane.

…= new Button(“+”);
…= new Button(“x”);
buttonArea.setLeft(newPostItNote);


You wil notice the butonArea BorderPane wil expand to acommodate the two new butons



_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
12
Task 6 – Creating a text area where we can write notes

You need to add a region where you can take notes. For this we will use a TextArea component

TextArea textArea;

Add this to the Center of our content BorderPane.




_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
13
Task 7 – Modifying the apearance of the Post-It Note

At this point your Post-It note is hideous as it does not folow a typical color scheme. In this step you
wil be modifying the apearance of al the components to use various yelow and grey shades.

We will refer as everything located in the Top section to be the title and everything in the Center to be
the body. There are many ways to specify a colour in CS, in this example we wil be using rgb values
from 0-255 (0 being no colour and 255 being ful colour).

For example:

content.setStyle("-fx-background-color: red”);

Is the same as writing

content.setStyle("-fx-background-color: rgb(255,0,0)”);


I have provided the RGB values used in my example, but try experimenting with your own colour
schemes.

Title: rgb(248, 247, 182)
Content: rgb(248, 253, 201)

Now e wil start of by modifying the title regions. Firstly, you can change the color of the butonArea
BorderPane that is currently set to RED. You should change it to use the Title rgb values.

The Buttons (newPostItNote and deletePostItNote) you created also need to have their appearance
changed to match in with the yelow. This can be done the same way you changed the colours of the
butonArea and textArea.

Now you can alter the font size and colour so the buton text is larger and grey in color. Create a new
Font buttonFont class variable and change the button font color using the pre-defined Color.GREY.

buttonFont = Font.font("Arial", FontWeight.BOLD,20);
newPostItNote.setFont(buttonFont);
newPostItNote.setTextFill(Color.GREY);

Do the same for the deletePostItNote button










_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
14
Task 8 – Modifying the text area apearance

Now it’s loking more like a Post-It Note, we should also change the text area to lok similar but with
a slightly lighter yellow color (using the RGB values provided earlier).

Unfortunately this gets a bit tricky as the default TextArea doesn’t behave the way we want it even
when we change the background colour and the inner colour via CSS.




To do this we ned to cast the iner part of our TextArea as a Region, which is the base class for Node-
based UI elements and modify it that way.

Region region = (Region) textArea.lookup(".content");
region.setStyle( "-fx-background-color: rgb(253, 253, 201)" );

As the lokup function is using CS, we ned to make sure that the Stage is showing for this method to
work properly, so make sure you place it after stage.show().

Now your Post-It Note should be loking something like this.


_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
15
Task 9 – Event capture for the + (new) button

We have two butons that curently do not operate. To make them operate we ned to capture the
events. For this we can implement the EventHandler class.

Add this code so we can create an action for our newPostItNote buton.

EventHandler newButton = new EventHandler(){
@Override public void handle(ActionEvent e){
new PostItNoteStage(sizeX,sizeY,0,0);
}
};

Add the event handler to your newPostItNote buton.

newPostItNote.setOnAction(newButton);

Run your application and you should be able to create a new Post It Note by clicking the ‘new’ Button.

However when it is created it will be placed in the top left corner every time. So we need to adjust the
position. To do this we will need to find both the current ‘stage’ position and check the screen
dimensions to ensure there is enough rom to fit your new note.

We can start by storing the x and y position of the current stage . The origin location is the top left
corner of your postit note. Retrieve them with the folowing commands.

x = stage.getX()
y = stage.getY()

Assuming we would like the new note to be created immediately to the right of the original one we
need to add the width to the start location.

double newX = x + stage.getWidth()
double newY = y

Pas your new positions as parameters to your constructor and run your aplication. You should be
able to create new postit notes that apear immediately to the right of the previous note.



_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
16
However a problem ocurs when you reach the width of your monitor. So one solution is to check if
the new X position exceeds the width and if so move down and go back to the start of the left side of
the scren. To achieve this we ned to get the scren width and ad some logic to calculate the new
starting position.



//Check we fit within the screen x size
Rectangle2D screen = Screen.getPrimary().getVisualBounds();
if(stage.getX() + stage.getWidth()*2 > screen.getWidth()){
newX = 0;
newY = stage.getY() + stage.getHeight();
}



_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
17
Task 10 – Close Buton Event

Now e ned to make the x (close) buton work as expected. Given you can have many notes open
simultaneously the x should only close the one note. Using your buton event handling that captures
the close event, change to dispose of the current window.

stage.close();

Run and test the function.


_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
18
Task 1 – Right Click Menu
Curently if you right click in the textArea a context menu apears with most of the features we ned.
However, since this is a learning exercise, let’s reinvent the whel and make our own Right Click Menu
with the items cut, copy, paste, about and exit.

Firstly we ned to create a ContextMenu and name it rightClickMenu.

rightClickMenu = new ContextMenu();

Then we create the MenuItem to ad to rightClickMenu

cut = new MenuItem("Cut");
rightClickMenu.getItems().add(cut);

Folow this template and ad the rest of the items; copy, paste, about, and exit.

Now e ned a way to display our menu instead of the default. To do this we add an EventFilter which
“consumes” the event,

textArea.addEventFilter(ContextMenuEvent.CONTEXT_MENU_REQUESTED, Event::consume);

Once the EventFilter has gobbled up our unwanted event, we can detect a right click by using a
MouseEvent EventHandler.

EventHandler rightClick = new EventHandler() {
@Override public void handle(MouseEvent e) {
if(e.getButton() == MouseButton.SECONDARY) {
menu.show(content, e.getScreenX(), e.getScreenY());;
}

}});

Now ad it to our content and textArea Panes.

content.setOnMouseClicked(rightClick)

Now implement the events for each of the MenuItems using the same template as used for the new
and close buttons. Create a ClipboardContent object in order to set the content on the clipboard. You
can access the clipboard with:

Clipboard.getSystemClipboard()

Note that you will need to check and define which data type you are either putting on or retrieving
from the clipboard. Here is my code for the paste function.

if(Clipboard.getSystemClipboard().hasString()){
textArea.appendText(
(String)Clipboard.getSystemClipboard().getContent(DataFormat.PLAIN_TEXT));
}

Compile and run your aplication to test out the menu.
_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
19
Task 12– About Dialog

We want to ad an about dialog to provide some information about the functionality of the program,
and author details. The dialog will display when the about item of the right click menu is selected,
loking something like the folowing template:

Dialog Title

Image
Text
Text
Text
Text

OK Buton


Our Dialog box wil be an Alert with AlertType.INFORMATION. Add the code to show the Alert to your
“about” event.

If done correctly, when you click about you should see the following dialog.








Your next tasks are to implement the about dialog in alignment with the template given above. You will
_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
need:
• A GridPane for the layout of the content
• A Text component for the text in the GridPane
• An ImageView for the picture

The picture should be a picture of you, saved in a common image format and place inside your project
folder. You can either scale it to a suitable size manualy, or do it programmaticaly. Initialise your
Image variable as folows:

Image image = new Image("pic.jpg");
ImageView imageView = new ImageView(image);
_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
21
Task 13 – Undecorated and re-size

The final task is to make the aplication lok like a more realistic Post-It note. The curent limiter of
this is the operating system window decoration. Windows and OS X ad their own title bar to the
window, which does limit the realism of our aplication.

To remove this, ad one line to the constructor of your PostItNoteStage class.

stage.initStyle(StageStyle.UNDECORATED);

If you run the program now, you wil se the note without any OS-specific decoration.



There is one problem, however. The OS decoration enabled the move and resize functions. Now that
we have taken that away, the note cannot be dragged around or resized. We can add that functionality
ourselves.

First, we ned to ad an .onMousePresed() event to our butonArea.

Create a new EventHandler like we did for our rightClickMenu. There we can calculate
an ofset for the X and Y axes from where we clicked to the post it notes position on the scren.

This stops the Post It Note from jumping to the spot where we clicked, and the top left will always be
the same distance away from the cursor while draging.

Do this by subtracting the click position from the stage position and store these as doubles OUTSIDE
of your class constructor.

_________________________________________________________________________________________________________________

Practical Exercises (INFT1004 and INFT1006) – Dr. Ros T. Smith
Now we set the position of the stage in the .onMouseDragged() method. This is simply done by ading
the ofsets we stored in .onMousePresed() to the current scren cordinates of the cursor.

Run and debug your aplication. If you have corectly implemented the formula, you wil be able to
move the Post-It by dragging on the title bar.

The resize function is similar to moving the window, but instead of seting a new location, you ned to
set the size of the PostItNoteStage. There are many methods for implementing this, but one could
include ading a panel to the botom right of the application and activating a similar method to the
drag method.

Try seting the width to the original width + the amount the cursor has moved on the x axis and repeat
for the y.

Lastly, restrict the resizing to remain, at minimum, the original size.

联系我们
  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-21:00
  • 微信:codinghelp
热点标签

联系我们 - QQ: 99515681 微信:codinghelp
程序辅导网!