Lecture 6 - Swing Flashcards
What are 5 examples of JFrame methods?
setTitle(String)
setSize(int dimx, int dimy) - num of pixels in the x and y directions
setLocation(int x, int y) - distance of top left corner of frame from top left corner of monitor, in pixels. If you don’t include any location method, the location is automatically set to (0,0).
setVisible(boolean)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)- ensure the system exits the application when user closed the Frame
How do we create a GUI in Java swing?
- The program creates a window object (JFrame)
- The program creates several component objects (JComponents)
- Layout managers (allows children to overlap)
- Event listener objects (handles the events that arrive at each of the components).
How do we customise our own JFrame?
use inheritence ie. extends JFrame
What class do we have to import to use JFrame?
javax.swing.JFrame
What are 3 examples of layout managers?
- FlowLayout (horizontal)
- BorderLayout (content pane is divided into 5 areas)
- GridLayout(centres vertically & horizontally)
Give an example of how you could create a panel & give it a GridLayout?
JPanel myPanel = new JPanel( new GridLayout(0,1))
There are actually 2 rows 1 col, but we can add 0 because the computer will interpret it as “use however many rows are needed”.
Give an example of how you could create a panel and give it a FlowLayout
JPanel mainPanel = new JPanel(FlowLayout())
**don’t need this because FlowLayout is the deafult layout for a JPanel
Give an example of how you create a label and add it to a panel?
Global:
private JLabel label1;
Main:
label1 = new JLabel(“Click here”);
JPanel myPanel = new JPanel();
myPanel.add(label1);
Give an example of how you can create a text field and add it to a panel
Global:
private JTextField textField1;
Main: textField1 = new JTextField("initial text", 15);
JPanel p = new JPanel(); p.add(textField1);
Give an example of how you can add a button?
Global:
private JButton button1;
Main: button1 = new JButton("quit");
JPanel myPanel = new JPanel();
myPanel.add(button1);
Give an example of how to add a label with the BorderLayout() to a panel
this.add(new JLabel("NORTH"), BorderLayout.NORTH); or p.add(new JLabel("bottom"), BorderLayout.SOUTH);
Explain a JPanel
Its a generic container
Its 1 component, but can store multiple components
What is the default layout for JPanel?
FlowLayout();
What is the default layout for JFrame?
BorderLayout();
What are useful methods for JPanel?
setBackground(color)
getHeight()
getWidth()