Lecture 8 - Swing Flashcards
What is an ActionListener
is a class that is responsible for handling all action events (ie. when the user clicks on a component or presses enter after inputting text). User in control
How do you use an ActionListener?
Give an example.
// Put it in the class title public class Ex extends JFrame implements ActionListener {
// add it to the reference of the button & add it to panel
public Ex(){
button1.addActionListener(this);
this.add(button1);
//public void actionPerformed(ActionEvent e){ ..
How do you track how many times a button has been clicked?
public class Ex extends JFrame implements ActionListener { int num = 0; // counter private JButton b = new JButtom("click me");
public Ex(){
b. addActionListener(this);
this. add(b);
public void actionPerformed(ActionEvent e){
num++;
b.setText(String.format(“I was clicked %d times”, num));
Create a button on the west panel & add a method so that it is handled.
public class b extends JFrame implements ActionListener{ JButton button1,
public b(){
button1 = new JButton(“Please stay”);
this.add(button1, BorderLayout.WEST);
button1.addActionListener(this);
actionPerformed():
public void actionPerformed(ActionEvent e){
..}
What does Integer.toString() do?
returns a String object representing this Integer’s value.
Write an actionPerformed() that does something if button1 is pressed & something else if button 2 is pressed.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) { clickCount++; button2.setText(Integer.toString(clickCount)); } else if (e.getSource() == button2) { clickCount--; beepAndEnd(button2,clickCount); }}
How do you turn a button off?
b.setEnabled(false);
// turn a button on button.setEnabled(true);
How do you end a program?
if(e.getSource() == quitButtonExample);
System.exit(0);
// if its 0 it is a normal exit // if its !=0 it tells the operating system something went wrong
How do you enable a GUI class to handle action events?
- import java.awt.event.
- Add implements ActionListener to the class header
- Use the addActionListener() for each button that fires an event
myButton.addActionListener(this); - Write an actionPerformed method containing the event handling code, using e.getSource to determine which event occured
How do you create a component in its own class & why is this useful?
By extending the JPanel Include extends JPanel in the class header
Useful because we can create a Panel seperate to the JFrame and then attach it to the JFrame
How do you access private variables?
Using getters & setters
What do we need for JTextField events?
A JTextField does not generate an event until a user presses ENTER.
To listen for events like this we need:
- addActionListener();
- event gets delivered to the actionPerformed();
- use getSource() to find out which textfield sent the event
- call getText() of JTextField (to find out the text that the user entered)
How do different numbers in .setLocation() change the location of the JFrame window?
Constants:
final int WIDTH = 0;
final int HEIGHT = 0;
this.setLocation(WIDTH, HEIGHT)
- The bigger the width value is, the further to the RHS of the screen it is.
- The bigger the height value is, the further down the screen the frame is.
Eg., this.setLocation(1400, 400);
and this.setSize(500,400)
The frame is in the bottom RHS corner of the screen, but this will vary depending on the size of your screen & the size of the Frame itself.
How do different numbers in .setSize change the shape of the JFrame window?
p.setSize(WIDTH, HEIGHT);
width is horizontal
height is vertical
Why does the frame still print the right size when you enter 0 for either the row or the column?
Because Java reads it as “use as many rows or columns as needed”.
What does getSource() do?
returns the object on which the Event initially occurred.
Eg., (if e.getSource() === button){ /// do something
What do you add in the main method to create a GUI and make sure it can be seen?
Example1 myGUI = new Example1(); myGUI.setVisible(true);
What does setText() do?
It lets you set the text of the thing that is calling it
Eg.,
public class void actionPerformed(ActionEvent e){
b.setText(“I was clicked”);
What import do you need for a beep?
import java.awt.Toolkit;
What does .addActionListener(this); say?
It says add the ActionListener which is this class
How do you make a beep?
Toolkit.getDefaultToolkit().beep();
That is just a better way of writing:
Toolkit tk = Toolkit.getDefaultToolkit();
tk.beep();
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
clickCount++;
button2.setText(Integer.toString(clickCount));
}
else if (e.getSource() == button2) {
// user has pressed the right button… so count down
// and beep
Toolkit.getDefaultToolkit().beep();
clickCount = 0;
//Toolkit.beep(); - cannot make a static reference to the static method beep if (clickCount > 0) { button2.setText(Integer.toString(clickCount)); } else { System.exit(0); } } }
If we click button 1, it increments button 2.
Also hear a beep everytime we click
If we click button2, it reduces the same number until it gets less than one.
What are these examples doing?
- textField1.addActionListener(parent)
- component.addActionListener(instanceOfListenerclass);
Register an instance of the event handler class as a listener on one or more components.
How do you convert a String to an integer?
int a = Integer.parseInt()
How do you convert a String to a double?
double d = Double.parseDouble(myString);
How do you convert an Integer to a String?
Integer.toString(int)
Eg.,
int clickCount = 0;
Integer.toString(clickCount);
Explain the purpose of these 2 classes?
public class Ex extends JFrame implements ActionListener {
public class ExPanel extends JPanel {
ExPanel creates a component in its own class
-passes another class as the variable to the constructor
public ExPanel(ActionListener parent) {
……creates some objects
…addActionListener();
-creates get() so another class can access the objects
Because ExPanel has created the objects, Ex can focus on the ActionListener.
-Creates a panel object globally using the constructor from the ExPanel class.
ExPanel p = new ExPanel(this);
- add this panel in the constructor & looks into this panel & looks at the components on it
add(p);
Now all that is needed is the actionPerformed(ActionEvent e).. Since the buttons, textfields etc are in a different class it will use: if(e.getSource() == p.getTextField()); ...
“Implements ActionListener” in the class name lets Java know….
It knows its expecting events from another class
Write an if statement that checks if the user’s input is “red” & if it is it sets the background colour to red, if its anything else set it to white.
if (panel.getTextField1().getText().equals("red")) panel.setBackground(Color.red); else panel.setBackground(Color.white); }
A JTextField only delivers strings from the user to the program. What do we do if we want to enter a number?
- getText() to give us it as a String
- Convert the string to a number.
int a = Integer.parseInt()
double d = Double.parseDouble(myString);
Eg.,
panel.getButton1().setText(Integer.toString(clickCount));
How do you remove white space from a String in a textField
myString.trim();
What might happen if you use:
int a = Integer.parseInt()
double d = Double.parseDouble(myString)
in a TextField?
It might throw an unchecked exception so we need to include a try/catch block.
How do we put a number into our text field?
setText(“” + num)
How do we disable a text field?
.setEditable(false)
What is the JOptionPane class used for?
(Not for this course, for masters project)!
It is used to create ‘temporary’ windows (pop up windows).
ie., error message window
Once a user has delt with the JOptionPane they disappear!
What are JOptionPane static methods?
(Not for this course, for masters project, look these up in week 7, video SwingCont 1_3).
- showMessageDialog - tell the user about something that has happened
- showConfirmDialog - ask a confirming question like yes/no/cancel
- showInputDialog - Prompt for some input
- showOptionDialog - The grand unification of the above three
What is the model view design of programming?
The Model – View – Controller style of programming is a way of deciding who does what in a GUI program in three parts:
- Model - the application logic, independent of user interaction
- View - the graphical display to the user, the components
- Controller - the code for dealing with user input, which appears as events
Why is BorderLayout useful?
Can be used as a component for another component to fill the space in the center
How would I amend it so that there was a horizontal and vertical gap of 1/2 unit
between each panel (as in Fig 5 on sheet)?
this.setLayout(new GridLayout(3,2,UNIT/2,UNIT/2));
What does this mean?
button2.addActionListener(this);
Action Listener is this class and we’re adding it to button2
If there are 2 buttons being pressed. What should you consider?
- Which button is being pressed
- If the each button is pressed, what is the outcome? It might affect the other button.
- When does the program end ie., when the counter is 0 exit.