import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Description of class TestWindow
* This version uses Composite Layout,
* can be run from the DOS prompt
* implements Action Listener,
* with an auto Timer control
* and has proper close down.
*
*/
public class TestWindow implements ActionListener
{
private int timerCount;
private Timer myTimer;
private JFrame frame;
private JLabel pictureLabel;
private JTextField field;
private JButton clickButton;
// note: the file path name below must be adjusted appropriately
private static final String PATH = "C:/Temp/Picture Quiz Images/";
// ---- swing stuff to build the frame and all its components ----
/**
* Create an ImageViewer show it on screen.
*/
public TestWindow()
{
makeFrame();
timerCount = 0;
myTimer = new Timer(3000,this);
myTimer.start();
}
/**
* Create the Swing frame and its content.
*/
private void makeFrame()
{
frame = new JFrame("Test Window");
// Set frame to close program completely when it is closed by user:
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu fileMenu = new JMenu("Select Picture");
menubar.add(fileMenu);
JMenuItem thisItem = new JMenuItem("Pic04.jpg");
thisItem.addActionListener(this);
fileMenu.add(thisItem);
JMenuItem thatItem = new JMenuItem("Pic05.jpg");
thatItem.addActionListener(this);
fileMenu.add(thatItem);
JMenuItem otherItem = new JMenuItem("Pic07.jpg");
otherItem.addActionListener(this);
fileMenu.add(otherItem);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
// not strictly necessary as BorderLayout is the default
JLabel label = new JLabel("or type file-id here:");
contentPane.add(label, BorderLayout.WEST);
field = new JTextField(15); // field sized for 15+ chars
contentPane.add(field, BorderLayout.CENTER);
pictureLabel = new JLabel();
pictureLabel.setIcon(new ImageIcon(PATH + "Pic04.jpg"));
contentPane.add(pictureLabel, BorderLayout.NORTH);
clickButton = new JButton("Change Picture");
clickButton.addActionListener(this);
contentPane.add(clickButton, BorderLayout.SOUTH);
// building is done - arrange the components and show
frame.pack();
frame.setVisible(true);
}
/*
* Invoked when an Action Event Occurs
*
*/
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == myTimer)
{ timerCount++;
if (timerCount > 9)
timerCount = 0;
changePicture("Pic0" + timerCount + ".jpg");
}
else if (event.getSource() == clickButton)
changePicture(field.getText());
else
field.setText(event.getActionCommand());
}
/*
* Change Picture
*
*/
public void changePicture(String pictureFileId)
{
pictureLabel.setIcon(new ImageIcon(PATH + pictureFileId));
}
/*
* Main to enable program to run outside of BlueJ
* Parameter will enable file to be selected
*
*/
public static void main(String[] args)
{
TestWindow tw = new TestWindow();
if (args.length == 1)
tw.changePicture(args[0]);
}
}