|
An Introduction to Graphical User Interface (GUI) Technology
With Examples in Java |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
JFrame
import java.awt.*;
import javax.swing.*;
/**
* An example that uses a JFrame
*
* @version 1.0
* @author Prof. David Bernstein, James Madison Univeristy
*/
public class JFrameDriver
{
/**
* The entry point of the example
*
* @param args The command line arguments
*/
public static void main(String[] args)
{
JFrame f;
f = new JFrame();
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
The "Graph Paper" Approach
null
LayoutManager
import java.awt.*;
import javax.swing.*;
/**
* An example of absolute layout with the null layout manager
*
* @version 1.0
* @author Prof. David Bernstein, James Madison Univeristy
*/
public class NullLayoutDriver
{
/**
* The entry point of the example
*
* @param args The command line arguments
*/
public static void main(String[] args)
{
Container contentPane;
JButton cancelButton, okButton;
JFrame frame;
JLabel titleLabel;
frame = new JFrame("A Really Amazing Window!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = frame.getContentPane();
contentPane.setLayout(null);
titleLabel = new JLabel("An Example of Absolute Layout");
contentPane.add(titleLabel);
titleLabel.setBounds(60,20,290,30);
okButton = new JButton("OK");
contentPane.add(okButton);
okButton.setBounds(190,210,60,30);
cancelButton = new JButton("Cancel");
contentPane.add(cancelButton);
cancelButton.setBounds(260,210,90,30);
frame.setSize(400,400);
frame.setVisible(true);
}
}
JButton ObjectsActionEvent
ActionListener
void actionPerformed(ActionEvent event)
JButton Objects (cont.)import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* An example that uses buttons
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class ButtonHandler implements ActionListener
{
private JLabel outputLabel;
/**
* Ecplicit Value Constructor.
*/
public ButtonHandler(JLabel outputLabel)
{
this.outputLabel = outputLabel;
}
/**
* Handle actionPerformed message (required by ActionListener)
*
* @param event The ActionEvent that generatedt his message
*/
public void actionPerformed(ActionEvent event)
{
String command;
command = event.getActionCommand();
if (command.equals("No"))
{
outputLabel.setText("Don't disagree with me!");
}
else if (command.equals("Yes"))
{
outputLabel.setText("I really respect your opinion.");
}
}
}
JMenuBar:
JMenuBar object and then
call its void add(JMenuItem item) methodJFrame has a
void setJMenuBar(JMenuBar bar) method