...
Code Block |
---|
import java.awt.*;
import javax.swing.*
import java.awt.event.*;
class MyGUIApp extends JFrame {
// Use fields for GUI components that need to be referenced outside of the GUI initialization process (initGUI)
/**
* Constructor for the GUI.
*/
public MyGUIApp() {
// initialize fields here.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Causes the application to end if the GUI frame is closed.
initGUI(); // initialize the GUI components
}
/**
* Actually start the GUI
*/
public void start() {
// Do any last second initializations, if needed.
setVisible(true); // Make the GUI visible
}
/**
* Initialize the GUI components
*/
private void initGUI() {
Container contentPane = getContentPane(); // all GUI components are added to the frame's ContentPane.
// You can also just call the accessor each time as well and not use a local variable.
// instantiate, initialize and connect all the GUI's components here.
// Don't forget to add them to the container that holds them, e.g. the ContentPane.
}
/**
* Main method that starts the app.
* In general, this would not be in this class but rather in a separate "controller" class
* with slightly different coding (as required for a true Model-View-Controller system).
* We put it here for now, for simplicity's sake only.
*/
public static void main(String[] args) {
MyGUIApp view = new MyGUIApp(); // instantiate the GUI but don't show it yet.
// Model classes would be instantiated here plus any other required objects.
view.start(); // Start the application by making the GUI visible.
}
}
|
Some typical GUI initializations:
Panels in main frame:
Code Block |
---|
JPanel controlPnl = new JPanel();
contentPane.add(controlPnl, BorderLayout.NORTH); // Fixed-size panel for control components, e.g. buttons, textfields, etc, at the top of the frame.
JPanel displayPnl = new JPanel();
contentPane.add(displayPnl, BorderLayout.CENTER); // Adjustable-size panel for display components, e.g. text areas, etc, in the middle of the frame.
|
A Button with a listener on the control panel:
Code Block |
---|
JButton runBtn = new JButton("Run!");
runBtn.addActionListener(new ActionListener() {
/**
* This method runs when the button is clicked.
*/
public void actionPerformed(ActionEvent evt) {
// Do stuff
}
});
contolPnl.add(runBtn);
|
A Label and a TextField with a listener on the control panel:
Code Block |
---|
JLabel infoLbl = new JLabel();
infoLbl.setText("Enter text here:");
controlPnl.add(infoLbl);
JTextField infoTF = new TextField("default text");
infoTF.addActionListener(new ActionListener() {
/**
* This method runs when "Enter" is pressed after entering text into the text field.
*/
public void actionPerformed(ActionEvent evt) {
String text = infoTF.getText(); // the text of the text field.
// Do stuff
}
});
controlPnl.add(infoTF);
|