ArrayList Index Error - java

I am trying to finish up a project that uses a graphical User Interface to search through a data Base of geysers in the US. I keep getting an error for one of my Array Lists. I would include my data for the program but is is 10,000 entries long. Any help much appreciated. This is being done in BlueJ
Error : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
DataBase Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class GeyserDatabase
{
private ArrayList < Geyser > Geysers;
private ArrayList < Eruption > Eruptions;
public GeyserDatabase() {
Geysers = new ArrayList < Geyser >();
Eruptions = new ArrayList < Eruption >();
}
public void readGeyserData(String filename){
try{
File f = new File(filename);
Scanner sc = new Scanner(f);
String text;
// keep reading as long as there is more data
while(sc.hasNext()) {
text = sc.nextLine();
Eruption e = new Eruption(text);
Eruptions.add(e);
}
sc.close();
}
catch(IOException e) {
System.out.println("Failed to read the data file: " + filename);
}
createGeyserList();
}
public void addEruption (Eruption e){
Eruptions.add(e);
}
public ArrayList <Eruption> getEruptionList(){
return Eruptions;
}
public ArrayList <Geyser> getGeyserList(){
return Geysers;
}
public int getNumEruptions() {
return Eruptions.size();
}
public int getNumEruptions(int m,int d,int y) {
int count = 0;
for ( Eruption e : Eruptions) {
if (e.getMonth()==m && e.getDay()==d && e.getYear()==y) {
count++;
}
}
return count;
}
public Eruption getLateNightEruption() {
Eruption latestEruption = Eruptions.get(0);
int latestHour = latestEruption.getHour();
int latestMinute = latestEruption.getMinute();
for ( Eruption e: Eruptions ) {
if (e.getHour() > latestHour || (e.getHour()==latestHour && e.getMinute()>latestMinute)) {
latestEruption = e;
latestHour = e.getHour();
latestMinute = e.getMinute();
}
}
return latestEruption;
}
public ArrayList < Eruption > getEruptions(String geyser) {
ArrayList < Eruption > result = new ArrayList < Eruption > ();
for ( Eruption e: Eruptions ) {
if (e.getGeyserName().startsWith(geyser)) {
result.add(e);
}
}
return result;
}
private void createGeyserList(){
ArrayList<String>nameList = new ArrayList<String>();
// create temporary list of unique geyser names
for(Eruption e:Eruptions){
if(!nameList.contains(e.getGeyserName())){
nameList.add(e.getGeyserName());
}
}
// create a list of geysers
ArrayList<Geyser>geyserList = new ArrayList<Geyser>();
for(String s:nameList){
Geyser g = new Geyser(s);
// count number of eruptions for current geyser name
for(Eruption e:Eruptions){
if(e.getGeyserName().equals(g.getName()))
g.increment();
}
geyserList.add(g);
}
}
public int getMostGeysers(){
return Geysers.size();
}
public Geyser findMostActiveGeyser(){
Geyser MostEruptions = Geysers.get(0);
int mostActive = MostEruptions.getNumEruptions();
for( Geyser g : Geysers){
if(g.getNumEruptions() > mostActive){
MostEruptions =g;
mostActive = g.getNumEruptions();
}
}
return MostEruptions;
}
public Geyser findLeastActiveGeyser()
{
Geyser leastActiveGeyser = Geysers.get(0);
int leastActive = leastActiveGeyser.getNumEruptions();
for(Geyser g: Geysers)
{
if(g.getNumEruptions() < leastActive)
{
leastActiveGeyser = g;
leastActive = g.getNumEruptions();
}
}
return leastActiveGeyser;
}
public String findDayWithMostEruptions(int y){
int dayMost = 1;
int monthMost = 1;
int maxSoFar = getNumEruptions(1,1,y);
for(int m = 1; m<=12; m++){
for(int d = 1; d<=31;d++){
int eruptionsDay = getNumEruptions(m,d,y);
if(eruptionsDay>maxSoFar){
dayMost = d;
monthMost = m;
maxSoFar=eruptionsDay;
}
}
}
return monthMost + "/" + dayMost + "/" + y + "Eruptions: " + maxSoFar;
}
public static void main(String args[]){
GeyserDatabase gdb = new GeyserDatabase();
}
}
GUI Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.text.*;
/***********************************************************************
* GUI front end for a Yellowstone Geyser database
*
* #author Scott Grissom
* #version August 1, 2016
public class GeyserGUI extends JFrame implements ActionListener{
/** results box */
private JTextArea resultsArea;
private GeyserDatabase db;
/**JButtons */
private JButton findLateNightEruption;
private JButton findAmountOfEruptionsonDate;
private JButton findMaxEruptionsInYear;
private JButton findGeyserByName;
private JButton findMostActiveGeyser;
private JButton findLeastActiveGeyser;
private JButton getGeyserList;
private JTextField month;
private JTextField day;
private JTextField Year;
private JTextField geyser;
/** menu items */
private JMenuBar menus;
private JMenu fileMenu;
private JMenu reportsMenu;
private JMenuItem quitItem;
private JMenuItem openItem;
private JMenuItem countItem;
private JMenuItem geyserItem;
/*********************************************************************
Main Method
*********************************************************************/
public static void main(String arg[]){
GeyserGUI gui = new GeyserGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Yellowstone Geysers");
gui.pack();
gui.setVisible(true);
}
/*********************************************************************
Constructor - instantiates and displays all of the GUI commponents
*********************************************************************/
public GeyserGUI(){
db = new GeyserDatabase();
// FIX ME: the following line should be removed
db.readGeyserData("GeyserData.txt");
// create the Gridbag layout
setLayout(new GridBagLayout());
GridBagConstraints position = new GridBagConstraints();
// create the Results Text Area (5 x 10 cells)
resultsArea = new JTextArea(20,40);
JScrollPane scrollPane = new JScrollPane(resultsArea);
position.gridx = 0;
position.gridy = 0;
position.gridheight = 10;
position.gridwidth = 5;
position.insets = new Insets(20,20,0,0);
add(scrollPane, position);
/*******************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 0;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Month"), position);
position = new GridBagConstraints();
position.gridx = 0;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
month = new JTextField(2);
add(month, position);
/*************************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 1;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Day"), position);
position = new GridBagConstraints();
position.gridx = 1;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
day = new JTextField(2);
add(day, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 2;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Year"), position);
position = new GridBagConstraints();
position.gridx = 2;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
Year = new JTextField(4);
add(Year, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 3;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Geyser"), position);
position = new GridBagConstraints();
position.gridx = 3;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
geyser = new JTextField(12);
add(geyser, position);
/*********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 0;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Eruptions"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 1;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLateNightEruption = new JButton("Late Night Eruption");
findLateNightEruption.addActionListener(this);
add(findLateNightEruption, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 2;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findAmountOfEruptionsonDate = new JButton("# On Date");
findAmountOfEruptionsonDate.addActionListener(this);
add(findAmountOfEruptionsonDate, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 3;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMaxEruptionsInYear = new JButton("Max Eruptions in Year");
findMaxEruptionsInYear.addActionListener(this);
add(findMaxEruptionsInYear, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 4;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findGeyserByName = new JButton("By Name");
findGeyserByName.addActionListener(this);
add(findGeyserByName, position);
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 5;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Geysers"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 6;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMostActiveGeyser = new JButton("Most Active");
findMostActiveGeyser.addActionListener(this);
add(findMostActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 7;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLeastActiveGeyser = new JButton("Least Active");
findLeastActiveGeyser.addActionListener(this);
add(findLeastActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 8;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
getGeyserList = new JButton("Geyser List");
getGeyserList.addActionListener(this);
add(getGeyserList, position);
// set up File menus
setupMenus();
pack();
}
/*********************************************************************
List all entries given an ArrayList of eruptions. Include a final
line with the number of eruptions listed
#param m list of eruptions
*********************************************************************/
private void displayEruptions(ArrayList <Eruption> m){
resultsArea.setText("");
for(Eruption e: m){
resultsArea.append("\n" + e.toString());
}
resultsArea.append ("\nNumber of Geysers: " + m.size());
}
/*********************************************************************
Respond to menu selections and button clicks
#param e the button or menu item that was selected
*********************************************************************/
public void actionPerformed(ActionEvent e){
Eruption item = null;
// either open a file or warn the user
if (e.getSource() == openItem){
openFile();
}else if(db.getNumEruptions() == 0){
String errorMessage = "Did you forget to open a file?";
resultsArea.setText(errorMessage);
return;
}
// menu item - quit
else if (e.getSource() == quitItem){
System.exit(1);
}
// FIX ME: Count menu item - display number of eruptions and geysers
else if (e.getSource() == countItem){
resultsArea.setText("\nNumber of Eruptions: " + db.getNumEruptions());
}
// FIX ME: display late night eruption
else if (e.getSource() == findLateNightEruption){
resultsArea.setText("Latest Eruption\n" + db.getLateNightEruption());
}
//FIX ME: display all geyser names
else if (e.getSource() == getGeyserList){
displayEruptions(db.getEruptionList());
}
//FIX ME: max eruptions day in a year (check for year)
else if(e.getSource() == findMaxEruptionsInYear){
String aux = Year.getText();
if(aux.length() == 0){
JOptionPane.showMessageDialog(this, "Enter a Year to Search For Maax Eruptions");
}
else
{
int y = Integer.parseInt(Year.getText());
String result = db.findDayWithMostEruptions(y);
resultsArea.setText(result);
}
}
// FIX ME: list all eruptions for a geyser (check for name)
else if(e.getSource() == findGeyserByName){
String name = geyser.getText();
if(name.length() == 0){
JOptionPane.showMessageDialog(this, "Provide Name");
}
else
{
ArrayList<Eruption>result = db.getEruptions(name);
displayEruptions(result);
}
}
// FIX ME: display eruptions for a particular date
else if(e.getSource()==findAmountOfEruptionsonDate){
String aux1 = Year.getText();
String aux2 = month.getText();
String aux3 = day.getText();
if(aux1.length() == 0 || aux2.length() == 0 || aux3.length() == 0)
{
JOptionPane.showMessageDialog(this, "Provide year,month, and day");
}
else
{
int y = Integer.parseInt(Year.getText());
int m = Integer.parseInt(month.getText());
int d = Integer.parseInt(day.getText());
int result = db.getNumEruptions(m, d, y);
resultsArea.setText("Number of Eruptions: " + result);
}
}
else if(e.getSource() == findMostActiveGeyser){
resultsArea.setText("Most active Geyser: " + db.findMostActiveGeyser());
}
else if(e.getSource() == findLeastActiveGeyser){
resultsArea.setText("Least active Geyser: " + db.findLeastActiveGeyser());
}
}
/*********************************************************************
In response to the menu selection - open a data file
*********************************************************************/
private void openFile(){
JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
int returnVal = fc.showOpenDialog(this);
// did the user select a file?
if (returnVal == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
// use the name of your lottery ticket variable
db.readGeyserData(filename);
}
}
/*********************************************************************
Create a custom gridbag constraint
*********************************************************************/
private GridBagConstraints makeConstraints(int x, int y, int h, int w, int align){
GridBagConstraints rtn = new GridBagConstraints();
rtn.gridx = x;
rtn.gridy = y;
rtn.gridheight = h;
rtn.gridwidth = w;
// set alignment: LINE_START, CENTER, LINE_END
rtn.anchor = align;
return rtn;
}
/*********************************************************************
Set up the menu items
*********************************************************************/
private void setupMenus(){
// create menu components
fileMenu = new JMenu("File");
quitItem = new JMenuItem("Quit");
openItem = new JMenuItem("Open...");
reportsMenu = new JMenu("Reports");
countItem = new JMenuItem("Counts");
// assign action listeners
quitItem.addActionListener(this);
openItem.addActionListener(this);
countItem.addActionListener(this);
// display menu components
fileMenu.add(openItem);
fileMenu.add(quitItem);
reportsMenu.add(countItem);
menus = new JMenuBar();
menus.add(fileMenu);
menus.add(reportsMenu);
setJMenuBar(menus);
}
}
Geyser Code:
import java.util.Scanner;
public class Geyser
{
String geyserName;
int count = 0;
public Geyser (String name){
geyserName = name;
}
public void increment (){
count++;
}
public String getName() {
return geyserName;
}
public int getNumEruptions() {
return count;
}
public static void main(String args[]) {
Geyser g = new Geyser("xyz");
if (g.getName().equals("xyz")) {
System.out.println("getName worked well.");
}
else {
System.out.println("getName did not work well.");
}
if (g.getNumEruptions() == 0) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
g.increment();
if (g.getNumEruptions() == 1) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
}
}
Eruption Code:
import java.util.Scanner;
public class Eruption
{
int month;
int day;
int year;
int hour;
int minute;
String geyserName;
public Eruption(String info){
Scanner scnr = new Scanner(info);
scnr.useDelimiter("/|,|:");
month = scnr.nextInt();
day = scnr.nextInt();
year = scnr.nextInt();
geyserName = scnr.next();
hour = scnr.nextInt();
minute = scnr.nextInt();
}
public int getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year;
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public String getGeyserName(){
return geyserName;
}
public String toString( ){
String geyserString = geyserName + " " + "on" + month +"/"+ day +"/" + year + "at" + hour +":"+ minute;
return geyserString;
}
public static void main(String [] args){
Eruption e = new Eruption("1/2/2016,Old Faithful,10:46");
if (e.getMonth() == 1) {
System.out.println("getMonth worked well");
}
}
}

Related

Why doesn't my find method work here even with all the values saved on the array?

I am fairly new to programming and I cant seem to find the problem in the area where I make the program search for the specific key term tho it's saved in the array.
here is the code where I add the details of the customer:
private void addCustomerToSeat(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Button[] seat = new Button[(SEATING_CAPACITY + 1)];
Button selectSeat = new Button(" Click to Book Seats ");
selectSeat.setLayoutX(320);
selectSeat.setLayoutY(512);
selectSeat.setOnAction(event -> {
window.setScene(scene2);
});
Label header = new Label("TRAIN BOOKING SYSTEM");
header.setLayoutX(250);
header.setLayoutY(30);
header.setStyle("-fx-font-size: 25px;");
Label clientName = new Label("Enter Customer Name: ");
clientName.setLayoutX(225);
clientName.setLayoutY(150);
clientName.setStyle("-fx-font-size: 16px;");
TextField cusName = new TextField();
cusName.setLayoutX(397);
cusName.setLayoutY(150);
Label destination = new Label("Choose destination: ");
destination.setLayoutX(225);
destination.setLayoutY(200);
destination.setStyle("-fx-font-size:16px;");
String [] destinations = {"Colombo to Badulla", "Badulla to Colombo"};
ComboBox Destination = new ComboBox(FXCollections.observableArrayList(destinations));
Destination.setLayoutX(397);
Destination.setLayoutY(200);
Label date = new Label("Select date:");
date.setLayoutY(275);
date.setLayoutX(225);
date.setStyle("-fx-font-size:16px;");
DatePicker datePicker = new DatePicker();
LocalDate now = LocalDate.now();
datePicker.setValue(now);
datePicker.setLayoutX(397);
datePicker.setLayoutY(275);
AnchorPane layout1 = new AnchorPane();
layout1.setStyle("-fx-background-color:#5a89a3; ");
layout1.getChildren().addAll(Destination,destination,selectSeat,clientName,cusName,header,date,datePicker);
scene1 = new Scene(layout1,800,600);
window.setTitle("Train Booking System");
window.setScene(scene1);
window.show();
Label header1 = new Label("TRAIN BOOKING SYSTEM");
header1.setLayoutX(250);
header1.setLayoutY(30);
header1.setStyle("-fx-font-size: 25px;");
Button submit = new Button("Submit");
submit.setLayoutX(640);
submit.setLayoutY(480);
Button exit = new Button("Exit");
exit.setLayoutX(710);
exit.setLayoutY(480);
exit.setOnAction(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
Label greenSeat = new Label("Unbooked Seat");
greenSeat.setLayoutY(160);
greenSeat.setLayoutX(590);
greenSeat.setStyle("-fx-font-size:14px;");
Button unbooked = new Button(" ");
unbooked.setLayoutY(160);
unbooked.setLayoutX(560);
unbooked.setStyle("-fx-background-color:green;");
Label redSeat = new Label("Booked Seat");
redSeat.setLayoutX(590);
redSeat.setLayoutY(200);
redSeat.setStyle("-fx-font-size:14px;");
Button booked = new Button(" ");
booked.setLayoutX(560);
booked.setLayoutY(200);
booked.setStyle("-fx-background-color:red;");
GridPane gridPane = new GridPane();
int columnIndex = 0;
int rowIndex = 0;
int rowIndexes = 0;
int[] reservedSeats = new int[1];
String seatNumber;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++) {
if (i <= 9) {
seatNumber = "0" + (i);
} else {
seatNumber = "" + (i);
}
seat[i] = new Button(seatNumber);
gridPane.add(seat[i], columnIndex, rowIndex);
columnIndex++;
rowIndexes++;
if (rowIndexes == 4) {
columnIndex = 0;
rowIndexes = 0;
rowIndex++;
}
}
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
if (seatBooking[f].equals("Empty")) {
seat[f].setStyle("-fx-background-color: green;");
}
if (seatBooking[f].equals("booked")) {
seat[f].setStyle("-fx-background-color: red");
}
}
List<Integer> bookedCurrent = new ArrayList<>();
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
int finalF = f;
seat[f].setOnAction(event -> {
seat[finalF].setStyle("-fx-background-color: red");
seatBooking[finalF] = "booked";
bookedCurrent.add(finalF);
});
submit.setOnAction(event -> {
String personName = cusName.getText();
personName = personName.toLowerCase();
window.close();
for ( int loopSeatArray = 1; loopSeatArray< (SEATING_CAPACITY + 1); loopSeatArray++) {
if (loopSeatArray == reservedSeats[0]) {
seatBooking[loopSeatArray] = "Booked";
customerName[loopSeatArray] = personName;
}
seatBookingAndCustomerName[loopSeatArray] = seatBooking[loopSeatArray];
}
for (int total = 43; total < (SEATING_CAPACITY + 1); total++){
seatBookingAndCustomerName[total]= customerName[total-42]; }
displayMenu(seatBooking, customerName, seatBookingAndCustomerName);
});
}
gridPane.setLayoutX(160);
gridPane.setLayoutY(80);
gridPane.setHgap(20);
gridPane.setVgap(5);
AnchorPane layout2 = new AnchorPane();
layout2.setStyle("-fx-background-color:#5a89a3; ");
layout2.getChildren().addAll(gridPane,submit,exit,header1,greenSeat,unbooked,redSeat,booked);
scene2 = new Scene(layout2,800,600);
window.setTitle("Train Booking System");
window.show();
window.setOnCloseRequest(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
}
and here is the part of the code where I prompt the user for the name and find the location of given name:
private void findCustomerSeats(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter customer name: ");
String name = input.nextLine();
boolean flag = false;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++){
if (name.toLowerCase().equals(customerName[i])){
System.out.println("Seats booked are: " + seatBooking);
flag = true;
}
}
if (flag !=true){
System.out.println(name + " has not reserved a seat");
}
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
}
when the above code is run, and when I input the name, it plain out does not work.
One potential issue, your for loop is starting at index 1, I would begin by using something like this:
for (int idx = 0; idx < customerName.length; idx++) {
//This way you will not check an index of your array that does not exist
//which could cause a NullPointerException
//Additionally, this is useful if you want to grow your customerName array
}
Another useful tip, that I use all the time. Try printing out more information and see if you can spot the issue. This might seem trivial but I have found it extremely helpful. For example:
System.out.println("Inputted Name: " + name);
for (int idx = 0; idx < customerName.length; idx++) {
System.out.println("Does " + name.toLowerCase() + " = " + customerName[idx] + " ?");
}

JRadioButton Java GUI

JButton calculateBtn = new JButton("Calculate");
calculateBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int iStart, fRate, gen;
try {
iStart = Integer.parseInt(startText.getText());
fRate = Integer.parseInt(fixedText.getText());
gen = Integer.parseInt(genText.getText());
if(FixedRad.isSelected()) {
for(int a = 0; a < gen; a++) {
iStart += iStart*fRate/100;
}
} else {
int vara, varb, varc, vard, vare, varf, varg, varh, vari, varj;
vara = Integer.parseInt(var1.getText());
varb = Integer.parseInt(var2.getText());
varc = Integer.parseInt(var3.getText());
vard = Integer.parseInt(var4.getText());
vare = Integer.parseInt(var5.getText());
varf = Integer.parseInt(var6.getText());
varg = Integer.parseInt(var7.getText());
varh = Integer.parseInt(var8.getText());
vari = Integer.parseInt(var9.getText());
varj = Integer.parseInt(var10.getText());
int[] iaGrowthRate = {vara, varb, varc, vard, vare, varf, varg, varh, vari, varj};
for( int a = 0; a < 10; a++) {
iStart += iStart*iaGrowthRate[a]/100;
}
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "Plese enter a Valid Number");
}
}
});
The first button works perfectly (FixedRad) but when I try with the Variable Button selected it does not work and the message "Please enter a valid number appears"
Thanks!

How to use the 'svm_toy' Applet example in LibSVM?

I'm using LIBSVM. In the download package is a svm_toy.java file. I could not find out how it works. Here is the source code:
import libsvm.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
/**
* SVM package
* #author unknown
*
*/
public class svm_toy extends Applet {
static final String DEFAULT_PARAM="-t 2 -c 100";
int XLEN;
int YLEN;
// off-screen buffer
Image buffer;
Graphics buffer_gc;
// pre-allocated colors
final static Color colors[] =
{
new Color(0,0,0),
new Color(0,120,120),
new Color(120,120,0),
new Color(120,0,120),
new Color(0,200,200),
new Color(200,200,0),
new Color(200,0,200)
};
class point {
point(double x, double y, byte value)
{
this.x = x;
this.y = y;
this.value = value;
}
double x, y;
byte value;
}
Vector<point> point_list = new Vector<point>();
byte current_value = 1;
public void init()
{
setSize(getSize());
final Button button_change = new Button("Change");
Button button_run = new Button("Run");
Button button_clear = new Button("Clear");
Button button_save = new Button("Save");
Button button_load = new Button("Load");
final TextField input_line = new TextField(DEFAULT_PARAM);
BorderLayout layout = new BorderLayout();
this.setLayout(layout);
Panel p = new Panel();
GridBagLayout gridbag = new GridBagLayout();
p.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridwidth = 1;
gridbag.setConstraints(button_change,c);
gridbag.setConstraints(button_run,c);
gridbag.setConstraints(button_clear,c);
gridbag.setConstraints(button_save,c);
gridbag.setConstraints(button_load,c);
c.weightx = 5;
c.gridwidth = 5;
gridbag.setConstraints(input_line,c);
button_change.setBackground(colors[current_value]);
p.add(button_change);
p.add(button_run);
p.add(button_clear);
p.add(button_save);
p.add(button_load);
p.add(input_line);
this.add(p,BorderLayout.SOUTH);
button_change.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_change_clicked(); button_change.setBackground(colors[current_value]); }});
button_run.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
button_clear.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_clear_clicked(); }});
button_save.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_save_clicked(input_line.getText()); }});
button_load.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_load_clicked(); }});
input_line.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
this.enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
void draw_point(point p)
{
Color c = colors[p.value+3];
Graphics window_gc = getGraphics();
buffer_gc.setColor(c);
buffer_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
window_gc.setColor(c);
window_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
}
void clear_all()
{
point_list.removeAllElements();
if(buffer != null)
{
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
repaint();
}
void draw_all_points()
{
int n = point_list.size();
for(int i=0;i<n;i++)
draw_point(point_list.elementAt(i));
}
void button_change_clicked()
{
++current_value;
if(current_value > 3) current_value = 1;
}
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
void button_run_clicked(String args)
{
// guard
if(point_list.isEmpty()) return;
svm_parameter param = new svm_parameter();
// default values
param.svm_type = svm_parameter.C_SVC;
param.kernel_type = svm_parameter.RBF;
param.degree = 3;
param.gamma = 0;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 40;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = new int[0];
param.weight = new double[0];
// parse options
StringTokenizer st = new StringTokenizer(args);
String[] argv = new String[st.countTokens()];
for(int i=0;i<argv.length;i++)
argv[i] = st.nextToken();
for(int i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
if(++i>=argv.length)
{
System.err.print("unknown option\n");
break;
}
switch(argv[i-1].charAt(1))
{
case 's':
param.svm_type = atoi(argv[i]);
break;
case 't':
param.kernel_type = atoi(argv[i]);
break;
case 'd':
param.degree = atoi(argv[i]);
break;
case 'g':
param.gamma = atof(argv[i]);
break;
case 'r':
param.coef0 = atof(argv[i]);
break;
case 'n':
param.nu = atof(argv[i]);
break;
case 'm':
param.cache_size = atof(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'p':
param.p = atof(argv[i]);
break;
case 'h':
param.shrinking = atoi(argv[i]);
break;
case 'b':
param.probability = atoi(argv[i]);
break;
case 'w':
++param.nr_weight;
{
int[] old = param.weight_label;
param.weight_label = new int[param.nr_weight];
System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);
}
{
double[] old = param.weight;
param.weight = new double[param.nr_weight];
System.arraycopy(old,0,param.weight,0,param.nr_weight-1);
}
param.weight_label[param.nr_weight-1] = atoi(argv[i-1].substring(2));
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
default:
System.err.print("unknown option\n");
}
}
// build problem
svm_problem prob = new svm_problem();
prob.l = point_list.size();
prob.y = new double[prob.l];
if(param.kernel_type == svm_parameter.PRECOMPUTED)
{
}
else if(param.svm_type == svm_parameter.EPSILON_SVR ||
param.svm_type == svm_parameter.NU_SVR)
{
if(param.gamma == 0) param.gamma = 1;
prob.x = new svm_node[prob.l][1];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.y[i] = p.y;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[1];
x[0] = new svm_node();
x[0].index = 1;
int[] j = new int[XLEN];
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
{
x[0].value = (double) i / XLEN;
j[i] = (int)(YLEN*svm.svm_predict(model, x));
}
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(0,0,0,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(0,0,0,YLEN-1);
int p = (int)(param.p * YLEN);
for(int i=1;i<XLEN;i++)
{
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(i,0,i,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(i,0,i,YLEN-1);
buffer_gc.setColor(colors[5]);
window_gc.setColor(colors[5]);
buffer_gc.drawLine(i-1,j[i-1],i,j[i]);
window_gc.drawLine(i-1,j[i-1],i,j[i]);
if(param.svm_type == svm_parameter.EPSILON_SVR)
{
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
window_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
window_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
}
}
}
else
{
if(param.gamma == 0) param.gamma = 0.5;
prob.x = new svm_node [prob.l][2];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.x[i][1] = new svm_node();
prob.x[i][1].index = 2;
prob.x[i][1].value = p.y;
prob.y[i] = p.value;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[2];
x[0] = new svm_node();
x[1] = new svm_node();
x[0].index = 1;
x[1].index = 2;
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
for (int j = 0; j < YLEN ; j++) {
x[0].value = (double) i / XLEN;
x[1].value = (double) j / YLEN;
double d = svm.svm_predict(model, x);
if (param.svm_type == svm_parameter.ONE_CLASS && d<0) d=2;
buffer_gc.setColor(colors[(int)d]);
window_gc.setColor(colors[(int)d]);
buffer_gc.drawLine(i,j,i,j);
window_gc.drawLine(i,j,i,j);
}
}
draw_all_points();
}
void button_clear_clicked()
{
clear_all();
}
void button_save_clicked(String args)
{
FileDialog dialog = new FileDialog(new Frame(),"Save",FileDialog.SAVE);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
try {
DataOutputStream fp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
int svm_type = svm_parameter.C_SVC;
int svm_type_idx = args.indexOf("-s ");
if(svm_type_idx != -1)
{
StringTokenizer svm_str_st = new StringTokenizer(args.substring(svm_type_idx+2).trim());
svm_type = atoi(svm_str_st.nextToken());
}
int n = point_list.size();
if(svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.y+" 1:"+p.x+"\n");
}
}
else
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.value+" 1:"+p.x+" 2:"+p.y+"\n");
}
}
fp.close();
} catch (IOException e) { System.err.print(e); }
}
void button_load_clicked()
{
FileDialog dialog = new FileDialog(new Frame(),"Load",FileDialog.LOAD);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
clear_all();
try {
BufferedReader fp = new BufferedReader(new FileReader(filename));
String line;
while((line = fp.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
if(st.countTokens() == 5)
{
byte value = (byte)atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x,y,value));
}
else if(st.countTokens() == 3)
{
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x,y,current_value));
}else
break;
}
fp.close();
} catch (IOException e) { System.err.print(e); }
draw_all_points();
}
protected void processMouseEvent(MouseEvent e)
{
if(e.getID() == MouseEvent.MOUSE_PRESSED)
{
if(e.getX() >= XLEN || e.getY() >= YLEN) return;
point p = new point((double)e.getX()/XLEN,
(double)e.getY()/YLEN,
current_value);
point_list.addElement(p);
draw_point(p);
}
}
public void paint(Graphics g)
{
// create buffer first time
if(buffer == null) {
buffer = this.createImage(XLEN,YLEN);
buffer_gc = buffer.getGraphics();
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
g.drawImage(buffer,0,0,this);
}
public Dimension getPreferredSize() { return new Dimension(XLEN,YLEN+50); }
public void setSize(Dimension d) { setSize(d.width,d.height); }
public void setSize(int w,int h) {
super.setSize(w,h);
XLEN = w;
YLEN = h-50;
clear_all();
}
public static void main(String[] argv)
{
new AppletFrame("svm_toy",new svm_toy(),500,500+50);
}
}
class AppletFrame extends Frame {
AppletFrame(String title, Applet applet, int width, int height)
{
super(title);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
applet.init();
applet.setSize(width,height);
applet.start();
this.add(applet);
this.pack();
this.setVisible(true);
}
}
Could someone give me an example or explanation? I also would like to scale my training data. Where is the right place to scale?
Thanks
SVM-Toy
SVM Toy is - as the name suggests - a simple toy build by the LIBSVM dev team and is not recommended for "productive" visualization of the SVM's decision boundary.
Moreover looking into the source-code of svm_toy it becomes clear, that this tool only supports 2D vectors.
Relevant code fragment is taken from the button_load_clicked() Method:
while ((line = fp.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
if (st.countTokens() == 5) {
byte value = (byte) atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x, y, value));
} else if (st.countTokens() == 3) {
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x, y, current_value));
} else {
break;
}
}
As you can see, the svm_toy implementation can only handle 2D vectors, which means it only supports vectors, which were constructed out of two features.
That means, you can only read and display files which are build from only two features like for example the fourclass dataset provided by the LIBSVM authors. However it seems, that this feature is not supported within this implementation.
I think, that the tool is designed for interactive visualization. You are able to change the color and click on the black application screen. After you set some points (each color representing an own class), you can click "run" and the decision boundary is displayed.
Displaying the desicion boundary in an high dimensional vector space is even nearly impossible. I would recommend to not use this tool implementation for any productive / scientific purpose.
Scaling
Scaling of your training data should be done after you transformed it into it's numeric representation and before you are going forward to train your SVM with this data.
In short that means, you have to do the following steps before using svm_train
Construct the numeric representation for each data point (with the help of feature selection, ...)
Analyse the resulting numeric representation for each data point
Scale your data for example to [-1,1]
Go ahead and train your SVM model. Note well, that you have to repeat 1-3 for predicting unknown data points. The only difference is, that you already know the necessary features, so there is no need for feature selection.

How to browse a file one folder to other folder and check size or dimenction copy it to another location

I have one Jtextfield and two Jbutton one button for browse image and other for copy image. first of all i want click on browse button then select a image then full path and image name show in text field then i click on upload button and image copy in specific folder.
Use file object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Register extends JFrame implements ActionListener
{
JTextField pro_pic_text;
JLabel pro_pic_lbl;
JButton browse_btn,upload_btn;
public Register()
{
setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.insets = new Insets(5,3,5,3);
pro_pic_lbl = new JLabel("Profile Picture :");
gbc1.gridx = 0;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(pro_pic_lbl,gbc1);
pro_pic_text = new JTextField(30);
pro_pic_text.setEditable(false);
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 3;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(pro_pic_text,gbc1);
browse_btn = new JButton("Browse...");
browse_btn.addActionListener(this);
gbc1.gridx = 4;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.NONE;
gbc1.anchor = GridBagConstraints.WEST;
add(browse_btn,gbc1);
upload_btn = new JButton("Upload");
upload_btn.addActionListener(this);
gbc1.gridx = 5;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.NONE;
gbc1.anchor = GridBagConstraints.WEST;
add(upload_btn,gbc1);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == browse_btn)
{
FileDialog fd = new FileDialog(new LibrarySystem(), "Choose Profile Picture",FileDialog.LOAD);
fd.show();
if(fd.getFile()==null&&pro_pic_text.getText().toString().trim().equals(""))
{
JOptionPane.showMessageDialog(this,"Choose your Profile Picrure","Warning",JOptionPane.WARNING_MESSAGE);
}
else
{
File ff1 = new File(fd.getFile());
String ffname = ff1.getName();
int aa = ffname.indexOf(".");
fftype = ffname.substring(aa+1);
if(fftype.equals("png") || fftype.equals("PNG") || fftype.equals("JPEG") || fftype.equals("jpeg") || fftype.equals("JPG") || fftype.equals("jpg"))
{
fileName = fd.getDirectory() + fd.getFile();
File ff2 = new File(fileName);
if(ff2.length()<=51300)
{
pro_pic_text.setText(fileName);
}
else
{
JOptionPane.showMessageDialog(this,"File size larger then 50kb not allowed","Warning",JOptionPane.WARNING_MESSAGE);
pro_pic_text.setText("");
}
}
else
{
JOptionPane.showMessageDialog(this,"Choose JPEG, JPG or PNG File","Warning",JOptionPane.WARNING_MESSAGE);
pro_pic_text.setText("");
}
}
}
else if(ae.getSource() == upload_btn)
{
pro_pic = pro_pic_text.getText().toString().trim();
if(pro_pic.equals(""))
{
JOptionPane.showMessageDialog(this,"First Choose your Profile Picrure","Warning",JOptionPane.WARNING_MESSAGE);
}
else
{
String cpro_pic = "src/profile pic/"+ffname+"."+fftype;
File ff1 = new File(pro_pic);
File ff2 = new File(cpro_pic);
iscopy = ff1.renameTo(ff2);
if(iscopy)
{
pro_pic_text.setText(cpro_pic);
}
else
{
JOptionPane.showMessageDialog(this,"Error in Photo Upload..!","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
use this
should be work

How can I get my java chat client and server to exchange messages from a textfield

I'm writing a chat program in Java using a GUI that looks like this
The idea is to start the server on one computer and the client on another (or multiple) (I'm currently just running both on the same computer). After a server is started, a client enters the host number and port number and hits connect. All of this is working so far. Once connected, either the user or the server can type in the textField and hit Send, and the message can be sent to the server, and the server sends the message to all clients.
my question is: How can I send text from the clients to the server and vice-versa?
I'm having trouble grasping how this would work. The server sits in a while loop and waits for more connections (all which work), so I don't know how it can accept text and then push it back.
Here's the entire program so you can compile it and see the problems I'm having:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.io.PrintWriter;
import java.util.Scanner;
public class Chat extends Frame implements Runnable, WindowListener, ActionListener, ItemListener
{
int port = 44004;
String host = "127.0.0.1";
//GUI objects
TextField ipAddressField = new TextField();
TextField portField = new TextField(""+port);
TextField hostField = new TextField(host);
TextField inputBox = new TextField();
static TextArea conversationBox = new TextArea();
Button startServerButton = new Button("Start Server");
Button sendButton = new Button("Send");
Button changeHost = new Button("Change Host");
Button changePort = new Button("Change Port");
Button connectButton = new Button("Connect");
Button disconnectButton = new Button("Disconnect");
Label hostLabel = new Label("Host:");
Label portLabel = new Label("Port:");
MenuBar mb = new MenuBar();
Menu colorMenu = new Menu("Color");
CheckboxMenuItem redItem = new CheckboxMenuItem("Red");
CheckboxMenuItem blueItem = new CheckboxMenuItem("Blue");
CheckboxMenuItem orangeItem = new CheckboxMenuItem("Orange");
CheckboxMenuItem blackItem = new CheckboxMenuItem("Black");
//runtime variables
Color color = Color.red;
volatile boolean kill = false;
volatile boolean isServer = false;
volatile boolean isClient = false;
String connections[];
//messaging variables
String message;
Scanner in;
PrintWriter out;
public static void main(String [] args)
{
new Chat();
}
ServerSocket server;
Socket s;
//gui components
protected Chat()
{
double[] colWeight = {1,1,1,1,1,1};
double[] rowWeight = {5,1,1,1,1};
int[] colWidth = {1,1,1,1,1,1};
int[] rowHeight = {5,1,1,1,1};
GridBagConstraints c = new GridBagConstraints();
GridBagLayout gbl = new GridBagLayout();
gbl.rowHeights = rowHeight;
gbl.columnWidths = colWidth;
gbl.columnWeights = colWeight;
gbl.rowWeights = rowWeight;
setBounds(100,100,400,600);
setLayout(gbl);
//add conversation box
this.conversationBox.setSize(400, 400);
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 5;
c.gridheight = 5;
c.fill = 1;
c.gridx = 0;
c.gridy = 0;
gbl.setConstraints(this.conversationBox, c);
//input text box
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 4;
c.gridheight = 1;
c.fill = 1;
c.gridx = 0;
c.gridy = 5;
gbl.setConstraints(this.inputBox, c);
//send button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 5;
gbl.setConstraints(this.sendButton, c);
//host label
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 0;
c.gridy = 6;
gbl.setConstraints(this.hostLabel, c);
//host input
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = 1;
c.gridx = 1;
c.gridy = 6;
gbl.setConstraints(this.hostField, c);
//change host button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 3;
c.gridy = 6;
gbl.setConstraints(this.changeHost, c);
//start server button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 6;
gbl.setConstraints(this.startServerButton, c);
//row
//port label
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 0;
c.gridy = 7;
gbl.setConstraints(this.portLabel, c);
//port input
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = 1;
c.gridx = 1;
c.gridy = 7;
gbl.setConstraints(this.portField, c);
//change port button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 3;
c.gridy = 7;
gbl.setConstraints(this.changePort, c);
//connect button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 7;
gbl.setConstraints(this.connectButton, c);
//disconnect button, shunned in the corner
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 8;
gbl.setConstraints(this.disconnectButton, c);
mb.add(colorMenu);
colorMenu.add(redItem);
colorMenu.add(blueItem);
colorMenu.add(orangeItem);
colorMenu.add(blackItem);
add(this.conversationBox);
add(this.inputBox);
add(this.sendButton);
add(this.hostLabel);
add(this.hostField);
add(this.changeHost);
add(this.startServerButton);
add(this.portLabel);
add(this.portField);
add(this.changePort);
add(this.connectButton);
add(this.disconnectButton);
inputBox.addActionListener(this);
sendButton.addActionListener(this);
changeHost.addActionListener(this);
changePort.addActionListener(this);
startServerButton.addActionListener(this);
connectButton.addActionListener(this);
disconnectButton.addActionListener(this);
hostField.addActionListener(this);
portField.addActionListener(this);
redItem.addItemListener(this);
blueItem.addItemListener(this);
orangeItem.addItemListener(this);
blackItem.addItemListener(this);
setMenuBar(mb);
addWindowListener(this);
setResizable(true);
pack();
setVisible(true);
new Thread(this).start();
}
public void run()
{
conversationBox.appendText("Session Start.\n");
inputBox.requestFocus();
while (!kill)
{
if (isServer)
{
conversationBox.appendText("Server starting on port " + port + "\n");
conversationBox.appendText("Waiting for clients...\n");
startServer();
}
if (isClient)
{
conversationBox.appendText("Starting connection to host " + host + " on port " + port + "\n");
startClient();
}
}
}
public void startClient()
{
try
{
Socket c = new Socket(host, port);
in = new Scanner(c.getInputStream());
out = new PrintWriter(c.getOutputStream());
while (true)
{
if (in.hasNext())
{
Chat.conversationBox.appendText("You Said: " + message);
out.println("Client Said: " + message);
out.flush();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void startServer()
{
try
{
server = new ServerSocket(port);
while (true)
{
s = server.accept();
conversationBox.appendText("Client connected from " + s.getLocalAddress().getHostName() + "\n");
}
}
catch (Exception e)
{
conversationBox.appendText("An error occurred.\n");
e.printStackTrace();
isServer = false;
reEnableAll();
}
}
public void actionPerformed(ActionEvent e) throws NumberFormatException
{
Object o = e.getSource();
if (o == sendButton || o == inputBox)
{
if(inputBox.getText() != "")
{
out.println(inputBox.getText());
inputBox.setText("");
}
}
if (o == changeHost || o == hostField)
{
if (hostField.getText() != "" && hostField.getText() != host)
{
host = hostField.getText();
conversationBox.appendText("Host changed to " + host + "\n");
}
}
if (o == changePort || o == portField)
{
if (portField.getText() != "" && Integer.valueOf(portField.getText()) != port)
{
try
{
port = Integer.valueOf(portField.getText());
conversationBox.appendText("Port changed to " + port + "\n");
}
catch(NumberFormatException up)
{
throw up; //blargh enter a real value
}
}
}
if (o == startServerButton)
{
isServer = true;
isClient = false;
startServerButton.enable(false);
connectButton.enable(false);
changeHost.enable(false);
changePort.enable(false);
hostField.enable(false);
portField.enable(false);
}
if (o == connectButton)
{
isServer = false;
isClient = true;
startServerButton.enable(false);
}
inputBox.requestFocus();
}
public void reEnableAll()
{
startServerButton.enable(true);
connectButton.enable(true);
changeHost.enable(true);
changePort.enable(true);
hostField.enable(true);
portField.enable(true);
}
public void windowClosing(WindowEvent e)
{
removeWindowListener(this);
inputBox.removeActionListener(this);
sendButton.removeActionListener(this);
changeHost.removeActionListener(this);
changePort.removeActionListener(this);
startServerButton.removeActionListener(this);
connectButton.removeActionListener(this);
disconnectButton.removeActionListener(this);
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void itemStateChanged(ItemEvent e)
{
Object o = e.getSource();
if (o == redItem)
{
redItem.setState(true);
blueItem.setState(false);
orangeItem.setState(false);
blackItem.setState(false);
color = Color.red;
}
if (o == blueItem)
{
redItem.setState(false);
blueItem.setState(true);
orangeItem.setState(false);
blackItem.setState(false);
color = Color.red;
}
if (o == orangeItem)
{
redItem.setState(false);
blueItem.setState(false);
orangeItem.setState(true);
blackItem.setState(false);
color = Color.red;
}
if (o == blackItem)
{
redItem.setState(false);
blueItem.setState(false);
orangeItem.setState(false);
blackItem.setState(true);
color = Color.red;
}
}
}
I test your code, I find that in your startServer() function, you don't create an OutputStream and InputStream
Modify your startClient function like this: (create two global variables : BufferedWriter bw and BufferedReader br, because we need it in your actionPerformed function)
BufferedWriter bw = null;
BufferedReader br = null;
public void startClient()
{
try
{
Socket c = new Socket(host, port);
bw = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
br = new BufferedReader(new InputStreamReader(c.getInputStream()));
char buffer[] = new char[1024];
while (br.read(buffer) > 0)
{
Chat.conversationBox.appendText("You Said: " + new String(buffer));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Modify your startServer function like this :
public void startServer()
{
try
{
server = new ServerSocket(port);
while (true)
{
s = server.accept();
s.getInputStream();
conversationBox.appendText("Client connected from " + s.getLocalAddress().getHostName() + "\n");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
char buffer[] = new char[1024];
conversationBox.appendText("Reading....");
while(br.read(buffer) > 0)
{
conversationBox.appendText("Client Say : " + new String(buffer));
bw.write(buffer);
bw.flush();
}
conversationBox.appendText("Reading Done....");
}
}
catch (Exception e)
{
conversationBox.appendText("An error occurred.\n");
e.printStackTrace();
isServer = false;
reEnableAll();
}
}
And in your actionPerformed function, please modify following codes:
if (o == sendButton || o == inputBox)
{
if (inputBox == null)
{
System.out.println("NULL");
}
if(inputBox.getText() != "")
{
//out.println(inputBox.getText());
//out.flush();
try
{
bw.write(inputBox.getText());
bw.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
inputBox.setText("");
}
}

Categories

Resources