Create the component
Create a listener
Create an instance of the listener
Add (“register”) the listener to the component
Add the component to the JFrame
You can skip steps 2 – 4 if your program doesn’t require an action
How does this work?
Create a visual interface
A JFrame
A button
Then implement a listener
this is the code which you wish to perform once the button Is pressed
register the listener to the button
when the button is pressed
Java calls ActionPerformed
You do not call ActionPerformed
ActionPerformed is an automation in Java
Registration tells Java to call it when the button is pressed
And then reads the listener
Labels
can add a line of text using JLabel component
create a component
JLabel MyLabel = new JLabel(“My Label”);
Skip
Skip
Skip
Add the component to the JFrame
MyWindow.add(MyLabel);
Layouts
We require a way to arrange multiple objects within a window
Java technique which accomplishes that is the layout
BorderLayout
GridLayout
FlowLayout
JFrame contains a method setLayout()
MyWindow.setLayout(Layout l);
Executing this sets the layout of the window to the layout object l.
Andrew is not sure that setLayout take a Layout as its param, he will find out for next class
BorderLayout
When Adding a component also specify a region in which It goes
MyWindow.add(MyButton, BorderLayout.North/East/South/West/Center)
GridLayout
GridLayout GL;
GL = new GridLayout (2, 3)
//2 = rows, 3 = columns
MyWindows.setLayout(GL);
JLabel Label 1 = new JLabel (“1”)
MyWindow.add (Label 1);
Flow Layout
flowLayout FL;
FL = newFlowLayout ();
MyWindow.setLayout (FL);
// add components
Good JFrame Practice
Up to now, everything has been done in main
This is bad practice because the window is an object
It should be treated as such
We are creating a modification of JFrame
Use inheritance
No comments:
Post a Comment