You are on page 1of 22

University of Technology, Jamaica

School of Computing & Information Technology


Advanced Programming (CIT3009)

The following are code for working with some of the common javax.swing 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 frame.radiobutton;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;

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");
rbtnMale.setBounds(100,50,100,30);
rbtnFemale = new JRadioButton("Female");
rbtnFemale.setBounds(100,100,100,30);
//Create a Button Group for the Radio Buttons
ButtonGroup bg = new ButtonGroup();
//Add the Radio Buttons to the Button Group
bg.add(rbtnMale);
bg.add(rbtnFemale);

button = new JButton("click");


button.setBounds(100,150,80,30);
//Add the Action Listener to the button
button.addActionListener(this);

//Add all components to the frame


this.add(rbtnMale);
this.add(rbtnFemale);
this.add(button);

this.setSize(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(rbtnMale.isSelected()){
JOptionPane.showMessageDialog(this,"Male selected.");
}
if(rbtnFemale.isSelected()){
JOptionPane.showMessageDialog(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 javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

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");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Initialize the JInternalFrame();
internalFrame = new JInternalFrame("Internal Frame", true, true,
true, true);
// set the title of the frame
internalFrame.setTitle("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
panel.add(label);
panel.add(button);
// set visibility internal frame
internalFrame.setVisible(true);
// add panel to internal frame
internalFrame.add(panel);
// add internal frame to frame
frame.add(internalFrame);
// set the size of frame
frame.setSize(300, 300);
frame.setVisible(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 java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

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();
textField.setBounds(100,50, 150,25);
label = new JLabel();
label.setBounds(50,100, 250,20);
urlLabel = new JLabel("Website URL:");
urlLabel.setBounds(25, 50, 80, 25);
button = new JButton("Find IP");
button.setBounds(50,150,95,30);

button.addActionListener(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 = textField.getText();
String ipAddress =
InetAddress.getByName(websiteAddress).getHostAddress();
label.setText("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)

System.out.println(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");
menuFile.setMnemonic(KeyEvent.VK_F);

JMenuItem menuItemOpen = new JMenuItem("Open");


menuItemOpen.setMnemonic(KeyEvent.VK_O);

KeyStroke keyStrokeToOpen =
KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK);
menuItemOpen.setAccelerator(keyStrokeToOpen);

menuItemOpen.addActionListener(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) {
System.out.println("Opening File...");
}
});

JMenuItem menuItemSave = new JMenuItem();

Action saveAction = new AbstractAction("Save") {


@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Saving...");
}
};
saveAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S);
saveAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK));

menuItemSave.setAction(saveAction);

JMenuItem menuItemExit = new JMenuItem("Exit");


menuItemExit.setMnemonic('X');

menuFile.add(menuItemOpen);
menuFile.add(menuItemSave);
menuFile.add(menuItemExit);

menuBar.add(menuFile);

setJMenuBar(menuBar);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(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 java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

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 = super.prepareRenderer(renderer,


dataRows, columns);

if (dataRows % 2 == 0) {
row.setBackground(Color.WHITE);
}else {
row.setBackground(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)) {
row.setBackground(Color.GREEN);
}
return row;

}
};
table.setPreferredScrollableViewportSize(new Dimension(450,
63));
table.setFillsViewportHeight(true);
jsp = new JScrollPane(table);
add(jsp);
}

public static void main(String[] args) {


JFrame jf = new JFrame();
JTableExample jte = new JTableExample();

jf.setTitle("JTable Example");
jf.setSize(500, 500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(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 layout.flow;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

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");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(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)

}
});
button.setSize(new Dimension(400, 30));
namePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
passwordPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

layoutComponents();
}

private void layoutComponents() {


frame.setLayout(new FlowLayout(FlowLayout.LEADING));
//Set up the first panel
namePanel.setSize(new Dimension(450, 30));
namePanel.add(usernameLabel);
namePanel.add(usernameTextField);
frame.add(namePanel); // Add the panel to the Frame
//Set up the second Panel
passwordPanel.setSize(new Dimension(450, 30));
passwordLabel.setText("Password: ");
passwordPanel.add(passwordLabel);
passwordPanel.add(passwordField);
frame.add(passwordPanel); //Add the PAnel to the Frame

buttonPanel.setSize(new Dimension(450, 30));


buttonPanel.add(button); //Add the Button to the Panel
frame.add(buttonPanel); //Add the Panel to the Frame

frame.setSize(new Dimension(420, 150));


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(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 layout.grid;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

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");
button.setSize(new Dimension(400, 30));
namePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
passwordPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

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() {


frame.setLayout(new GridLayout(3, 1, 0, 0));

namePanel.setSize(new Dimension(400, 30));


namePanel.add(usernameLabel);
namePanel.add(usernameTextField);
frame.add(namePanel);

passwordPanel.setSize(new Dimension(400, 30));


passwordLabel.setText("Password: ");
passwordPanel.add(passwordLabel);
passwordPanel.add(passwordField);
frame.add(passwordPanel);

buttonPanel.setSize(400, 30);
buttonPanel.add(button);
frame.add(buttonPanel);

frame.setSize(new Dimension(450, 150));


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(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 layout.gridbag;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

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


frame.setLayout(new GridBagLayout());

usernameLabel.setSize(150, 20); //Set size of the label


//For each component Re-Initialize the GridBag Constraints /
Settings
gbc = new GridBagConstraints();
gbc.gridx = 0; //Set which column on the X-Axis the first
component should go
gbc.gridy = 0; //Set which row on the Y-Axis the first component
should go
gbc.gridwidth = 1; //Set how many columns the component should
span
//Set where in the frame the component should be located
/anchored
gbc.anchor = GridBagConstraints.NORTHWEST;
//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
gbc.insets = new Insets(9, 10, 0, 0);
//Add the component to the frame with all it constraints
frame.add(usernameLabel, gbc);

gbc = new GridBagConstraints(); //Re-Initialize the GridBag


Constraints / Settings
gbc.gridx = 3; //Set which column on the X-Axis the first
component should go
gbc.gridy = 0; //Set which row on the Y-Axis the first component
should go
gbc.gridwidth = 3; //Set how many columns the component should
span
gbc.gridheight = 2; //Set the height of the component
gbc.ipadx = 0; //Set the internal padding for the component's
width
//Set where in the frame the component should be
located/anchored
gbc.anchor = GridBagConstraints.NORTHWEST;
//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)

gbc.insets = new Insets(11, 7, 0, 10);


//Add the component to the frame with all its settings /
constraints
frame.add(usernameTextField, gbc);

passwordLabel.setText("Password: ");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(9, 10, 0, 0);
frame.add(passwordLabel, gbc);

gbc = new GridBagConstraints();


gbc.gridx = 3;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 2;
gbc.ipadx = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(11, 7, 0, 10);
frame.add(passwordField, gbc);

gbc = new GridBagConstraints();


gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 6;
gbc.ipadx = 150;
gbc.ipady = 50;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(10, 10, 11, 0);
frame.add(button, gbc);
/**/
frame.setSize(new Dimension(450, 150));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(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 table.tablemodel;

import java.io.File;
import java.util.Date;
import javax.swing.table.AbstractTableModel;

/** * 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[] {
String.class, Long.class, Date.class,
Boolean.class, Boolean.class, Boolean.class
};
// This table model works for any one given directory
public FileTableModel(File dir) {
this.dir = dir;
this.filenames = dir.list(); // Store a list of files in the
directory
}
@Override
public int getRowCount() {
return filenames.length; // # 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(file.length());
case 2: return new Date(file.lastModified());
case 3: return file.isDirectory() ? Boolean.TRUE :
Boolean.FALSE;
case 4: return file.canRead() ? Boolean.TRUE :
Boolean.FALSE;
case 5: return file.canWrite() ? Boolean.TRUE :
Boolean.FALSE;
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) {
super.setValueAt(aValue, rowIndex, columnIndex);
}
@Override
public void fireTableCellUpdated(int row, int column) {
super.fireTableCellUpdated(row, column);
}

package table.tablemodel;

import java.io.File;
import javax.swing.JFrame;

Page 21 of 22 Prepared by:- Christopher Panther


October 21, 2020
University of Technology, Jamaica
School of Computing & Information Technology
Advanced Programming (CIT3009)

import javax.swing.JScrollPane;
import javax.swing.JTable;

public class FileTableModelDriver {

public static void main(String[] args) {


// Figure out what directory to display
File dir;
if (args.length > 0){
dir = new File(args[0]);
}
else{
dir = new File(System.getProperty("user.home"));
}
// 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");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add a JScrollPane with the table to the frame
frame.getContentPane().add(new JScrollPane(table), "Center");
frame.setSize(600, 400);
frame.setVisible(true);

Page 22 of 22 Prepared by:- Christopher Panther


October 21, 2020

You might also like