University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
The following are code for working with some of the common [Link] components.
Enter them into your code editor and compile them. Try to understand what the code is doing
in each case.
Page 1 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
Page 2 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
Page 3 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class RadioButtonExample extends JFrame
implements ActionListener{
private static final long serialVersionUID = 1L;
private JRadioButton rbtnMale;
private JRadioButton rbtnFemale;
private JButton button;
public RadioButtonExample(){
rbtnMale = new JRadioButton("Male");
[Link](100,50,100,30);
rbtnFemale = new JRadioButton("Female");
[Link](100,100,100,30);
//Create a Button Group for the Radio Buttons
ButtonGroup bg = new ButtonGroup();
//Add the Radio Buttons to the Button Group
[Link](rbtnMale);
[Link](rbtnFemale);
button = new JButton("click");
[Link](100,150,80,30);
//Add the Action Listener to the button
[Link](this);
//Add all components to the frame
[Link](rbtnMale);
[Link](rbtnFemale);
[Link](button);
[Link](300,300);
setLayout(null);
setVisible(true);
Page 4 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if([Link]()){
[Link](this,"Male selected.");
}
if([Link]()){
[Link](this,"Female selected.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}
}
Page 5 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
Page 6 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JInternalFrameExample{
private JFrame frame;
private JLabel label; // label to display text
private JInternalFrame internalFrame;
private JButton button;
private JPanel panel;
public JInternalFrameExample() {
// create a new frame to
frame = new JFrame("frame");
[Link](JFrame.EXIT_ON_CLOSE);
//Initialize the JInternalFrame();
internalFrame = new JInternalFrame("Internal Frame", true, true,
true, true);
// set the title of the frame
[Link]("InternalFrame");
// create a Button
button = new JButton("Click me");
// create a label to display text
label = new JLabel("This is a JInternal Frame ");
panel = new JPanel();
// add label and button to panel
[Link](label);
[Link](button);
// set visibility internal frame
[Link](true);
// add panel to internal frame
[Link](panel);
// add internal frame to frame
[Link](internalFrame);
// set the size of frame
[Link](300, 300);
[Link](true);
}
Page 7 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LabelExample extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JTextField textField;
private JLabel label, urlLabel;
private JButton button;
public LabelExample(){
textField = new JTextField();
[Link](100,50, 150,25);
label = new JLabel();
[Link](50,100, 250,20);
urlLabel = new JLabel("Website URL:");
[Link](25, 50, 80, 25);
button = new JButton("Find IP");
[Link](50,150,95,30);
[Link](this);
add(button);
add(textField);
add(urlLabel);
add(label);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
try{
String websiteAddress = [Link]();
String ipAddress =
[Link](websiteAddress).getHostAddress();
[Link]("IP of " + websiteAddress + " is: " + ipAddress);
}catch(Exception ex){
Page 8 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
[Link](ex);
}
}
public static void main(String[] args) {
new LabelExample();
}
}
/* ============= Program with menu bar and short cut keys ================*/
public class SwingShortcutDemo extends JFrame {
public SwingShortcutDemo() throws HeadlessException {
super("Swing Shortcuts Demo");
makeMenu();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(640, 480);
setLocationRelativeTo(null);
private void makeMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
[Link](KeyEvent.VK_F);
JMenuItem menuItemOpen = new JMenuItem("Open");
[Link](KeyEvent.VK_O);
KeyStroke keyStrokeToOpen =
[Link](KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK);
[Link](keyStrokeToOpen);
[Link](new ActionListener() {
Page 9 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
@Override
public void actionPerformed(ActionEvent evt) {
[Link]("Opening File...");
}
});
JMenuItem menuItemSave = new JMenuItem();
Action saveAction = new AbstractAction("Save") {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Saving...");
}
};
[Link](Action.MNEMONIC_KEY, KeyEvent.VK_S);
[Link](Action.ACCELERATOR_KEY,
[Link](KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK));
[Link](saveAction);
JMenuItem menuItemExit = new JMenuItem("Exit");
[Link]('X');
[Link](menuItemOpen);
[Link](menuItemSave);
[Link](menuItemExit);
[Link](menuFile);
setJMenuBar(menuBar);
}
public static void main(String[] args) {
[Link](new Runnable() {
@Override
public void run() {
new SwingShortcutDemo().setVisible(true);
}
});
}
Page 10 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
/* =================Program using a JTable ========================*/
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JTableExample extends JPanel{
private JTable table;
private JScrollPane jsp;
public JTableExample() {
String[] columns = {"Name", "Age", "Gender"};
String[][] data_rows = {
{"Chris", "45", "Male"},
{"Paula", "32", "Female"},
{"Michael", "17", "Male"},
{"Beverly", "32", "Female"}
};
table = new JTable(data_rows, columns) {
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int data_row, int columns) {
return false;
}
public Component prepareRenderer(TableCellRenderer
renderer, int dataRows, int columns) {
Component row = [Link](renderer,
dataRows, columns);
if (dataRows % 2 == 0) {
[Link]([Link]);
}else {
[Link](Color.LIGHT_GRAY);
}
Page 11 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
if (isCellSelected(dataRows, columns)) {
[Link]([Link]);
}
return row;
}
};
[Link](new Dimension(450,
63));
[Link](true);
jsp = new JScrollPane(table);
add(jsp);
}
public static void main(String[] args) {
JFrame jf = new JFrame();
JTableExample jte = new JTableExample();
[Link]("JTable Example");
[Link](500, 500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](jte);
}
Page 12 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
/* ===================== Working with Layout Managers ==================*/
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FlowLayoutExample {
//Create variables
private JFrame frame;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JTextField usernameTextField;
private JPasswordField passwordField;
private JButton button;
private JPanel namePanel;
private JPanel passwordPanel;
private JPanel buttonPanel;
public FlowLayoutExample() {
frame = new JFrame("FlowLayout Example");
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel();
usernameTextField = new JTextField(20);
passwordField = new JPasswordField(20);
button = new JButton("Sign In");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link](frame, "Sign in button
clicked...", "Flowlayout Example", JOptionPane.INFORMATION_MESSAGE);
Page 13 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
}
});
[Link](new Dimension(400, 30));
namePanel = new JPanel(new FlowLayout([Link]));
passwordPanel = new JPanel(new FlowLayout([Link]));
buttonPanel = new JPanel(new FlowLayout([Link]));
layoutComponents();
}
private void layoutComponents() {
[Link](new FlowLayout([Link]));
//Set up the first panel
[Link](new Dimension(450, 30));
[Link](usernameLabel);
[Link](usernameTextField);
[Link](namePanel); // Add the panel to the Frame
//Set up the second Panel
[Link](new Dimension(450, 30));
[Link]("Password: ");
[Link](passwordLabel);
[Link](passwordField);
[Link](passwordPanel); //Add the PAnel to the Frame
[Link](new Dimension(450, 30));
[Link](button); //Add the Button to the Panel
[Link](buttonPanel); //Add the Panel to the Frame
[Link](new Dimension(420, 150));
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Page 14 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
/* ============================ Grid Layout ========================== */
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class GridLayoutExample {
//Create variables
private JFrame frame;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JTextField usernameTextField;
private JPasswordField passwordField;
private JButton button;
private JPanel namePanel;
private JPanel passwordPanel;
private JPanel buttonPanel;
public GridLayoutExample() {
frame = new JFrame("GridLayout Example");
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel();
usernameTextField = new JTextField(20);
passwordField = new JPasswordField(20);
button = new JButton("Sign In");
[Link](new Dimension(400, 30));
namePanel = new JPanel(new FlowLayout([Link]));
passwordPanel = new JPanel(new FlowLayout([Link]));
buttonPanel = new JPanel(new FlowLayout([Link]));
layoutComponents();
}
Page 15 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
private void layoutComponents() {
[Link](new GridLayout(3, 1, 0, 0));
[Link](new Dimension(400, 30));
[Link](usernameLabel);
[Link](usernameTextField);
[Link](namePanel);
[Link](new Dimension(400, 30));
[Link]("Password: ");
[Link](passwordLabel);
[Link](passwordField);
[Link](passwordPanel);
[Link](400, 30);
[Link](button);
[Link](buttonPanel);
[Link](new Dimension(450, 150));
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Page 16 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
/* ========================== GridBag Layout ======================== */
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class GridBagLayoutExample {
//Create objects of the GUI components
private JFrame frame;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JTextField usernameTextField;
private JPasswordField passwordField;
private JButton button;
//Create an object of the GridBagConstraints / Settings
private GridBagConstraints gbc;
public GridBagLayoutExample() {
//Initialize OR Instantiate the Components
frame = new JFrame("GridBagLayout Example");
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel();
usernameTextField = new JTextField(20);
passwordField = new JPasswordField(20);
button = new JButton("Sign In");
gbc = new GridBagConstraints();
layoutComponents(); //Call method to layout the components
}
private void layoutComponents() {
Page 17 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
//Set the Layout Manager for the frame
[Link](new GridBagLayout());
[Link](150, 20); //Set size of the label
//For each component Re-Initialize the GridBag Constraints /
Settings
gbc = new GridBagConstraints();
[Link] = 0; //Set which column on the X-Axis the first
component should go
[Link] = 0; //Set which row on the Y-Axis the first component
should go
[Link] = 1; //Set how many columns the component should
span
//Set where in the frame the component should be located
/anchored
[Link] = [Link];
//The insets field specifies the external padding of the
component, the minimum
//amount of space between the component and the edges of its
display area
[Link] = new Insets(9, 10, 0, 0);
//Add the component to the frame with all it constraints
[Link](usernameLabel, gbc);
gbc = new GridBagConstraints(); //Re-Initialize the GridBag
Constraints / Settings
[Link] = 3; //Set which column on the X-Axis the first
component should go
[Link] = 0; //Set which row on the Y-Axis the first component
should go
[Link] = 3; //Set how many columns the component should
span
[Link] = 2; //Set the height of the component
[Link] = 0; //Set the internal padding for the component's
width
//Set where in the frame the component should be
located/anchored
[Link] = [Link];
//The insets field specifies the external padding of the
component, the minimum
//amount of space between the component and the edges of its
display area
Page 18 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
[Link] = new Insets(11, 7, 0, 10);
//Add the component to the frame with all its settings /
constraints
[Link](usernameTextField, gbc);
[Link]("Password: ");
gbc = new GridBagConstraints();
[Link] = 0;
[Link] = 1;
[Link] = 1;
[Link] = [Link];
[Link] = new Insets(9, 10, 0, 0);
[Link](passwordLabel, gbc);
gbc = new GridBagConstraints();
[Link] = 3;
[Link] = 1;
[Link] = 3;
[Link] = 2;
[Link] = 0;
[Link] = [Link];
[Link] = new Insets(11, 7, 0, 10);
[Link](passwordField, gbc);
gbc = new GridBagConstraints();
[Link] = 0;
[Link] = 2;
[Link] = 6;
[Link] = 150;
[Link] = 50;
[Link] = [Link];
[Link] = new Insets(10, 10, 11, 0);
[Link](button, gbc);
/**/
[Link](new Dimension(450, 150));
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Page 19 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
/* ================== Table With Table Model Example ===================== */
package [Link];
import [Link];
import [Link];
import [Link];
/** * The methods in this class allow the JTable component to get
* and display data about the files in a specified directory.
* It represents a table with six columns: filename, size, modification
date,
* plus three columns for flags: directory, readable, writable.
**/
public class FileTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
protected File dir;
protected String[] filenames;
protected String[] columnNames = new String[] {
"name", "size", "last modified", "directory?", "readable?",
"writable?"
};
protected Class<?>[] columnClasses = new Class[] {
[Link], [Link], [Link],
[Link], [Link], [Link]
};
// This table model works for any one given directory
public FileTableModel(File dir) {
[Link] = dir;
[Link] = [Link](); // Store a list of files in the
directory
}
@Override
public int getRowCount() {
return [Link]; // # of files in dir
}
@Override
public int getColumnCount() {
return 6; // A constant for this model
}
Page 20 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
File file = new File(dir, filenames[rowIndex]);
switch(columnIndex) {
case 0: return filenames[rowIndex];
case 1: return new Long([Link]());
case 2: return new Date([Link]());
case 3: return [Link]() ? [Link] :
[Link];
case 4: return [Link]() ? [Link] :
[Link];
case 5: return [Link]() ? [Link] :
[Link];
default: return null;
}
}
// Information about each column
public String getColumnName(int col) {
return columnNames[col];
}
public Class<?> getColumnClass(int col) {
return columnClasses[col];
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
[Link](aValue, rowIndex, columnIndex);
}
@Override
public void fireTableCellUpdated(int row, int column) {
[Link](row, column);
}
package [Link];
import [Link];
import [Link];
Page 21 of 22 Prepared by:- Christopher Panther
October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)
import [Link];
import [Link];
public class FileTableModelDriver {
public static void main(String[] args) {
// Figure out what directory to display
File dir;
if ([Link] > 0){
dir = new File(args[0]);
}
else{
dir = new File([Link]("[Link]"));
}
// Create a TableModel object to represent the contents of the
directory
FileTableModel model = new FileTableModel(dir);
// Create a JTable and tell it to display our model
JTable table = new JTable(model);
// Display it all in a scrolling window and make the window appear
JFrame frame = new JFrame("FileTableDemo");
[Link](JFrame.EXIT_ON_CLOSE);
// Add a JScrollPane with the table to the frame
[Link]().add(new JScrollPane(table), "Center");
[Link](600, 400);
[Link](true);
Page 22 of 22 Prepared by:- Christopher Panther
October 21, 2020