Skip to content

Instantly share code, notes, and snippets.

@sahat
Created September 28, 2011 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sahat/1248666 to your computer and use it in GitHub Desktop.
Save sahat/1248666 to your computer and use it in GitHub Desktop.
CS221 Homework #2
import javax.swing.*;
import java.io.*;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.*;
/**
* Created by Sahat
* Class: CS221
* Date: 9/23/11
* Time: 8:11 PM
*/
public class Data {
private Date timeStamp;
private DefaultListModel model;
private FileWriter fileWriter;
private BufferedReader bufferedReader;
private String historical = "";
public Data() {
model = new DefaultListModel();
timeStamp = new Date();
}
// calculates historical average, once, during the constructor call
public void calculateHistorical() {
double total = 0;
double size = model.getSize();
for(int i=0; i<model.size(); i++) {
total += Double.parseDouble(model.getElementAt(i).toString());
}
historical = String.valueOf(total / size);
}
public void Save() {
try {
fileWriter = new FileWriter("myFile.txt");
fileWriter.write("");
for (int i=0; i<model.getSize(); i++) {
fileWriter.append(timeStamp + ": ");
fileWriter.append(model.elementAt(i) + "\n");
}
fileWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Data has been saved to file successfully.");
}
public void Load() {
try {
bufferedReader = new BufferedReader(new FileReader("myFile.txt"));
String s;
while ((s = bufferedReader.readLine()) != null) {
model.addElement(s.split(": ")[1]);
}
bufferedReader.close();
calculateHistorical();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Data has been been read successfully.");
}
public String getHistorical() {
return historical;
}
public DefaultListModel getModel() {
return model;
}
public void setModel(DefaultListModel model) {
this.model = model;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
public void setHistorical(String text) {
historical = text;
}
}
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.Array;
import java.sql.DataTruncation;
import java.util.ArrayList;
import java.util.Collections;
/**
* Created by Sahat
* Class: CS221
* Date: 9/23/11
* Time: 8:11 PM
*/
public class RadiationDataLog {
public static void main(String[] args) {
RadiationDataLogGUI frame = new RadiationDataLogGUI();
frame.setVisible(true);
}
}
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.*;
import java.util.Date;
/**
* Created by Sahat
* Class: CS221
* Date: 9/23/11
* Time: 8:11 PM
*/
public class RadiationDataLogGUI extends JFrame {
private JPanel contentPane;
private JTextField textFieldMeasurements;
private JTextField textFieldHistorical;
private ButtonGroup radioGroup;
private JButton btnHistoricalSubmit;
private JPanel panelMeasurements;
private JList listBox;
private JLabel lblHistoricalMean;
private JLabel lblHistoricalValue;
private JLabel lblStandardDeviation;
private JLabel lblMaximum;
private JLabel lblMinimum;
private JRadioButton radioManual;
private JRadioButton radioFile;
private JButton exitButton;
private JButton btmMeasurementsAdd;
private DefaultListModel listModel;
private JButton btnMeasurementsDelete;
private JScrollPane scrollPane;
private JLabel lblMinValue;
private JLabel lblMaxValue;
private JLabel lblStandardDeviationValue;
private JLabel lblMeanValue;
private JLabel lblTotalValue;
private JLabel lblMean;
private JLabel lblWarning;
private JLabel lblHistoricalBackground;
private Date timeStamp;
private Data data;
private Statistics statistics;
private NumberFormat formatter;
public RadiationDataLogGUI(){
/*
Basic configurations for the main window .
Since I'm using a "fixed" layout I've disabled ability to resize the window.
*/
setResizable(false);
setTitle("Radiation Log");
addWindowListener(new FrameListener());
setBounds(100, 100, 600, 400);
contentPane = new JPanel();
contentPane.setOpaque(false);
contentPane.setForeground(Color.white);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
/*
UIManager lets you globally chance the font style on a certain type of component,
e.g. button, label, textfield, etc...
*/
UIManager.put( "Button.font", new Font( "Courier New", Font.BOLD, 12 ));
UIManager.put( "Label.font", new Font( "Courier New", Font.BOLD, 14 ));
UIManager.put( "TextField.font", new Font( "Courier New", Font.BOLD, 14 ));
UIManager.put( "RadioButton.font", new Font( "Courier New", Font.BOLD, 14 ));
exitButton = new JButton("Exit");
exitButton.setBounds(477, 343, 117, 29);
contentPane.setLayout(null);
contentPane.add(exitButton);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exitButtonActionPerformed(e);
}
});
JPanel panelStatistics = new JPanel();
panelStatistics.setOpaque(false);
panelStatistics.setBackground(new Color(0, 0, 0, 150));
panelStatistics.setBounds(286, 6, 308, 325);
contentPane.add(panelStatistics);
panelStatistics.setLayout(null);
lblMinimum = new JLabel("Minimum:");
lblMinimum.setForeground(Color.white);
lblMinimum.setBounds(6, 81, 77, 16);
panelStatistics.add(lblMinimum);
lblMaximum = new JLabel("Maximum:");
lblMaximum.setForeground(Color.white);
lblMaximum.setBounds(6, 53, 77, 16);
panelStatistics.add(lblMaximum);
lblMean = new JLabel("Mean:");
lblMean.setForeground(Color.white);
lblMean.setBounds(6, 109, 77, 16);
panelStatistics.add(lblMean);
lblStandardDeviation = new JLabel("Std. Deviation:");
lblStandardDeviation.setForeground(Color.white);
lblStandardDeviation.setBounds(6, 137, 123, 16);
panelStatistics.add(lblStandardDeviation);
lblHistoricalMean = new JLabel("Historical Mean:");
lblHistoricalMean.setForeground(Color.white);
lblHistoricalMean.setBounds(6, 25, 153, 16);
panelStatistics.add(lblHistoricalMean);
// historical mean
lblHistoricalValue = new JLabel("0.00");
lblHistoricalValue.setForeground(Color.white);
lblHistoricalValue.setHorizontalAlignment(SwingConstants.RIGHT);
lblHistoricalValue.setBounds(152, 25, 150, 16);
panelStatistics.add(lblHistoricalValue);
// mean
lblMeanValue = new JLabel("0.00");
lblMeanValue.setForeground(Color.white);
lblMeanValue.setHorizontalAlignment(SwingConstants.RIGHT);
lblMeanValue.setBounds(152, 109, 150, 16);
panelStatistics.add(lblMeanValue);
// maximum
lblMaxValue = new JLabel("0.00");
lblMaxValue.setForeground(Color.white);
lblMaxValue.setHorizontalAlignment(SwingConstants.RIGHT);
lblMaxValue.setBounds(152, 53, 150, 16);
panelStatistics.add(lblMaxValue);
// minimum
lblMinValue = new JLabel("0.00");
lblMinValue.setForeground(Color.white);
lblMinValue.setHorizontalAlignment(SwingConstants.RIGHT);
lblMinValue.setBounds(152, 81, 150, 16);
panelStatistics.add(lblMinValue);
// standard deviation
lblStandardDeviationValue = new JLabel("0.00");
lblStandardDeviationValue.setForeground(Color.white);
lblStandardDeviationValue.setHorizontalAlignment(SwingConstants.RIGHT);
lblStandardDeviationValue.setBounds(152, 137, 150, 16);
panelStatistics.add(lblStandardDeviationValue);
/*
// date and time
lblDateValue = new JLabel("mm/dd/yy");
lblDateValue.setForeground(Color.white);
lblDateValue.setHorizontalAlignment(SwingConstants.RIGHT);
lblDateValue.setBounds(152, 165, 150, 16);
panelStatistics.add(lblDateValue);
*/
// warning message
lblWarning = new JLabel("");
lblWarning.setForeground(Color.red);
lblWarning.setHorizontalAlignment(SwingConstants.CENTER);
lblWarning.setBounds(6, 300, 296, 16);
panelStatistics.add(lblWarning);
JPanel panelHistorical = new JPanel();
panelHistorical.setOpaque(false);
panelHistorical.setBackground(new Color(0, 0, 0, 150));
panelHistorical.setBounds(6, 6, 268, 121);
contentPane.add(panelHistorical);
panelHistorical.setLayout(null);
radioGroup = new ButtonGroup();
radioManual = new JRadioButton("Manual", true);
radioManual.setForeground(Color.white);
radioManual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
radioManual(e);
}
});
radioManual.setBounds(6, 19, 125, 23);
radioGroup.add(radioManual);
panelHistorical.add(radioManual);
radioFile = new JRadioButton("Load File", false);
radioFile.setForeground(Color.white);
radioFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
radioFile(e);
}
});
radioFile.setBounds(136, 19, 126, 23);
radioGroup.add(radioFile);
panelHistorical.add(radioFile);
textFieldHistorical = new JTextField();
textFieldHistorical.setBackground(Color.black);
textFieldHistorical.setBorder(new LineBorder(new Color(153,0,255,70)));
textFieldHistorical.setCaretColor(Color.white);
textFieldHistorical.setForeground(new Color(153,0,255,255));
textFieldHistorical.setBounds(6, 82, 147, 28);
panelHistorical.add(textFieldHistorical);
textFieldHistorical.setColumns(10);
textFieldHistorical.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
historicalActionPerformed(e);
}
});
lblHistoricalBackground = new JLabel("Enter Historical Radiation Data:");
lblHistoricalBackground.setForeground(Color.white);
lblHistoricalBackground.setBounds(6, 54, 256, 16);
panelHistorical.add(lblHistoricalBackground);
btnHistoricalSubmit = new JButton("Submit");
btnHistoricalSubmit.setBounds(160, 83, 102, 29);
panelHistorical.add(btnHistoricalSubmit);
btnHistoricalSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
historicalActionPerformed(e);
}
});
panelMeasurements = new JPanel();
panelMeasurements.setBackground(new Color(0, 0, 0, 150));
panelMeasurements.setBounds(6, 138, 268, 234);
contentPane.add(panelMeasurements);
panelMeasurements.setLayout(null);
/*
DefaultListModel is inherited from a ListModel, which is sort of like an arraylist.
It has similar methods to ArrayList, but one thing I have noticed is you cannot
pass ListModel to the Collections class to get access to some useful Collections
API methods. Anyway this ListModel is my "array-like data" that gets read by the Listbox.
*/
listModel = new DefaultListModel();
listBox = new JList();
listBox.setSelectionBackground(new Color(153,0,255,200));
listBox.setModel(listModel);
listBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listBox.setSelectedIndex(0);
listBox.setVisibleRowCount(8);
listBox.setOpaque(false);
listBox.setForeground(Color.white);
listBox.setBackground(Color.black);
listBox.setFont(new Font("Courier New", Font.BOLD, 14));
listBox.setFocusable(false);
/*
In order to have a scroll bar in the listbox upon reaching 8 elements or more,
I have to pass my listbox to the scrollpane component.
*/
scrollPane = new JScrollPane(listBox);
scrollPane.setBorder(new LineBorder(new Color(153,0,255,70)));
scrollPane.setOpaque(false);
scrollPane.getViewport().setBackground(Color.black);
scrollPane.setBounds(10, 62, 136, 140);
panelMeasurements.add(scrollPane);
btnMeasurementsDelete = new JButton("Delete");
btnMeasurementsDelete.setBounds(155, 59, 100, 29);
btnMeasurementsDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonMeasurementsDeleteActionPerformed(e);
}
});
/*
I usually avoid adding any kind of logic into into the constructor, but in this
case it is necessary to decide initially whether the "Delete" button should be
enabled or disabled depending if listmodel is empty or contains some elements.
*/
if (listModel.isEmpty()) {
btnMeasurementsDelete.setEnabled(false);
}
panelMeasurements.add(btnMeasurementsDelete);
textFieldMeasurements = new JTextField();
textFieldMeasurements.setBackground(Color.black);
textFieldMeasurements.setBorder(new LineBorder(new Color(153,0,255,70)));
textFieldMeasurements.setCaretColor(Color.white);
textFieldMeasurements.setForeground(new Color(153, 0, 255, 255));
textFieldMeasurements.setBounds(6, 22, 144, 28);
textFieldMeasurements.setColumns(10);
panelMeasurements.add(textFieldMeasurements);
textFieldMeasurements.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
measurementsAddActionPerformed(e);
}
});
btmMeasurementsAdd = new JButton("Add");
btmMeasurementsAdd.setBounds(155, 23, 100, 29);
panelMeasurements.add(btmMeasurementsAdd);
// Displays the sum of all measurements in the listbox
lblTotalValue = new JLabel("0.00");
lblTotalValue.setForeground(Color.white);
lblTotalValue.setHorizontalAlignment(SwingConstants.CENTER);
lblTotalValue.setBounds(160, 100, 100, 16);
panelMeasurements.setOpaque(false);
panelMeasurements.add(lblTotalValue);
btmMeasurementsAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
measurementsAddActionPerformed(e);
}
});
addWindowFocusListener(new WindowAdapter() {
public void windowGainedFocus(WindowEvent e) {
textFieldHistorical.requestFocusInWindow();
}
});
/*
This block of code is responsible for setting radiation wallpaper
to the main panel. I am using JLabel as a conainer for the image
and then resizing it to the same size as contentPane to fill up
the entire panel. try/catch is mandatory, in case file is not found.
*/
try {
BufferedImage myPicture = ImageIO.read(new File("radiation.jpg"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
picLabel.setBounds(0,0,600,400);
contentPane.add(picLabel);
} catch (IOException e) {
e.printStackTrace();
}
timeStamp = new Date();
data = new Data();
statistics = new Statistics();
formatter = new DecimalFormat("#0.00");
}
private void buttonMeasurementsDeleteActionPerformed(ActionEvent e) {
int index = listBox.getSelectedIndex();
listModel.remove(index);
int size = listModel.getSize();
if (size == 0) {
btnMeasurementsDelete.setEnabled(false);
lblMinValue.setText("0");
lblMaxValue.setText("0");
lblMeanValue.setText("0");
lblTotalValue.setText("0");
}
else if (index == listModel.getSize()) {
index--;
}
playSound("menuwhoosh.wav");
listBox.setSelectedIndex(index);
listBox.ensureIndexIsVisible(index);
textFieldMeasurements.requestFocusInWindow();
statistics.setModel(listModel);
if (size > 0) {
lblMinValue.setText(String.valueOf(formatter.format(statistics.calculateMin())));
lblMaxValue.setText(String.valueOf(formatter.format(statistics.calculateMax())));
lblMeanValue.setText(String.valueOf(formatter.format(statistics.calculateMean())));
lblTotalValue.setText(String.valueOf(formatter.format(statistics.calculateTotal())));
lblStandardDeviationValue.setText(String.valueOf(formatter.format(statistics.calculateStdDeviation())));
}
data.setModel(listModel);
if (statistics.calculateStdDeviation() >= 2 || statistics.calculateMean() > Double.parseDouble(
data.getHistorical())*0.1 + Double.parseDouble(data.getHistorical())) {
lblWarning.setText("Alert: High radiation levels!");
playSound("prescue.wav");
}
if (statistics.calculateStdDeviation() < 2 || statistics.calculateMean() < Double.parseDouble(
data.getHistorical())*0.1 +Double.parseDouble(data.getHistorical()) ||
statistics.calculateMean() == 0) {
lblWarning.setText("");
}
}
private boolean isNumber(String n) {
try {
Double.parseDouble(n);
} catch(NumberFormatException nfe) {
return false;
}
return true;
}
private void measurementsAddActionPerformed(ActionEvent e) {
String measurement = textFieldMeasurements.getText();
if (measurement.equals("") || !(isNumber(measurement))) {
playSound("buzz.wav");
textFieldMeasurements.requestFocusInWindow();
textFieldMeasurements.selectAll();
return;
}
playSound("add.wav");
int index = listBox.getSelectedIndex();
if (index == -1) {
index = 0;
}
else {
index++;
}
listModel.addElement(textFieldMeasurements.getText());
textFieldMeasurements.setText("");
textFieldMeasurements.requestFocusInWindow();
listBox.setSelectedIndex(index);
listBox.ensureIndexIsVisible(index);
btnMeasurementsDelete.setEnabled(true);
statistics.setModel(listModel);
lblMinValue.setText(String.valueOf(formatter.format(statistics.calculateMin())));
lblMaxValue.setText(String.valueOf(formatter.format(statistics.calculateMax())));
lblMeanValue.setText(String.valueOf(formatter.format(statistics.calculateMean())));
lblTotalValue.setText(String.valueOf(formatter.format(statistics.calculateTotal())));
lblStandardDeviationValue.setText(String.valueOf(formatter.format(statistics.calculateStdDeviation())));
data.setModel(listModel);
if (statistics.calculateStdDeviation() >= 2 || statistics.calculateMean() > Double.parseDouble(
data.getHistorical())*0.1 + Double.parseDouble(data.getHistorical())) {
lblWarning.setText("Alert: High radiation levels!");
playSound("prescue.wav");
}
repaint();
}
private void historicalActionPerformed(ActionEvent e) {
String measurement = textFieldHistorical.getText();
if (measurement.equals("") || listModel.contains(measurement) || !(isNumber(measurement))) {
playSound("buzz.wav");
textFieldHistorical.requestFocusInWindow();
textFieldHistorical.selectAll();
return;
}
playSound("btnpress.wav");
textFieldMeasurements.setText("");
textFieldMeasurements.requestFocusInWindow();
textFieldHistorical.setEnabled(false);
btnHistoricalSubmit.setEnabled(false);
radioManual.setEnabled(false);
radioFile.setEnabled(false);
lblHistoricalValue.setText(textFieldHistorical.getText());
textFieldMeasurements.requestFocusInWindow();
data.setHistorical(textFieldHistorical.getText());
data.setTimeStamp(timeStamp);
}
private void radioFile(ActionEvent evt) {
data.Load();
if (listModel.getSize() > 0) {
btnMeasurementsDelete.setEnabled(true);
}
textFieldHistorical.setEnabled(false);
btnHistoricalSubmit.setEnabled(false);
radioManual.setEnabled(false);
radioFile.setEnabled(false);
textFieldMeasurements.requestFocusInWindow();
statistics.setModel(data.getModel());
lblHistoricalValue.setText(data.getHistorical());
lblMeanValue.setText("0");
lblMinValue.setText("0");
lblMaxValue.setText("0");
lblStandardDeviationValue.setText("0");
}
private void radioManual(ActionEvent evt) {
textFieldHistorical.setEnabled(true);
btnHistoricalSubmit.setEnabled(true);
textFieldHistorical.requestFocusInWindow();
}
private void exitButtonActionPerformed(ActionEvent e) {
data.Save();
System.exit(0);
}
/*
This method overrides the default behavior of the close window button
in the top right corner (top-left corner on Ubuntu and Mac).
The only reason why I am doing that is to call Save() method
to write all existing data to the file.
*/
private class FrameListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
data.Save();
System.exit(0);
}
}
/*
This method uses Clip and AudioInputStream to handle audio files. The name of the file
is passed as an argument when this method is called from button's action listener event.
*/
public static synchronized void playSound(String fileName) {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new FileInputStream(fileName));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import javax.swing.*;
import java.lang.Math;
/**
* Created by Sahat
* Class: CS221
* Date: 9/23/11
* Time: 8:11 PM
*/
public class Statistics {
ListModel model;
public Statistics() {
model = new DefaultListModel();
}
public void setModel(ListModel listModel) {
this.model = listModel;
}
public double calculateMean() {
return calculateTotal() / model.getSize();
}
public double calculateMin() {
double minValue = Double.parseDouble(model.getElementAt(0).toString());
for (int i = 1; i < model.getSize(); i++) {
if(Double.parseDouble(model.getElementAt(i).toString()) < minValue) {
minValue = Double.parseDouble(model.getElementAt(i).toString());
}
}
return minValue;
}
public double calculateMax() {
double maxValue = Double.parseDouble(model.getElementAt(0).toString());
for (int i = 1; i < model.getSize(); i++){
if(Double.parseDouble(model.getElementAt(i).toString()) > maxValue){
maxValue = Double.parseDouble(model.getElementAt(i).toString());
}
}
return maxValue;
}
public double calculateTotal() {
double total = 0;
for (int i = 0; i < model.getSize(); i++) {
total = total + Double.parseDouble(model.getElementAt(i).toString());
}
return total;
}
public double calculateStdDeviation() {
double numerator = 0;
double denominator = model.getSize();
for (int i = 0; i < model.getSize(); i++) {
numerator += Math.pow(Double.parseDouble(model.getElementAt(i).toString()) - calculateMean(), 2);
}
double standardDeviation = Math.sqrt(numerator/denominator);
return standardDeviation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment