Help with ArrayList...

Hi Everyone:
I have this java program that I'm doing for school and I need a little bit of insite on how to do certain things. Basically what I did was I read a text file into the program. Once I tokenized the text(by line), I created another object(we'll call it Throttle) and passed the values that was tokenized, then I stored the object(Throttle) into ArrayList. Now, my question is how to I access the object(Throttle) from the ArrayList and use the object's(Throttle) methods? Here's the code that I have currently:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Project1 extends JFrame
private JButton numOfThrottles, shiftThrottle, createThrottle, quit;
private JPanel panel;
private FileReader fr;
private BufferedReader br;
private FileWriter fw;
private int tempTop;
private int whatToShift;
private int tempPosition;
private ArrayList arrThrottles = new ArrayList();
private String line;
private Throttle myThrottle = null, daThrottle;
private StringTokenizer st;
public Project1()
super ("Throttles - by Joe Munoz");
panel = new JPanel();
setContentPane(panel);
panel.setLayout(null);
//**button stuff
numOfThrottles = new JButton("Number of Throttles");
shiftThrottle = new JButton("Shift a Throttle");
createThrottle = new JButton("Create New Throttle");
quit = new JButton("Quit");
panel.add(numOfThrottles);
panel.add(shiftThrottle);
panel.add(createThrottle);
panel.add(quit);
numOfThrottles.setBounds(5,7,150,25);
shiftThrottle.setBounds(5,30,150,25);
createThrottle.setBounds(5,50,150,25);
quit.setBounds(5,70,150,25);
numOfThrottles.addActionListener(new ClickDetector());
shiftThrottle.addActionListener(new ClickDetector());
createThrottle.addActionListener(new ClickDetector());
quit.addActionListener(new ClickDetector());
//window stuff
setSize(170,135);
show();
try
br = new BufferedReader(new FileReader("C:\\Storage.txt"));
catch (FileNotFoundException ex)
System.out.println ("File Not Found!");
try
line = br.readLine();
while (line != null)
st = new StringTokenizer(line, " ");
tempTop = Integer.parseInt(st.nextToken());
tempPosition = Integer.parseInt(st.nextToken());
myThrottle = new Throttle(tempTop, tempPosition);
arrThrottles.add(myThrottle);
line = br.readLine();
catch(Exception e)
System.out.println("IO Exception!!!");
System.exit(0);
private class ClickDetector implements ActionListener
public void actionPerformed(ActionEvent event)
try
if (event.getSource() == numOfThrottles)
JOptionPane.showMessageDialog(null, "Number of Throttles is..." + myThrottle.getNumOfThrottles());
if (event.getSource() == shiftThrottle)
String shift = JOptionPane.showInputDialog("Please Choose a Throttle from 0 to " + (arrThrottles.size() - 1));
whatToShift = Integer.parseInt(shift);
System.out.println ("whatToShift = " + whatToShift);
// Need help here
if (event.getSource() == createThrottle)
String inTop = JOptionPane.showInputDialog("Please Enter Top");
tempTop = Integer.parseInt(inTop);
String inPosition = JOptionPane.showInputDialog("Please Enter Position");
tempPosition = Integer.parseInt(inPosition);
myThrottle = new Throttle(tempTop, tempPosition);
arrThrottles.add(myThrottle);
JOptionPane.showMessageDialog(null, "The Throttle has been created");
if (event.getSource() == quit)
System.out.println ("you clicked quit");
catch (Exception e)
JOptionPane.showMessageDialog(null, "No Numbers inputted!");
Any insite/suggestions on what to do? Thank You.
Joe

Hi,
I have a question addition to this same question.
If you have an object and there are 10 different objects with in the object ..
tempTop = Integer.parseInt(st.nextToken());
tempPosition = Integer.parseInt(st.nextToken());
tempBottom = 10;
Is this how you access( from the same example) each object value
strTop= (Throttle)arrThrottles.get(i).tempTop;
strPos= (Throttle)arrThrottles.get(i).tempPosition;
strB= (Throttle)arrThrottles.get(i).tempBottom;
----I AM USING ARRAYS in a JAVABEAN
Class test {
public objectTEMP t[] = null;
public void initialize(val1,al2) {
     t = redim(t,10,false); //To set the length of the array to 10
public class T {
String s1 = null;
String s2 = null;
int i1 = null;
public void setS1(String inVal) {
          s1=inVal;
public void setS2(String inVal) {
     s2=inVal;
public void setI1(int inVal) {
     i1=inVal;
public String getS1() {
          return s1;
public String getS2() {
          return s2;
public String getI1() {
          return i1;
for (int i=0; i<t.length;i++) {
System.out.println("t"+i+t.getS1());
t.setS1("SOMESTRING");
System.out.println("t"+i+t.getS1());
Any use the setter and getter method from JSP to update or get the information.
I want to change this to ArrayList as they are fast and they have resizing ability.
How to I implement this in ARRAYLIST.
Thanks a bunch

Similar Messages

  • Basic help with ArrayLists

    I'm doing a project in Java where I have to put numbers in a list, then shuffle them. Then I have to access those numbers and create a Bingo card. I've got everything down except for the accessing the numbers part. How exactly do I access integers from an array list? I read online that I should cast the elements in the ArrayList to an int, but I try that and get an incovertible types error message when I try to compile. Here is my code so far:
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Collections;
    * Numbers class -- will generate a list of numbers, shuffle them, and then have a method to return them to the Bingo card.
    public class Numbers
        private ArrayList bingoB;
        int cnt;
        String testString;
        public Numbers()
           bingoB = new ArrayList();
           resetNumbers();
        public int getNumberB()
             int test = (int) bingoB.get(0);
             testString = "b-" + test;
             return testString;
        public void resetNumbers()
            for(cnt = 1; cnt <= 15; cnt++)
            bingoB.add(new Integer(cnt));
            Collections.shuffle(bingoB);I really need help with the casting/accessing integer part, but any other tips about what I've got going on in the int getNumberB method would be helpful as well. Thanks in advance.

    You don't cast to 'int', you cast to 'Integer'. You put 'Integer' in, so you take 'Integer' out.
    To get the 'int' value from an 'Integer', use the "intValue()" method in the Integer class.
    testString should be local to getNumberB--it should not be an instance variable. Is getNumberB supposed to return an int or a String? If you want the String, you need:
    public String getNumberB() { ...}

  • Help with ArrayLists!

    Hi, I'm taking a java class at school, and I'm really, really bad at it. Anyway, I need help... I'm not even really sure what my problem is.. but I will try to explain.
    Anyway, I know I have a ton of problems, and I'm not even close to finishing the program, but here goes. I think part of my problem stems from making the arraylists into fish objects.. is there any way to work around that?
    The error that is popping up right now is "cannot resolve method- get (int)"; I'm thinking it doesn't work becuase I made the lists into fish objects, yes?
    Driver class
    * Driver class for the Fish class.
    * Christina
    * May 12, 2005
    import java.util.*;
    import cs1.Keyboard;
    public class Play
    public static void main (String [] args)
    boolean done = false;
    Fish comp = new Fish();
    Fish user = new Fish();
    Fish deck = new Fish();
    Fish userPairs = new Fish();
    Fish compPairs = new Fish();
    deck.fill();
    comp.deal();
    user.deal();
    System.out.println("Welcome to the lame, boring, Go Fish game... Yeah. Indeed.");
    System.out.println("Well.. you should know how to play.. if you don't I'd like to accuse you of" +
    " being an android, because only robots would not have played Go Fish before. Robots and hermits." +
    " Maybe you're a robot hermit? Or an alien? ");
    System.out.println("Your cards and pairs will be printed out before your turn. ");
    user.printCard();
    Method class:
    * Contains all the methods for the lame, command line version of Go Fish
    * Christina
    * May ??, 2005
    import java.util.*;
    import cs1.Keyboard;
    public class Fish
    ArrayList array = new ArrayList();
    Random generator = new Random();
    public Fish ()
    ArrayList array = new ArrayList();
    //ArrayList comp = new ArrayList();
    public void fill() //Fills the deck with 52 cards.
    for (int count= 0; count < 14; count++)
    for (int index = 0; index < 4; index++)
    Integer cardNum = new Integer(count);
    array.add(cardNum);
    public void deal(Fish array2) //Deals cards to the user and computer
    int num;
    for (int index=0; index <= 7; index++)
    num = generator.nextInt(52);
    array.add(array2.get(num));
    array2.remove(num);
    public void drawCard (Fish Array2)
    int num, length;
    length = deck.size();
    num = generator.nextInt(length);
    Integer card = new Integer(num);
    array.add(card);
    array2.remove(card);
    public void removeCard(int num)
    array.remove(num);
    public void printCard()
    for(int i = 0; i< array.size(); i++)
    System.out.println(array.get(i));
    /**public void sort()
    for(int i= 0; i < array.size(); i++)
    if(array.get(i).compareTo(i+1))
    array.add(i+1, array.get(i));
    //public int getCard()
    // int num;
    // return num.get();
    public void askUser(String card)
    System.out.println("Pick a card to ask for. Enter the number of the card ie 2." +
    "Note: Aces are represented by 0, Jacks by 11, Queens 12, and Kings 13.");
    card = Keyboard.readString();
    public void askComputer(int num, int length)
    length = this.size();
    num = generator.nextInt(length);
    this.get(num);
    System.out.println("Do you have any " + num);
    public void Pair(int pair)
    }

    Thanks a ton for the help^^ Unfortunately, because of my poor design no doubt, I still have plenty of problems.
    Oh, and I'd rather not
    Now, I have no idea why it refuses to acknowledge any of the method calls in the driver class.
    What the compiler says is wrong:
    --------------------Configuration: Final Project - j2sdk1.4.2_06 <Default> - <Default>--------------------
    C:\Program Files\Xinox Software\JCreatorV3LE\MyProjects\Final Project\Play.java:22: cannot resolve symbol
    symbol : method fill ()
    location: class java.util.ArrayList
    deck.fill();
    ^
    C:\Program Files\Xinox Software\JCreatorV3LE\MyProjects\Final Project\Play.java:23: cannot resolve symbol
    symbol : method deal ()
    location: class java.util.ArrayList
    comp.deal();
    ^
    C:\Program Files\Xinox Software\JCreatorV3LE\MyProjects\Final Project\Play.java:24: cannot resolve symbol
    symbol : method deal ()
    location: class java.util.ArrayList
    user.deal();
    ^
    C:\Program Files\Xinox Software\JCreatorV3LE\MyProjects\Final Project\Play.java:31: cannot resolve symbol
    symbol : method printCard ()
    location: class java.util.ArrayList
    user.printCard();
    ^
    4 errors
    Process completed.
    Now edited code:
    * Contains all the methods for the lame, command line version of Go Fish
    * Christina
    * May ??, 2005
    import java.util.*;
    import cs1.Keyboard;
    public class Fish
        ArrayList array = new ArrayList();
        Random generator = new Random();
        public Fish ()
        public void fill() //Fills the deck with 52 cards.
            for (int count= 0; count < 14; count++)
                for (int index = 0;  index < 4; index++)
                   Integer cardNum = new Integer(count);
                   array.add(cardNum);
        public void deal(ArrayList array2) //Deals cards to the user and computer
            int num;
            for (int index=0; index <= 7; index++)
            num = generator.nextInt(52); 
            array.add(array2.get(num));
            array2.remove(num);
        public void drawCard (ArrayList array2)
            int num, length;
            length = array2.size();
            num = generator.nextInt(length);
            Integer card = new Integer(num);
            array.add(card);
            array2.remove(card);
        public void removeCard(int num)
            array.remove(num);
        public void printCard()
            for(int i = 0; i< array.size(); i++)
                System.out.println(array.get(i));
        //public int getCard()
        //    int num;
        //    return num.get();
        public void askUser(String card)
            System.out.println("Pick a card to ask for. Enter the number of the card ie 2." +
             "Note: Aces are represented by 0, Jacks by 11, Queens 12, and Kings 13.");
            card = Keyboard.readString();
        public void askComputer(int num, int length)
            length = array.size();
            num = generator.nextInt(length);
            array.get(num);
            System.out.println("Do you have any " + num);
        public void Pair(int pair)
    * Driver class for the Fish class.
    * Christina
    * May 12, 2005
    import java.util.*; 
    import cs1.Keyboard;
    public class Play
        public static void main (String [] args)
            boolean done = false;
            ArrayList comp = new ArrayList();
            ArrayList user = new ArrayList();
            ArrayList deck = new ArrayList(52);
            ArrayList userPairs = new ArrayList();
            ArrayList compPairs = new ArrayList();
            deck.fill();
            comp.deal();
            user.deal();       
            System.out.println("Welcome to the lame, boring, Go Fish game... Yeah. Indeed.");
            System.out.println("Well.. you should know how to play.. if you don't I'd like to accuse you of" +
                        " being an android, because only robots would not have played Go Fish before. Robots and hermits." +
                        " Maybe you're a robot hermit? Or an alien? ");
            System.out.println("Your cards and pairs will be printed out before your turn. ");
            user.printCard();
    }

  • Help with ArrayLists ......Please

    Hello everyone
    I have written a simple class file for an arraylist. I have used the following methods.
    pushTop----Insert an element from the top of the array
    removeTop----Remove an element from the top of the array
    pushEnd----Insert an element from the bottom of the array
    removeEnd----Remove an element from the bottom of the array
    Also I need another method to extract an element from any point of the array.
    Could you please look at this code and see if it will work or not?
    public class ArrayList{
    protected int array[];
    protected int start, end;
    protected boolean full;
    public pArrayList(int size){
    array = new array[size]
    start = end = 0;
    full = false
    public boolean isEmpty(){
    return((start==end)&&!full);
    public void pushTop(int i){
    if start < array.length
    array [start] = i;
    start++;
    public int removeTop(){
    if (isEmpty())
    return 0;
    return array[start--]
    public pushEnd (int i)
    if end < array.length
    array [end] = i;
    end--;
    public int removeEnd(){
    if (isEmpty())
    return 0;
    return array [end];
    end--;
    thank you

    Given that this code won't even compile, there isn't much help we can provide.
    Why don't you try compiling and running your class, then come back with specific questions about why certain things don't work?
    - K

  • Need some help with ArrayLists...

    Hello, I am having trouble implementing the code requested by the following questions:
    1. Suppose an ArrayList holds Comparable objects. Write a method that
    removes the smallest value from such a list.
    2. Implement Selection Sort for an ArrayList of Comparable objects:
    public void selectionSort(ArrayList list)
    Use ArrayList�s get and set methods; do not use the add(i, obj)
    method.
    3. Implement Insertion Sort for an ArrayList of Comparable objects:
    public ArrayList insertionSort(ArrayList list)
    Your method should use and return a spare list, leaving the original list
    unchanged. Use ArrayList�s get and add(i, obj) methods.
    Thanks, any help would be greatly appreciated! :-)

    The problem is that I can only write the method
    definitions and can't go any further into implementing
    any of the actual body code! :-(Post what you've got so far. When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.

  • Need help with an assignment

    first of all, who has heard of the game called zuul? It is a very boring text based game I am currently having the pleasure of improving.
    Basically, you are in a room, that is connected to a bunch of other rooms and depending on the room you are in, you have different exists and different items in the room.
    The goal is to navigate through the collection of Rooms and there is no real win condition, It is more for learning then for actually playing.
    You navigate by a series of commands such as: go (direction)( as in "direction of exit", NSEW), quit, a few other odd bits.
    ex: go south, quit, go west etc
    The game has several classes: Game, Command, CommandWords, Item, Parser, Room.
    Obviously Game is the main central head conch, (it is not the super class.)
    Game makes use of Item, Room, Parser, and Command.
    Item is the class that deals with the number of items in the Room.
    Room is the class that deals with the rooms the player will navigate to and from.
    Command reads in the commands such as "go-(direction)" or "quit".
    Parser makes everybody understand each other by using both Command and CommandWords.
    CommandWords is a list of commands such as "go", "quit" etc.
    The problem I am having right now is to allow a player to move through the rooms while holding a certain item. The item has to come from the rooms and the player should be able to drop it.
    So I have to add two new commands: take and drop. The problem is that I have been asked to do this without creating a new class. Otherwise I would have just created class Player and be done with it. So I am trying to figure out whose responsibility should it be to take care of the take and drop command. I have done some preliminary work in class Game, it is the take(Command command) and drop() methods.
    I have also a few questions concerning other aspects of the project, I have listed their locations here:
    1. The take() method in class Game, the for-each loop, a complier error with ArrayList
    2. class Parser, a general question about the string tokenzier
    If you want to see how the game is suppose to run, just comment out the bodies of take() and drop(). Not the declaration. Everything else works.
    I shall now provide the code to all classes. I wish there were an option to upload a zip file, then you don't have to read through all the codes and copy&paste all the codes. The complier I am using is BlueJ. And the SDK version is 1.6. With the exception of class Game, everything else can be assumed to be error free.
    Thank you for your time,
    Davy
    class Game
    import java.util.*;
    *  This class is the main class of the "World of Zuul" application.
    *  "World of Zuul" is a very simple, text based adventure game.  Users
    *  can walk around some scenery. That's all. It should really be extended
    *  to make it more interesting!
    *  To play this game, create an instance of this class and call the "play"
    *  method.
    *  This main class creates and initialises all the others: it creates all
    *  rooms, creates the parser and starts the game.  It also evaluates and
    *  executes the commands that the parser returns.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    public class Game
        private Parser parser;
        private Room currentRoom;
        private Room previousRoom;
        private Stack<Room> previousRooms;
         * Create the game and initialise its internal map.
        public Game()
            createRooms();
            parser = new Parser();
         * Create all the rooms and link their exits together.
        private void createRooms()
            Room outside, theatre, pub, lab, office;
            // create the rooms
            outside = new Room("outside the main entrance of the university");
            theatre = new Room("in a lecture theatre");
            pub = new Room("in the campus pub");
            lab = new Room("in a computing lab");
            office = new Room("in the computing admin office");
            // create some items
            Item desk, chair, beer, podium, tree;
            desk = new Item("desk", "student desk",10);
            chair = new Item("chair", "student chair",5);
            beer = new Item("beer", "glass of beer", 0.5);
            podium = new Item("podium", "lecture podium", 100);
            tree = new Item("tree", "a tree", 500.5);
            // put items in some of the rooms
            outside.addItem(tree);
            theatre.addItem(desk);
            theatre.addItem(chair);
            theatre.addItem(podium);
            pub.addItem(beer);
            pub.addItem(beer);
            office.addItem(desk);
            lab.addItem(chair);
            lab.addItem(beer);
            // initialise room exits
            outside.setExit("east", theatre);
            outside.setExit("south", lab);
            outside.setExit("west", pub);
            theatre.setExit("west", outside);
            pub.setExit("east", outside);
            lab.setExit("north", outside);
            lab.setExit("east", office);
            office.setExit("west", lab);
            currentRoom = outside;  // start game outside
            previousRooms = new Stack<Room>(); // no rooms on the stack
            previousRoom = null;
         *  Main play routine.  Loops until end of play.
        public void play()
            printWelcome();
            // Enter the main command loop.  Here we repeatedly read commands and
            // execute them until the game is over.
            boolean finished = false;
            while (! finished) {
                Command command = parser.getCommand();
                finished = processCommand(command);
            System.out.println("Thank you for playing.  Good bye.");
         * Print out the opening message for the player.
        private void printWelcome()
            System.out.println();
            System.out.println("Welcome to the World of Zuul!");
            System.out.println("World of Zuul is a new, incredibly boring adventure game.");
            System.out.println("Type 'help' if you need help.");
            System.out.println();
            System.out.println(currentRoom.getLongDescription());
         * Given a command, process (that is: execute) the command.
         * @param command The command to be processed.
         * @return true If the command ends the game, false otherwise.
        private boolean processCommand(Command command)
            boolean wantToQuit = false;
            if(command.isUnknown()) {
                System.out.println("I don't know what you mean...");
                return false;
            String commandWord = command.getCommandWord();
            if (commandWord.equals("help")) {
                printHelp();
            else if (commandWord.equals("go")) {
                goRoom(command);
            else if (commandWord.equals("look")) {
                look(command);
            else if (commandWord.equals("eat")) {
                eat(command);
            else if (commandWord.equals("back")) {
                back(command);
            else if (commandWord.equals("stackBack")) {
                stackBack(command);
            else if (commandWord.equals("take")){
                take(command);
            else if (commandWord.equals("drop")) {
                drop(command);
            else if (commandWord.equals("quit")) {
                wantToQuit = quit(command);
            // else command not recognised.
            return wantToQuit;
        // implementations of user commands:
         * Print out some help information.
         * Here we print some stupid, cryptic message and a list of the
         * command words.
        private void printHelp()
            System.out.println("You are lost. You are alone. You wander");
            System.out.println("around at the university.");
            System.out.println();
            System.out.println("Your command words are:");
            System.out.println(parser.getCommands());
         * Try to go to one direction. If there is an exit, enter the new
         * room, otherwise print an error message.
         * @param command The command entered.
        private void goRoom(Command command)
            if(!command.hasSecondWord()) {
                // if there is no second word, we don't know where to go...
                System.out.println("Go where?");
                return;
            String direction = command.getSecondWord();
            // Try to leave current room.
            Room nextRoom = currentRoom.getExit(direction);
            if (nextRoom == null) {
                System.out.println("There is no door!");
            else {
                previousRooms.push(currentRoom);
                previousRoom = currentRoom;
                currentRoom = nextRoom;
                System.out.println(currentRoom.getLongDescription());
         * "Look" was entered.
         * @param command The command entered.
        private void look(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Look what?");
                return;
            System.out.println(currentRoom.getLongDescription());
         * "Eat" was entered.
         * @param command The command entered.
        private void eat(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Eat what?");
                return;
            System.out.println("You have eaten and are no longer hungry!");
         * "Back" was entered.
         * @param command The command entered.
        private void back(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Back what?");
                return;
            if (previousRoom==null) {
                System.out.println("Can't go back.");
                return;
            // push current room on stack (for stackBack)
            previousRooms.push(currentRoom);
            // swap current and previous rooms (for back)
            Room temp = currentRoom;
            currentRoom = previousRoom;
            previousRoom = temp;
            // You could replace the previous three lines with the following
            // which use the stack to get the previous room
            // but note that this makes "back" dependent on "stackBack".
            // (If you do it this way you no longer need "temp".
            // currentRoom = previousRoom;
            // previousRoom = previousRooms.peek();
            System.out.println("You have gone back:");
            System.out.println(currentRoom.getLongDescription());
         * "StackBack" was entered.
         * @param command The command entered.
        private void stackBack(Command command)
            if(command.hasSecondWord()) {
                System.out.println("StackBack what?");
                return;
            if (previousRooms.isEmpty()) {
                System.out.println("Can't go StackBack.");
                return;
            // set previous room (for "back")
            previousRoom = currentRoom;
            // set new current room (using stack)
            currentRoom = previousRooms.pop();
            System.out.println("You have gone StackBack:");
            System.out.println(currentRoom.getLongDescription());
         * allows a player to take something from the room
         * @param command
        private void take(Command command){
        String a;
        a=command.getSecondWord();
        for (Item i:currentRoom.items()) { //a for each loop, since the room's items are kept in a list, but this gives a                                           //compiler error, it doesn't work because items is an ArrayList, but I need a way to pick up the item. I thought that if //given the item's name, I could run a check through the room's ArrayList of items via a for-each loop
            if (a==i.getName()) {
            removeItem (i);
            return;
         * allows a player to drop an item in the room
         * @param command
        private void drop(Command command) {
            if(command.hasSecondWord()) {
                System.out.println("drop what?");
                return;
            //add item method is suppose to be used here
         * "Quit" was entered. Check the rest of the command to see
         * whether we really quit the game.
         * @param command The command entered.
         * @return true, if this command quits the game, false otherwise.
        private boolean quit(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Quit what?");
                return false;
            else {
                return true;  // signal that we want to quit
    }class Room
    import java.util.*;
    * Class Room - a room in an adventure game.
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * A "Room" represents one location in the scenery of the game.  It is
    * connected to other rooms via exits.  For each existing exit, the room
    * stores a reference to the neighboring room.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.03 October 25, 2007
    public class Room
        private String description;
        private HashMap<String, Room> exits;        // stores exits of this room.
        // The items in the room
        private ArrayList<Item> items;
         * Create a room described "description". Initially, it has
         * no exits. "description" is something like "a kitchen" or
         * "an open court yard".
         * @param description The room's description.
        public Room(String description)
            this.description = description;
            exits = new HashMap<String, Room>();
            items = new ArrayList<Item>();
         * Define an exit from this room.
         * @param direction The direction of the exit.
         * @param neighbor  The room to which the exit leads.
        public void setExit(String direction, Room neighbor)
            exits.put(direction, neighbor);
         * Gives a short description of the room.
         * @return The short description of the room
         * (the one that was defined in the constructor).
        public String getShortDescription()
            return description;
         * Return a description of the items in the room
         * (Note that this could be combined with getLongDescription, but
         * this way shows better cohesion, and could avoid code duplication
         * for future enhancements.)
         * @return A description of the items in this room
        public String getItemsDescription()
            String s = new String();
            if (items.size()==0)
                s += "There are no items in this room.\n";
            else {
                s += "The item(s) in the room are:\n";
                for (Item item : items ) {
                   s += item.getInfo() + "\n";
            return s;
         * Return a description of the room in the form:
         *     You are in the kitchen.
         *     Exits: north west
         *     and information on the items in the room
         * @return A long description of this room
        public String getLongDescription()
            String s = "You are " + description + ".\n" + getExitString() + "\n";
            s += getItemsDescription();
            return s;
         * Return a string describing the room's exits, for example
         * "Exits: north west".
         * @return Details of the room's exits.
        private String getExitString()
            String returnString = "Exits:";
            Set<String> keys = exits.keySet();
            for(String exit : keys) {
                returnString += " " + exit;
            return returnString;
         * Return the room that is reached if we go from this room in direction
         * "direction". If there is no room in that direction, return null.
         * @param direction The exit's direction.
         * @return The room in the given direction.
        public Room getExit(String direction)
            return exits.get(direction);
         * Adds the given item to the room.
         * @param item The item to be added
        public void addItem(Item item)
            items.add(item);
         * Removes an item if the person picks it up
         * @param item the item to be removed
        public void removeItem (Item item)
            items.remove(item);
    }class Item
    * This represents an item in a room in zuul.
    * @author L.S. Marshall
    * @version 1.00 October 9, 2007
    public class Item
        // The description of the item
        private String description;
        // The weight of the item
        private double weight;
        private String name;
         * Constructor for objects of class Item
         * @param desc description of the item
         * @param weight the weight of the item
        public Item(String name, String desc, double weight)
            description = desc;
            this.weight = weight;
            this.name=name;
         * Returns a string representing this item
         * @return string representing this item
        public String getInfo()
            return ("Item: " + description + ", weighs " + weight + ".");
         * returns the name of the string
         * @ return the name in a string
        public String getName()
            return ( name );
    }class Command
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * This class holds information about a command that was issued by the user.
    * A command currently consists of two strings: a command word and a second
    * word (for example, if the command was "take map", then the two strings
    * obviously are "take" and "map").
    * The way this is used is: Commands are already checked for being valid
    * command words. If the user entered an invalid command (a word that is not
    * known) then the command word is <null>.
    * If the command had only one word, then the second word is <null>.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    public class Command
        private String commandWord;
        private String secondWord;
         * Create a command object. First and second word must be supplied, but
         * either one (or both) can be null.
         * @param firstWord The first word of the command. Null if the command
         *                  was not recognised.
         * @param secondWord The second word of the command.
        public Command(String firstWord, String secondWord)
            commandWord = firstWord;
            this.secondWord = secondWord;
         * Return the command word (the first word) of this command. If the
         * command was not understood, the result is null.
         * @return The command word.
        public String getCommandWord()
            return commandWord;
         * @return The second word of this command. Returns null if there was no
         * second word.
        public String getSecondWord()
            return secondWord;
         * @return true if this command was not understood.
        public boolean isUnknown()
            return (commandWord == null);
         * @return true if the command has a second word.
        public boolean hasSecondWord()
            return (secondWord != null);
    }class Parser
    import java.util.Scanner;
    import java.util.StringTokenizer;
    //I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
    //Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
    //yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
    //Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
    //it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * This parser reads user input and tries to interpret it as an "Adventure"
    * command. Every time it is called it reads a line from the terminal and
    * tries to interpret the line as a two word command. It returns the command
    * as an object of class Command.
    * The parser has a set of known command words. It checks user input against
    * the known commands, and if the input is not one of the known commands, it
    * returns a command object that is marked as an unknown command.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.01 October 9, 2007
    public class Parser
        private CommandWords commands;  // holds all valid command words
        private Scanner reader;         // source of command input
         * Create a parser to read from the terminal window.
        public Parser()
            commands = new CommandWords();
            reader = new Scanner(System.in);
         * Command returns the command typed by the user.
         * @return The next command from the user.
        public Command getCommand()
            String inputLine;   // will hold the full input line
            String word1 = null;
            String word2 = null;
            System.out.print("> ");     // print prompt
            inputLine = reader.nextLine();
            // Find up to two words on the line.
            Scanner tokenizer = new Scanner(inputLine);
            if(tokenizer.hasNext()) {
                word1 = tokenizer.next();      // get first word
                if(tokenizer.hasNext()) {
                    word2 = tokenizer.next();      // get second word
                    // note: we just ignore the rest of the input line.
            // Now check whether this word is known. If so, create a command
            // with it. If not, create a "null" command (for unknown command).
            if(commands.isCommand(word1)) {
                return new Command(word1, word2);
            else {
                return new Command(null, word2);
         * Returns a list of valid command words.
         * @string list of valid command words
        public String getCommands()
            return commands.getCommandList();
    }class CommandWords
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game.
    * This class holds an enumeration of all command words known to the game.
    * It is used to recognise commands as they are typed in.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.01 October 9, 2007
    public class CommandWords
        // a constant array that holds all valid command words
        private static final String[] validCommands = {
            "go", "quit", "help", "look", "eat", "back", "stackBack",
            "take", "drop",
         * Constructor - initialise the command words.
        public CommandWords()
            // nothing to do at the moment...
         * Check whether a given String is a valid command word.
         * @param aString the command word
         * @return true if it is, false if it isn't.
        public boolean isCommand(String aString)
            for(int i = 0; i < validCommands.length; i++) {
                if(validCommands.equals(aString))
    return true;
    // if we get here, the string was not found in the commands
    return false;
    * Return a string containing all valid commands.
    * @return string of all valid commands
    public String getCommandList()
    String s="";
    for(String command: validCommands) {
    s += command + " ";
    return s;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    right, sorry, that was thoughtless of me.
    class Parser
    import java.util.Scanner;
    import java.util.StringTokenizer;
    //I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
    //Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
    //yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
    //Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
    //it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * This parser reads user input and tries to interpret it as an "Adventure"
    * command. Every time it is called it reads a line from the terminal and
    * tries to interpret the line as a two word command. It returns the command
    * as an object of class Command.
    * The parser has a set of known command words. It checks user input against
    * the known commands, and if the input is not one of the known commands, it
    * returns a command object that is marked as an unknown command.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.01 October 9, 2007
    public class Parser
        private CommandWords commands;  // holds all valid command words
        private Scanner reader;         // source of command input
         * Create a parser to read from the terminal window.
        public Parser()
            commands = new CommandWords();
            reader = new Scanner(System.in);
         * Command returns the command typed by the user.
         * @return The next command from the user.
        public Command getCommand()
            String inputLine;   // will hold the full input line
            String word1 = null;
            String word2 = null;
            System.out.print("> ");     // print prompt
            inputLine = reader.nextLine();
            // Find up to two words on the line.
            Scanner tokenizer = new Scanner(inputLine);
            if(tokenizer.hasNext()) {
                word1 = tokenizer.next();      // get first word
                if(tokenizer.hasNext()) {
                    word2 = tokenizer.next();      // get second word
                    // note: we just ignore the rest of the input line.
            // Now check whether this word is known. If so, create a command
            // with it. If not, create a "null" command (for unknown command).
            if(commands.isCommand(word1)) {
                return new Command(word1, word2);
            else {
                return new Command(null, word2);
         * Returns a list of valid command words.
         * @string list of valid command words
        public String getCommands()
            return commands.getCommandList();
    }

  • Problem with ArrayLists and writing and reading from a .dat file (I think)

    I'm brand new to this forum, but I'm sure hoping someone can help me with a problem I'm having with ArrayLists. This program was originally created with an array of objects that were displayed on a GUI with jtextFields, then cycling thru them via jButtons: First, Next, Previous, Last. Now I need to add the ability to modify, delete and add records. Both iterations of this program needed to write to and read from a .dat file.
    It worked just like it was suppose to when I used just the array, but now I need to use a "dynamic array" that will grow or shrink as needed: i.e. an ArrayList.
    When I aded the ArrayList I had the ArrayList use toArray() to fill my original array so I could continue to use all the methods I'd created for using with my array. Now I'm getting a nullPointerException every time I try to run my program, which means somewhere I'm NOT filling my array ???? But, I'm writing just fine to my .dat file, which is confusing me to no end!
    It's a long program, and I apologize for the length, but here it is. There are also 2 class files, a parent and 1 child below Inventory6. This was written in NetBeans IDE 5.5.1.
    Thank you in advance for any help anyone can give me!
    LabyBC
    package my.Inventory6;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.io.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.ArrayList;
    import java.text.NumberFormat;
    // Class Inventory6
    public class Inventory6 extends javax.swing.JFrame {
    private static InventoryPlusColor[] inventory;
    private static ArrayList inList;
    // create a tool that insure the specified format for a double number, when displayed
    private DecimalFormat doubleFormat = new DecimalFormat( "0.00" );
    private DecimalFormat singleFormat = new DecimalFormat( "0");
    // the index within the array of products of the current displayed product
    private int currentProductIndex;
    /** Creates new form Inventory6 */
    public Inventory6() {
    initComponents();
    currentProductIndex = 0;
    } // end Inventory6()
    private static InventoryPlusColor[] getInventory() {
    ArrayList<InventoryPlusColor> inList = new ArrayList<InventoryPlusColor>();
    inList.add(new InventoryPlusColor(1, "Couch", 3, 1250.00, "Blue"));
    inList.add(new InventoryPlusColor(2, "Recliner", 10, 525.00, "Green"));
    inList.add(new InventoryPlusColor(3, "Chair", 6, 125.00, "Mahogany"));
    inList.add(new InventoryPlusColor(4, "Pedestal Table", 2, 4598.00, "Oak"));
    inList.add(new InventoryPlusColor(5, "Sleeper Sofa", 4, 850.00, "Yellow"));
    inList.add(new InventoryPlusColor(6, "Rocking Chair", 2, 459.00, "Tweed"));
    inList.add(new InventoryPlusColor(7, "Couch", 4, 990.00, "Red"));
    inList.add(new InventoryPlusColor(8, "Chair", 12, 54.00, "Pine"));
    inList.add(new InventoryPlusColor(9, "Ottoman", 3, 110.00, "Black"));
    inList.add(new InventoryPlusColor(10, "Chest of Drawers", 5, 598.00, "White"));
    for (int j = 0; j < inList.size(); j++)
    System.out.println(inList);
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    return inventory;
    } // end getInventory() method
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    IDNumberLbl = new javax.swing.JLabel();
    IDNumberField = new javax.swing.JTextField();
    prodNameLbl = new javax.swing.JLabel();
    prodNameField = new javax.swing.JTextField();
    colorLbl = new javax.swing.JLabel();
    colorField = new javax.swing.JTextField();
    unitsInStockLbl = new javax.swing.JLabel();
    unitsInStockField = new javax.swing.JTextField();
    unitPriceLbl = new javax.swing.JLabel();
    unitPriceField = new javax.swing.JTextField();
    invenValueLbl = new javax.swing.JLabel();
    invenValueField = new javax.swing.JTextField();
    restockingFeeLbl = new javax.swing.JLabel();
    restockingFeeField = new javax.swing.JTextField();
    jbtFirst = new javax.swing.JButton();
    jbtNext = new javax.swing.JButton();
    jbtPrevious = new javax.swing.JButton();
    jbtLast = new javax.swing.JButton();
    jbtAdd = new javax.swing.JButton();
    jbtDelete = new javax.swing.JButton();
    jbtModify = new javax.swing.JButton();
    jbtSave = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    searchIDNumLbl = new javax.swing.JLabel();
    searchIDNumbField = new javax.swing.JTextField();
    jbtSearch = new javax.swing.JButton();
    searchResults = new javax.swing.JLabel();
    jbtExit = new javax.swing.JButton();
    jbtExitwoSave = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Inventory Program"));
    IDNumberLbl.setText("ID Number");
    IDNumberField.setEditable(false);
    prodNameLbl.setText("Product Name");
    prodNameField.setEditable(false);
    colorLbl.setText("Product Color");
    colorField.setEditable(false);
    colorField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    colorFieldActionPerformed(evt);
    unitsInStockLbl.setText("Units In Stock");
    unitsInStockField.setEditable(false);
    unitPriceLbl.setText("Unit Price $");
    unitPriceField.setEditable(false);
    invenValueLbl.setText("Inventory Value $");
    invenValueField.setEditable(false);
    restockingFeeLbl.setText("5% Restocking Fee $");
    restockingFeeField.setEditable(false);
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(unitPriceLbl)
    .addComponent(unitsInStockLbl)
    .addComponent(colorLbl)
    .addComponent(prodNameLbl)
    .addComponent(IDNumberLbl)
    .addComponent(restockingFeeLbl)
    .addComponent(invenValueLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(IDNumberField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(prodNameField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(colorField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(invenValueField, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
    .addContainerGap())
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(IDNumberLbl)
    .addComponent(IDNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(prodNameLbl)
    .addComponent(prodNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(colorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(colorLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitsInStockLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitPriceLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(restockingFeeLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(invenValueField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(invenValueLbl))
    .addContainerGap())
    jbtFirst.setText("First");
    jbtFirst.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtFirstActionPerformed(evt);
    jbtNext.setText("Next");
    jbtNext.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtNextActionPerformed(evt);
    jbtPrevious.setText("Previous");
    jbtPrevious.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtPreviousActionPerformed(evt);
    jbtLast.setText("Last");
    jbtLast.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtLastActionPerformed(evt);
    jbtAdd.setText("Add");
    jbtAdd.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtAddActionPerformed(evt);
    jbtDelete.setText("Delete");
    jbtModify.setText("Modify");
    jbtModify.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtModifyActionPerformed(evt);
    jbtSave.setText("Save");
    jbtSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtSaveActionPerformed(evt);
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Search by:"));
    searchIDNumLbl.setText("Item Number:");
    jbtSearch.setText("Search");
    searchResults.setFont(new java.awt.Font("Tahoma", 1, 12));
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(searchIDNumLbl)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(259, 259, 259)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(searchIDNumLbl)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtSearch)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jbtExit.setText("Save and Exit");
    jbtExit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitActionPerformed(evt);
    jbtExitwoSave.setText("Exit");
    jbtExitwoSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitwoSaveActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jbtExitwoSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jbtExit)))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtFirst)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtNext)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtPrevious)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtLast))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(12, 12, 12)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtAdd)
    .addComponent(jbtDelete)
    .addComponent(jbtModify)
    .addComponent(jbtSave))))
    .addContainerGap())
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtFirst, jbtLast, jbtNext, jbtPrevious});
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtAdd, jbtDelete, jbtModify, jbtSave});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(21, 21, 21)
    .addComponent(jbtAdd)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtDelete)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtModify)
    .addGap(39, 39, 39)
    .addComponent(jbtSave))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jbtFirst)
    .addComponent(jbtNext)
    .addComponent(jbtPrevious)
    .addComponent(jbtLast))
    .addGap(15, 15, 15)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtExit)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtExitwoSave)))
    .addContainerGap())
    pack();
    }// </editor-fold>
    private void jbtExitwoSaveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.exit(0);
    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String prodNameMod, colorMod;
    double unitsInStockMod, unitPriceMod;
    int idNumMod;
    idNumMod = Integer.parseInt(IDNumberField.getText());
    prodNameMod = prodNameField.getText();
    unitsInStockMod = Double.parseDouble(unitsInStockField.getText());
    unitPriceMod = Double.parseDouble(unitPriceField.getText());
    colorMod = colorField.getText();
    if(currentProductIndex == inventory.length) {
    inList.add(new InventoryPlusColor(idNumMod, prodNameMod,
    unitsInStockMod, unitPriceMod, colorMod));
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    } else {
    inventory[currentProductIndex].setIDNumber(idNumMod);
    inventory[currentProductIndex].setProdName(prodNameMod);
    inventory[currentProductIndex].setUnitsInStock(unitsInStockMod);
    inventory[currentProductIndex].setUnitPrice(unitPriceMod);
    inventory[currentProductIndex].setColor(colorMod);
    displayProduct(inventory[currentProductIndex]);
    private static void writeInventory(InventoryPlusColor i,
    DataOutputStream out) {
    try {
    out.writeInt(i.getIDNumber());
    out.writeUTF(i.getProdName());
    out.writeDouble(i.getUnitsInStock());
    out.writeDouble(i.getUnitPrice());
    out.writeUTF(i.getColor());
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception writing data",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } //end writeInventory()
    private static DataOutputStream openOutputStream(String name) {
    DataOutputStream out = null;
    try {
    File file = new File(name);
    out =
    new DataOutputStream(
    new BufferedOutputStream(
    new FileOutputStream(file)));
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error", "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return out;
    } // end openOutputStream()
    private static void closeFile(DataOutputStream out) {
    try {
    out.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeFile()
    private static DataInputStream getStream(String name) {
    DataInputStream in = null;
    try {
    File file = new File(name);
    in = new DataInputStream(
    new BufferedInputStream(
    new FileInputStream(file)));
    } catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "The file doesn't exist",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error creating file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return in;
    private static void closeInputFile(DataInputStream in) {
    try {
    in.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeInputFile()
    private double entireInventory() {
    // a temporary double variable that the method will return ...
    // after each product's inventory is added to it
    double entireInventory = 0;
    // loop to control number of products
    for (int index = 0; index < inventory.length; index++) {
    // add each inventory to the entire inventory
    entireInventory += inventory[index].setInventoryValue();
    } // end loop to control number of products
    return entireInventory;
    } // end method entireInventory
    private void jbtLastActionPerformed(java.awt.event.ActionEvent evt) {                                       
    currentProductIndex = inventory.length-1; // move to the last product
    // display the information for the last product
    displayProduct(inventory[currentProductIndex]);
    private void jbtPreviousActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (currentProductIndex != 0) // it's not the first product displayed
    currentProductIndex -- ; // move to the previous product (decrement the current index)
    } else // the first product is displayed
    currentProductIndex = inventory.length-1; // move to the last product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtNextActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (currentProductIndex != inventory.length-1) // it's not the last product displayed
    currentProductIndex ++ ; // move to the next product (increment the current index)
    } else // the last product is displayed
    currentProductIndex = 0; // move to the first product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtFirstActionPerformed(java.awt.event.ActionEvent evt) {                                        
    currentProductIndex = 0;
    // display the information for the first product
    displayProduct(inventory[currentProductIndex]);
    private void colorFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    private void jbtModifyActionPerformed(java.awt.event.ActionEvent evt) {                                         
    prodNameField.setEditable(true);
    prodNameField.setFocusable(true);
    unitsInStockField.setEditable(true);
    unitPriceField.setEditable(true);
    private void jbtAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
    IDNumberField.setText("");
    IDNumberField.setEditable(true);
    prodNameField.setText("");
    prodNameField.setEditable(true);
    colorField.setText("");
    colorField.setEditable(true);
    unitsInStockField.setText("");
    unitsInStockField.setEditable(true);
    unitPriceField.setText("");
    unitPriceField.setEditable(true);
    restockingFeeField.setText("");
    invenValueField.setText("");
    currentProductIndex = inventory.length;
    private void jbtExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
    DataOutputStream out = openOutputStream("inventory.dat");
    for (InventoryPlusColor i : inventory)
    writeInventory(i, out);
    closeFile(out);
    System.exit(0);
    private static InventoryPlusColor readProduct(DataInputStream in) {
    int idNum = 0;
    String prodName = "";
    double inStock = 0.0;
    double pric

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • Is there a Java utility class to help with data management in a desktop UI?

    Is there a Java utility class to help with data management in a desktop UI?
    I am writing a UI to configure a network device that will be connected to the serial port of the computer while it is being configured. There is no web server or database for my application. The UI has a large number of fields (50+) spread across 16 tabs. I will write the UI in Java FX. It should run inside the browser when launched, and issue commands to the network device through the serial port. A UI has several input fields spread across tabs and one single Submit button. If a field is edited, and the submit button clicked, it issues a command and sends the new datum to the device, retrieves current value and any errors. so if input field has bad data, it is indicated for example, the field has a red border.
    Is there a standard design pattern or Java utility class to accomplish the frequently encountered, 'generic' parts of this scenario? lazy loading, submitting only what fields changed, displaying what fields have errors etc. (I dont want to reinvent the wheel if it is already there). Otherwise I can write such a class and share it back here if it is useful.
    someone recommended JGoodies Bindings for Swing - will this work well and in FX?

    Many thanks for the reply.
    In the servlet create an Arraylist and in th efor
    loop put the insances of the csqabean in this
    ArrayList. Exit the for loop and then add the
    ArrayList as an attribute to the session.I am making the use of Vector and did the same thing as u mentioned.I am using scriplets...
    >
    In the jsp retrieve the array list from the session
    and in a for loop step through the ArrayList
    retrieving each CourseSectionQABean and displaying.
    You can do this in a scriptlet but should also check
    out the jstl tags.I am able to remove this problem.Thanks again for the suggestion.
    AS

  • A problem with ArrayLists

    Hello
    I'm pretty new to Java, and sometimes all those objects, instances, classes, data types etc confuse me. I'm having some kind of a problem with ArrayLists (tried with vectors too, didn't work) . I'm writing a program which takes float numbers from user input and does stuff to them. No syntax error in my code, but I get a java.lang.ClassCastException when I run it.
    I insert stuff to the ArrayList like this:
    luku.add(new Float(syotettyLuku));no problem
    I'm trying to access information from the list like this inside a while loop
    float lukui = new Float((String)luku.get(i)) .floatValue();but the exception comes when the programme hits that line, no matter which value i has.
    Tried this too, said that types are incompatible:
    float lukui = ((float)luku.get(i)) .floatValue();What am I doing wrong? I couldn't find any good tutorials about using lists, so i'm really lost here.
    I'll post the whole code here, if it helps. Sorry about the Finnish variable and method names, but you get the idea :)
    package esa;
    import java.io.*;
    import java.util.*;
    public class Esa {
    static final int maxLukuja = 100;
    static BufferedReader syote = new BufferedReader(new InputStreamReader(System.in));
    static String rivi;
    static String lopetuskasky = "exit";
    static double keskiarvo;
    static ArrayList luku = new ArrayList();
    static int lukuja;
    static float summa = 0;
    // M��ritell��n pari metodia, joiden avulla voidaan tarkastaa onko tarkasteltava muuttuja liukuluku
    static Float formatFloat(String rivi) {
        if (rivi == null) {
            return null;
        try {
            return new Float(rivi);
        catch(NumberFormatException e) {
            return null;
    static boolean isFloat(String rivi) {
        return (formatFloat(rivi) != null);
    // Luetaan luvut k�ytt�j�lt� ja tallnnetaan ne luku-taulukkoon
    static void lueLuvut() throws IOException{
        int i = 0;
        float syotettyLuku;
        while(i < maxLukuja) {
            System.out.println("Anna luku kerrallaan ja paina enter. Kun halaut lopettaa, n�pp�ile exit");
            rivi = syote.readLine();
            boolean onkoLiukuluku = isFloat(rivi);
            if (onkoLiukuluku) {
                syotettyLuku = Float.parseFloat(rivi);
                if (syotettyLuku == 0) {
                    lukuja = luku.size();              
                    break;
                }  // if syotettyluku
                else {
                    luku.add(new Float(syotettyLuku));
                    i++;
                } // else
            } // if onkoLiukuluku
            else {
               System.out.println("Antamasi luku ei ole oikeaa muotoa, yrit� uudelleen.");
               System.out.println("");
            } // else
        } // while i < maxlukuja
    // lueLuvut
    static void laskeKeskiarvo() {
        int i = 0;
        while(i < lukuja) {
            float lukui = ((float)luku.get(i)) .floatValue();
            System.out.println(lukui);
            summa = summa + lukui;
        }   i++;
        keskiarvo = (summa / lukuja);
    } // laskeKeskiarvo
    public static void main(String args[]) throws IOException {
    lueLuvut();
    laskeKeskiarvo();
    } // main
    } // class

    Thanks! Now it's functioning.
    As I mentioned, I tried this:
    float lukui = ((float)luku.get(i))
    .floatValue();And your reply was:
    float lukui =
    ((Float)luku.get(i)).floatValue So the problem really was the spelling, it should
    have been Float with a capital F.
    From what I understand, Float refers to the Float
    class, Correct. And float refers to the float primitive type. Objects and primitives are not interchangeable. You need to take explicit steps to convert between them. Although, in 1.5/5.0, autoboxing/unboxing hide some of this for you.
    so why isn't just a regular float datatype
    doing the job here, like with the variable lukui?Not entirely sure what you're asking.
    Collections take objects, not primitives, and since you put an object in, you get an object out. You then have to take the extra step to get a primitive representation of that object. You can't just cast between objects and primitives.
    Again, autoboxing will relieve some of this drudgery. I haven't used it myself yet, so I can't comment on how good or bad it is.

  • Need help with my addressbook program

    hi,
    i need help with my program here. this one should works as:
    - saves user input into a txt file
    - displays name of the saved person on the jlist whenever i run the program
    - displays info about the person when clicked via textboxes given by reading the txt file where the user inputs are
    - should scroll when the list exceeds the listbox
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JList;
    import java.awt.event.ActionListener;
    import java.io.*;
    import javax.swing.event.*;
    import java.io.FilterInputStream;
    public class AddressList extends JPanel implements ActionListener
         JTextField txt1 = new JTextField();
         JTextField txt2 = new JTextField();
         JTextField txt3 = new JTextField();
         DefaultListModel mdl = new DefaultListModel();
         JList list = new JList();
         JScrollPane listScroller = new JScrollPane(list);
         ListSelectionModel listSelectionModel;
         File fob = new File("Address3.txt");
         String name;
         char[] chars;     
         public void ListDisplay()
              try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   if(fob.exists())
                         while((name = rand.readLine()) != null)
                              chars = name.toCharArray();
                              if(chars[0] == '*')
                                   mdl.addElement(name);
                                   list.setModel(mdl);
                              if(chars[0] == '#')
                                   continue;
                    else
                        System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
         public AddressList()
              this.setLayout(null);
              listSelectionModel = list.getSelectionModel();
            listSelectionModel.addListSelectionListener(new ListInfo());
              list.setBounds(10,40,330,270);
              listScroller.setBounds(320,40,20,100);
              add(list);
              add(listScroller);
              JLabel lbl4 = new JLabel("Name: ");
              lbl4.setBounds(400,10,80,30);
              add(lbl4);
              JLabel lbl5 = new JLabel("Cellphone #: ");
              lbl5.setBounds(400,50,80,30);
              add(lbl5);
              JLabel lbl6 = new JLabel("Address: ");
              lbl6.setBounds(400,90,80,30);
              add(lbl6);
              JLabel lbl7 = new JLabel("List ");
              lbl7.setBounds(10,10,100,30);
              add(lbl7);
              txt1.setBounds(480,10,200,30);
              add(txt1);
              txt2.setBounds(480,50,200,30);
              add(txt2);
              txt3.setBounds(480,90,200,30);
              add(txt3);
              JButton btn1 = new JButton("Add");
              btn1.setBounds(480,130,100,30);
              btn1.addActionListener(this);
              btn1.setActionCommand("Add");
              add(btn1);
              JButton btn2 = new JButton("Save");
              btn2.setBounds(480,170,100,30);
              btn2.addActionListener(this);
              btn2.setActionCommand("Save");
              add(btn2);
              JButton btn3 = new JButton("Cancel");
              btn3.setBounds(480,210,100,30);
              btn3.addActionListener(this);
              btn3.setActionCommand("Cancel");
              add(btn3);
              JButton btn4 = new JButton("Close");
              btn4.setBounds(480,250,100,30);
              btn4.addActionListener(this);
              btn4.setActionCommand("Close");
              add(btn4);
         public static void main(String[]args)
              JFrame frm = new JFrame("Address List");
              AddressList panel = new AddressList();
              frm.getContentPane().add(panel,"Center");
              frm.setSize(700,350);
              frm.setVisible(true);
              panel.ListDisplay();
         public void actionPerformed(ActionEvent e)
              String cmd;
              cmd = e.getActionCommand();
              if(cmd.equals("Add"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Save"))
                   mdl.addElement(txt1.getText());
                   list.setModel(mdl);
                   try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                   LineNumberReader line = new LineNumberReader(br);
                    if(fob.exists())
                              rand.seek(fob.length());
                              rand.writeBytes("* " + txt1.getText());
                              rand.writeBytes("\r\n" + "# " + txt2.getText());
                              rand.writeBytes("\r\n" + "# " + txt3.getText() + "\r\n");
                    else
                         System.out.println("No such file..");
                        txt1.setText("");
                        txt2.setText("");
                        txt3.setText("");
                    catch(IOException a)
                         System.out.println(a.getMessage());
              else if(cmd.equals("Cancel"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Close"))
                   System.exit(0);
    class ListInfo implements ListSelectionListener
         public void valueChanged(ListSelectionEvent e)
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
              int minIndex = lsm.getMinSelectionIndex();
            int maxIndex = lsm.getMaxSelectionIndex();
              try //*this one should display the info of the person whenever i click the person's name at the list box via textbox.. but i cant seem to get it right since it always display the info of the first person inputed.. i tried to get the program to display them whenever it reads lines with * on them....
                   File fob = new File("Address3.txt");
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   LineNumberReader line = new LineNumberReader(br);
                   if(fob.exists())
                              for(int i = minIndex; i<=maxIndex; i++)
                                   if(lsm.isSelectedIndex(i))
                                        while((name = rand.readLine()) != null)
                                             chars = name.toCharArray();
                                             if(chars[0] == '#')
                                                  continue;
                                             if(chars[0] == '*')
                                                  txt1.setText(rand.readLine());
                                                 txt2.setText(rand.readLine());
                                                 txt3.setText(rand.readLine());
                    else
                              System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
    }the only problem now is about how it should display the right info about the person whenever i click its name on the list.. something about file reading or something, i just cant figure it out.
    and also about how to make it scroll once it exceeds the list.. i cant make it work, maybe something about wrong declaration..
    thanks in advance..
    Edited by: syder on Mar 14, 2008 2:26 AM

    Like said before, do one thing at a time. At startup, something like:
    //put all the content in a list
    ArrayList<String> lines = new ArrayList<String>();
    while(String line=rand.readLine()!=null) {
        lines.add(line);
    }If you follow the good advice to create a class to encapsulate the entries, you could populate a list of such entries like this:
    static final int ENTRY_SIZE = 3;//you have 3 fields now, better to have a constant if that changes
    ArrayList<Entry> entries = new ArrayList<Entry>();
    for(int i=0; i<lines.size(); i+=ENTRY_SIZE) {
        Entry entry = new Entry(lines.get(i), lines.get(i+1), lines.get(i+2);
        entries.add(newEntry);
    }You could also do both of the above in one run, but I think you will understand better what's happening if you do one thing at a time.
    If you don't want to put the entries in an encapsulating class, you can still access this without looping:
    int listStartIdx = <desired_entry_index>*ENTRY_SIZE;
    String att1 = lines.get(listStartIdx).substring(1);
    String att2 = lines.get(listStartIdx+1).substring(1);
    String att3 = lines.get(listStartIdx+2).substring(1);

  • Please Help with text parsing problem

    Hello,
    I have the following text in a file (cut and pasted from VI)
    12 15 03 12 15 03 81 5 80053 1 1,2,3 $23.00 1 ^M
    12 15 03 12 15 03 81 5 84550 1 1,2,3 $15.00 1 ^M
    12 15 03 12 15 03 81 5 84100 1 1,2,3 $15.00 1 ^M
    12 15 03 12 15 03 81 5 83615 1 1,2,3 $15.00 1 ^M
    12 15 03 12 15 03 81 5 82977 1 1,2,3 $15.00 1 ^M
    12 15 03 12 15 03 81 5 80061 1 1,2,3 $44.00 1 ^M
    12 15 03 12 15 03 81 5 83721 1 1,2,3 $15.00 1 ^M
    12 15 03 12 15 03 81 5 84439 1 1,2,3 $44.00 1 ^M
    12 15 03 12 15 03 81 5 84443 1 1,2,3 $40.00 1 ^M
    12 15 03 12 15 03 81 5 85025 1 1,2,3 $26.00 1 ^M
    12 15 03 12 15 03 81 5 85008 1 1,2,3 $5.00 1 ^M
    this method reads the text from a file and stores it in a ArrayList
        public ArrayList readInData(){
            File claimFile = new File(fullClaimPath);
            ArrayList returnDataAL = new ArrayList();
            if(!claimFile.exists()){
                System.out.println("Error: claim data - File Not Found");
                System.exit(1);
            try{
                BufferedReader br = new BufferedReader(new FileReader(claimFile));
                String s;
                while ((s = br.readLine()) != null){
                         System.out.println(s + " HHHH");
                        returnDataAL.add(s);
            }catch(Exception e){ System.out.println(e);}
            return returnDataAL;
        }//close loadFile()if i print the lines from above ... from the arraylist ... here is waht i get ...
    2 15 03 12 15 03 81 5 80053 1 1,2,3 $23.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 84550 1 1,2,3 $15.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 84100 1 1,2,3 $15.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 83615 1 1,2,3 $15.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 82977 1 1,2,3 $15.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 80061 1 1,2,3 $44.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 83721 1 1,2,3 $15.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 84439 1 1,2,3 $44.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 84443 1 1,2,3 $40.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 85025 1 1,2,3 $26.00 1 HHHH
    HHHH
    12 15 03 12 15 03 81 5 85008 1 1,2,3 $5.00 1 HHHH
    HHHH
    I see the ^M on the end of the lines ... but i dont understand why im getting the blank lines
    in between each entry ... I printed "HHHH" just to help with debugging ... anyone have any ideas why i am getting the extra blank lines?
    thanks,
    jd

    maybe its a FileReader deal.. Im not sure, maybe try using InputStreams. This code works for me (it reads from data.txt), give it a try and see if it works:
    import java.io.*;
    public class Example {
         public Example() throws IOException {
              BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("data.txt")));
              String s = "";
              while ((s = b.readLine()) != null) {
                   System.out.println(s);
              b.close();
         public static void main(String[] args) {
              try {
                   new Example();
              catch (IOException e) {
                   e.printStackTrace();
    }

  • Help with Paint program.

    Hello. I am somewhat new to Java and I was recently assigned to do a simple paint program. I have had no trouble up until my class started getting into the graphical functions of Java. I need help with my program. I am supposed to start off with a program that draws lines and changes a minimum of 5 colors. I have the line function done but my color change boxes do not work and I am able to draw inside the box that is supposed to be reserved for color buttons. Here is my code so far:
    // Lab13110.java
    // The Lab13 program assignment is open ended.
    // There is no provided student version for starting, nor are there
    // any files with solutions for the different point versions.
    // Check the Lab assignment document for additional details.
    import java.applet.Applet;
    import java.awt.*;
    public class Lab13110 extends Applet
         int[] startX,startY,endX,endY;
         int currentStartX,currentStartY,currentEndX,currentEndY;
         int lineCount;
         Rectangle red, green, blue, yellow, black;
         int numColor;
         Image virtualMem;
         Graphics gBuffer;
         int rectheight,rectwidth;
         public void init()
              startX = new int[100];
              startY = new int[100];
              endX = new int[100];
              endY = new int[100];
              lineCount = 0;
              red = new Rectangle(50,100,25,25);
              green = new Rectangle(50,125,25,25);
              blue = new Rectangle(50,150,25,25);
              yellow = new Rectangle(25,112,25,25);
              black = new Rectangle(25,137,25,25);
              numColor = 0;
              virtualMem = createImage(100,600);
              gBuffer = virtualMem.getGraphics();
              gBuffer.drawRect(0,0,100,600);
         public void paint(Graphics g)
              for (int k = 0; k < lineCount; k++)
                   g.drawLine(startX[k],startY[k],endX[k],endY[k]);
              g.drawLine(currentStartX,currentStartY,currentEndX,currentEndY);
              g.setColor(Color.red);
              g.fillRect(50,100,25,25);
              g.setColor(Color.green);
              g.fillRect(50,125,25,25);
              g.setColor(Color.blue);
              g.fillRect(50,150,25,25);
              g.setColor(Color.yellow);
              g.fillRect(25,112,25,25);
              g.setColor(Color.black);
              g.fillRect(25,137,25,25);
              switch (numColor)
                   case 1:
                        g.setColor(Color.red);
                        break;
                   case 2:
                        g.setColor(Color.green);
                        break;
                   case 3:
                        g.setColor(Color.blue);
                        break;
                   case 4:
                        g.setColor(Color.yellow);
                        break;
                   case 5:
                        g.setColor(Color.black);
                        break;
                   case 6:
                        g.setColor(Color.black);
                        break;
              g.setColor(Color.black);
              g.drawRect(0,0,100,575);
         public boolean mouseDown(Event e, int x, int y)
              currentStartX = x;
              currentStartY = y;
              if(red.inside(x,y))
                   numColor = 1;
              else if(green.inside(x,y))
                   numColor = 2;
              else if(blue.inside(x,y))
                   numColor = 3;
              else if(yellow.inside(x,y))
                   numColor = 4;
              else if(black.inside(x,y))
                   numColor = 5;
              else
                   numColor = 6;
              repaint();
              return true;
         public boolean mouseDrag(Event e, int x, int y)
              int Rectheight = 500;
              int Rectwidth = 900;
              currentEndX = x;
              currentEndY = y;
              Rectangle window = new Rectangle(0,0,900,500);
              //if (window.inside(Rectheight,Rectwidth))
                   repaint();
              return true;
         public boolean mouseUp(Event e, int x, int y)
              int Rectheight = 500;
              int Rectwidth = 900;
              startX[lineCount] = currentStartX;
              startY[lineCount] = currentStartY;
              endX[lineCount] = x;
              endY[lineCount] = y;
              lineCount++;
              Rectangle window = new Rectangle(0,0,900,500);
              if (window.inside(Rectheight,Rectwidth))
                   repaint();
              return true;
         public void Rectangle(Graphics g, int x, int y)
              g.setColor(Color.white);
              Rectangle screen = new Rectangle(100,0,900,600);
    }If anyone could point me in the right direction of how to go about getting my buttons to work and fixing the button box, I would be greatly appreciative. I just need to get a little bit of advice and I think I should be good after I get this going.
    Thanks.

    This isn't in any way a complete solution, but I'm posting code for a mouse drag outliner. This may be preferable to how you are doing rectangles right now
    you are welcome to use and modify this code but please do not change the package and make sure that you tell your teacher where you got it from
    MouseDragOutliner.java
    package tjacobs.ui;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Stroke;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    * See the public static method addAMouseDragOutliner
    public class MouseDragOutliner extends MouseAdapter implements MouseMotionListener {
         public static final BasicStroke DASH_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 10.0f, new float[] {8, 8}, 0);
         private boolean mUseMove = false;
         private Point mStart;
         private Point mEnd;
         private Component mComponent;
         private MyRunnable mRunner= new MyRunnable();
         private ArrayList mListeners = new ArrayList(1);
         public MouseDragOutliner() {
              super();
         public MouseDragOutliner(boolean useMove) {
              this();
              mUseMove = useMove;
         public void mouseDragged(MouseEvent me) {
              doMouseDragged(me);
         public void mousePressed(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseEntered(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseReleased(MouseEvent me) {
              Iterator i = mListeners.iterator();
              Point end = me.getPoint();
              while (i.hasNext()) {
                   ((OutlineListener)i.next()).mouseDragEnded(mStart, end);
              //mStart = null;
         public void mouseMoved(MouseEvent me) {
              if (mUseMove) {
                   doMouseDragged(me);
         public     void addOutlineListener(OutlineListener ol) {
              mListeners.add(ol);
         public void removeOutlineListener(OutlineListener ol) {
              mListeners.remove(ol);
         private class MyRunnable implements Runnable {
              public void run() {
                   Graphics g = mComponent.getGraphics();
                   if (g == null) {
                        return;
                   Graphics2D g2 = (Graphics2D) g;
                   Stroke s = g2.getStroke();
                   g2.setStroke(DASH_STROKE);
                   int x = Math.min(mStart.x, mEnd.x);
                   int y = Math.min(mStart.y, mEnd.y);
                   int w = Math.abs(mEnd.x - mStart.x);
                   int h = Math.abs(mEnd.y - mStart.y);
                   g2.setXORMode(Color.WHITE);
                   g2.drawRect(x, y, w, h);
                   g2.setStroke(s);
         public void doMouseDragged(MouseEvent me) {
              mEnd = me.getPoint();
              if (mStart != null) {
                   mComponent = me.getComponent();
                   mComponent.repaint();
                   SwingUtilities.invokeLater(mRunner);
         public static MouseDragOutliner addAMouseDragOutliner(Component c) {
              MouseDragOutliner mdo = new MouseDragOutliner();
              c.addMouseListener(mdo);
              c.addMouseMotionListener(mdo);
              return mdo;
         public static interface OutlineListener {
              public void mouseDragEnded(Point start, Point finish);
         public static void main(String[] args) {
              JFrame f = new JFrame("MouseDragOutliner Test");
              Container c = f.getContentPane();
              JPanel p = new JPanel();
              //p.setBackground(Color.BLACK);
              c.add(p);
              addAMouseDragOutliner(p);
              f.setBounds(200, 200, 400, 400);
              f.addWindowListener(new WindowClosingActions.Exit());
              f.setVisible(true);
    }

  • Help with: oracle.toplink.essentials.exceptions.ValidationException

    hi guys,
    I really need ur help with this.
    I have a remote session bean that retrieves a list of books from the database using entity class and I call the session bean from a web service. The problem is that when i display the books in a jsp directly from the session bean everything works ok but the problem comes when I call the session bean via the web service than it throws this:
    Exception Description: An attempt was made to traverse a relationship using indirection that had a null Session. This often occurs when an entity with an uninstantiated LAZY relationship is serialized and that lazy relationship is traversed after serialization. To avoid this issue, instantiate the LAZY relationship prior to serialization.
    at oracle.toplink.essentials.exceptions.ValidationException.instantiatingValueholderWithNullSession(ValidationException.java:887)
    at oracle.toplink.essentials.internal.indirection.UnitOfWorkValueHolder.instantiate(UnitOfWorkValueHolder.java:233)
    at oracle.toplink.essentials.internal.indirection.DatabaseValueHolder.getValue(DatabaseValueHolder.java:105)
    at oracle.toplink.essentials.indirection.IndirectList.buildDelegate(IndirectList.java:208)
    at oracle.toplink.essentials.indirection.IndirectList.getDelegate(IndirectList.java:330)
    at oracle.toplink.essentials.indirection.IndirectList$1.<init>(IndirectList.java:425)
    at oracle.toplink.essentials.indirection.IndirectList.iterator(IndirectList.java:424)
    at com.sun.xml.bind.v2.runtime.reflect.Lister$CollectionLister.iterator(Lister.java:278)
    at com.sun.xml.bind.v2.runtime.reflect.Lister$CollectionLister.iterator(Lister.java:265)
    at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.serializeListBody(ArrayElementProperty.java:129)
    at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:152)
    at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:322)
    at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:681)
    at com.sun.xml.bind.v2.runtime.property.ArrayElementNodeProperty.serializeItem(ArrayElementNodeProperty.java:65)
    at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.serializeListBody(ArrayElementProperty.java:168)
    at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:152)
    at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:322)
    at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:681)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:277)
    at com.sun.xml.bind.v2.runtime.BridgeImpl.marshal(BridgeImpl.java:100)
    at com.sun.xml.bind.api.Bridge.marshal(Bridge.java:141)
    at com.sun.xml.ws.message.jaxb.JAXBMessage.writePayloadTo(JAXBMessage.java:315)
    at com.sun.xml.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:142)
    at com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:108)
    at com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:258)
    at com.sun.xml.ws.transport.http.HttpAdapter.encodePacket(HttpAdapter.java:320)
    at com.sun.xml.ws.transport.http.HttpAdapter.access$100(HttpAdapter.java:93)
    at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:454)
    at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:244)
    at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:135)
    at com.sun.enterprise.webservice.JAXWSServlet.doPost(JAXWSServlet.java:176)
    ... 29 more
    This happens when I test the web service using netbeans 6.5.
    here's my code:
    session bean:
    ArrayList bookList = null;
    public ArrayList retrieveBooks()
    try
    List list = em.createNamedQuery("Book.findAll").getResultList();
    bookList = new ArrayList(list);
    catch (Exception e)
    e.getCause();
    return bookList;
    web service:
    @WebMethod(operationName = "retrieveBooks")
    public Book[] retrieveBooks()
    ArrayList list = ejbUB.retrieveBooks();
    int size = list.size();
    Book[] bookList = new Book[size];
    Iterator it = list.iterator();
    int i = 0;
    while (it.hasNext())
    Book book = (Book) it.next();
    bookList[i] = book;
    i++;
    return bookList;
    Please help guys, it's very urgent

    Yes i have a relationship but i didnt want it to be directly. Maybe this is a design problem but in my case I dont expect any criminals to be involved in lawsuit. My tables are like that:
    CREATE TABLE IF NOT EXISTS Criminal(
         criminal_id INTEGER NOT NULL AUTO_INCREMENT,
         gender varchar(1),
         name varchar(25) NOT NULL,
         last_address varchar(100),
         birth_date date,
         hair_color varchar(10),
         eye_color varchar(10),
         weight INTEGER,
         height INTEGER,
         PRIMARY KEY (criminal_id)
    ENGINE=INNODB;
    CREATE TABLE IF NOT EXISTS Lawsuit(
         lawsuit_id INTEGER NOT NULL AUTO_INCREMENT,
         courtName varchar(25),
         PRIMARY KEY (lawsuit_id),
         FOREIGN KEY (courtName) REFERENCES Court_of_Law(courtName) ON DELETE NO ACTION
    ENGINE=INNODB;
    CREATE TABLE IF NOT EXISTS Rstands_trial(
         criminal_id INTEGER,
         lawsuit_id INTEGER,
         PRIMARY KEY (criminal_id, lawsuit_id),
         FOREIGN KEY (criminal_id) REFERENCES Criminal(criminal_id) ON DELETE NO ACTION,
         FOREIGN KEY (lawsuit_id) REFERENCES Lawsuit(lawsuit_id) ON DELETE CASCADE
    ENGINE=INNODB;So I couldnt get it.

  • Help with BufferedImage and JPanel

    I have a program that should display some curves, but thats not the problem, the real problem is when i copy the image contained in the JPanel to the buffered image then i draw something there and draw it back to the JPanel. My panel initialy its white but after the operation it gets gray
    Please if some one could help with this
    here is my code divided in three classes
    //class VentanaPrincipal
    package gui;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JSeparator;
    import javax.swing.border.LineBorder;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    * This code was edited or generated using CloudGarden's Jigloo
    * SWT/Swing GUI Builder, which is free for non-commercial
    * use. If Jigloo is being used commercially (ie, by a corporation,
    * company or business for any purpose whatever) then you
    * should purchase a license for each developer using Jigloo.
    * Please visit www.cloudgarden.com for details.
    * Use of Jigloo implies acceptance of these licensing terms.
    * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
    * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
    * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
    public class VentanaPrincipal extends javax.swing.JFrame {
              //Set Look & Feel
              try {
                   javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch(Exception e) {
                   e.printStackTrace();
         private JMenuItem helpMenuItem;
         private JMenu jMenu5;
         private JMenuItem deleteMenuItem;
         private JSeparator jSeparator1;
         private JMenuItem pasteMenuItem;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel3;
         private JLabel jLabel2;
         private JLabel jLabel1;
         private JButton jSPLineButton;
         private JButton jHermiteButton;
         private JButton jBezierButton;
         private JPanel jPanel2;
         private JPanel jPanel1;
         private JMenuItem jResetMenuItem1;
         private JMenuItem copyMenuItem;
         private JMenuItem cutMenuItem;
         private JMenu jMenu4;
         private JMenuItem exitMenuItem;
         private JSeparator jSeparator2;
         private JMenu jMenu3;
         private JMenuBar jMenuBar1;
          * Variables no autogeneradas
         private int botonSeleccionado;
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              VentanaPrincipal inst = new VentanaPrincipal();
              inst.setVisible(true);
         public VentanaPrincipal() {
              super();
              initGUI();
         private void initGUI() {
              try {
                        this.setTitle("Info3 TP 2");
                             jPanel1 = new pizarra();
                             getContentPane().add(jPanel1, BorderLayout.WEST);
                             jPanel1.setPreferredSize(new java.awt.Dimension(373, 340));
                             jPanel1.setMinimumSize(new java.awt.Dimension(10, 342));
                             jPanel1.setBackground(new java.awt.Color(0,0,255));
                             jPanel1.setBorder(BorderFactory.createCompoundBorder(
                                  new LineBorder(new java.awt.Color(0, 0, 0), 1, true),
                                  null));
                             BufferedImage bufimg = (BufferedImage)jPanel1.createImage(jPanel1.getWidth(), jPanel1.getHeight());
                             ((pizarra) jPanel1).setBufferedImage(bufimg);
                             jPanel2 = new JPanel();
                             getContentPane().add(jPanel2, BorderLayout.CENTER);
                             GridBagLayout jPanel2Layout = new GridBagLayout();
                             jPanel2Layout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
                             jPanel2Layout.rowHeights = new int[] {69, 74, 76, 71};
                             jPanel2Layout.columnWeights = new double[] {0.0, 0.0, 0.1};
                             jPanel2Layout.columnWidths = new int[] {83, 75, 7};
                             jPanel2.setLayout(jPanel2Layout);
                                  jBezierButton = new JButton();
                                  jPanel2.add(jBezierButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jBezierButton.setText("Bezier");
                                  jBezierButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jBezierButton.addActionListener(new ActionListener() {
                                       public void actionPerformed(ActionEvent evt) {
                                            bezierActionPerformed();
                                  jHermiteButton = new JButton();
                                  jPanel2.add(jHermiteButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jHermiteButton.setText("Hermite");
                                  jHermiteButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jSPLineButton = new JButton();
                                  jPanel2.add(jSPLineButton, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jSPLineButton.setText("SP Line");
                                  jSPLineButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jLabel1 = new JLabel();
                                  jPanel2.add(jLabel1, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                                  jLabel1.setText("Posicion Mouse");
                                  jLabel2 = new JLabel();
                                  jPanel2.add(jLabel2, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel2.setText("X:");
                                  jLabel3 = new JLabel();
                                  jPanel2.add(jLabel3, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel3.setText("Y:");
                                  jLabel4 = new JLabel();
                                  jPanel2.add(jLabel4, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel4.setText("-");
                                  jLabel5 = new JLabel();
                                  jPanel2.add(jLabel5, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel5.setText("-");
                   this.setSize(600, 400);
                        jMenuBar1 = new JMenuBar();
                        setJMenuBar(jMenuBar1);
                             jMenu3 = new JMenu();
                             jMenuBar1.add(jMenu3);
                             jMenu3.setText("Archivo");
                                  jSeparator2 = new JSeparator();
                                  jMenu3.add(jSeparator2);
                                  exitMenuItem = new JMenuItem();
                                  jMenu3.add(exitMenuItem);
                                  exitMenuItem.setText("Exit");
                                  jResetMenuItem1 = new JMenuItem();
                                  jMenu3.add(jResetMenuItem1);
                                  jResetMenuItem1.setText("Reset");
                             jMenu4 = new JMenu();
                             jMenuBar1.add(jMenu4);
                             jMenu4.setText("Edit");
                                  cutMenuItem = new JMenuItem();
                                  jMenu4.add(cutMenuItem);
                                  cutMenuItem.setText("Cut");
                                  copyMenuItem = new JMenuItem();
                                  jMenu4.add(copyMenuItem);
                                  copyMenuItem.setText("Copy");
                                  pasteMenuItem = new JMenuItem();
                                  jMenu4.add(pasteMenuItem);
                                  pasteMenuItem.setText("Paste");
                                  jSeparator1 = new JSeparator();
                                  jMenu4.add(jSeparator1);
                                  deleteMenuItem = new JMenuItem();
                                  jMenu4.add(deleteMenuItem);
                                  deleteMenuItem.setText("Delete");
                             jMenu5 = new JMenu();
                             jMenuBar1.add(jMenu5);
                             jMenu5.setText("Help");
                                  helpMenuItem = new JMenuItem();
                                  jMenu5.add(helpMenuItem);
                                  helpMenuItem.setText("Help");
              } catch (Exception e) {
                   e.printStackTrace();
         private void bezierActionPerformed(){
              botonSeleccionado = 1;
              ((pizarra) jPanel1).setTipoFigura(botonSeleccionado);
              ((pizarra) jPanel1).pintarGrafico();
    //class graphUtils
    package func;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.image.BufferedImage;
    public class graphUtils {
         public static void dibujarPixel(BufferedImage img, int x, int y, int color){
              img.setRGB(x, y, color);
         public static void dibujarLinea(BufferedImage img, int x0, int y0, int x1, int y1, int color){
            int dx = x1 - x0;
            int dy = y1 - y0;
            if (Math.abs(dx) > Math.abs(dy)) {          // Pendiente m < 1
                float m = (float) dy / (float) dx;     
                float b = y0 - m*x0;
                if(dx < 0) dx = -1; else dx = 1;
                while (x0 != x1) {
                    x0 += dx;
                    dibujarPixel(img, x0, Math.round(m*x0 + b), color);
            } else
            if (dy != 0) {                              // Pendiente m >= 1
                float m = (float) dx / (float) dy;
                float b = x0 - m*y0;
                if(dy < 0) dy = -1; else dy = 1;
                while (y0 != y1) {
                    y0 += dy;
                    dibujarPixel(img, Math.round(m*y0 + b), y0, color);
         public static void dibujarBezier(BufferedImage img, Point puntos, int color){
    //class pizarra
    package gui;
    import javax.swing.*;
    import sun.awt.VerticalBagLayout;
    import sun.security.krb5.internal.bh;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.util.ArrayList;
    import func.graphUtils;
    * esta clase pizarra extiende la clase JPanel y se agregan las funciones de pintado
    * y rellenado que se muestra en pantalla dentro del panel que se crea con esta clase
    * @author victorg
    public class pizarra extends JPanel implements MouseListener{
         private int tipoFigura;
         BufferedImage bufferImagen;
         Image img;
         Graphics img_gc;
         private Color colorRelleno, colorLinea;
         private Point puntosBezier[] = new Point[3];
         public pizarra(){
              super();          
              addMouseListener(this);
              //this.setBackground(Color.BLUE);
              colorLinea = Color.BLUE;
         public void setTipoFigura(int seleccion){
              // se setea para ver si es bezier, hermite, SP line
              tipoFigura = seleccion;
         public void setTipoRelleno(int seleccion){
         public void setColorRelleno(Color relleno){
              colorRelleno = relleno;          
         public void setColorLinea(Color linea){
              colorLinea = linea;
         public void setBufferedImage(BufferedImage bufimg){
              bufferImagen = bufimg;
         public void pintarGrafico(){
              Graphics g = this.getGraphics();     
              g.setColor(colorLinea);
              //accion ejecutada cuando se selecciona para graficar un poligono
              if(tipoFigura == 1){// bezier
                   if(bufferImagen == null){
                        //mantiene guardada la imagen cuando la pantalla pasa a segundo plano
                        bufferImagen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
                        this.setBackground(Color.WHITE);                                                  
                        bufferImagen = (BufferedImage)createImage(getWidth(), getHeight());
                        //bufferImagen = this.createImage(getWidth(), getHeight());
                   //g.drawImage(bufferImagen,0,0,this);
                   graphUtils.dibujarLinea(bufferImagen,10, 10, 50, 50, colorLinea.getRGB());
                   g.drawImage(bufferImagen,0,0,this);
         protected void paintComponent(Graphics g) { // llamado al repintar
              //setBackground(colorFondo);
              super.paintComponent(g);
    //          Graphics2D g2 = (Graphics2D)g;          
    //          g2.drawImage(bufferImagen, 0,0, this);          
    //          g2.dispose();     
         public void mouseClicked(MouseEvent arg0) {          
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
    }

    1) Swing related questions should be posted in the Swing forum.
    Custom painting should be done in the paintComponent(..) method. You created a "pintarGraphico" method to do the custom painting, but that method is only execute once. When Java determines that the panel needs to be repainted, the paintComponent() method is executed which simply does a super.paintComponent(), which in turn simply paints the background of the panel overwriting you custom painting.

  • Working with arraylists in JavaScript????

    I am getting a script error while trying to use an ArrayList inside a JavaScript method. How will i store the list???.My code is as follows :
    obj1[<c:out value="${count.count}"/>]=<c:out value="${formids.excludeList}"/>
    where 'excludeList' is an arrayList and it has the value [yellow,green] i am getting a JavaScript error that 'yellow' is undefined. I tried to declare obj1 as :-
    var obj1 = new Array(count); and var obj1 = new Object();
    still it was showing errors. I tried putting single values like integers into the array and it worked but not with arraylists. Can anyone pls help.

    Are yellow and green supposed to be string values in JS? If so, you will have to enclose them in quoted. Add a loop to fill in the JS array:
    var obj1 = new Array(count); //Can't be count or count.count  Must be the length of the List
    <c:forEach var="color" items="${formids.excludeList}" varStatus="innerCount">
      obj1[<cout value="${innerCount.count}"/>] = "<c:out value="<c:out value="${color}"/>";
    </c:forEach>

Maybe you are looking for

  • MacPro eSata Port/Card doesn't work with new Hard Disk

    I just bought 4 x 3TB Hard Disc http://tinyurl.com/d2rglvn (specs of disc) Which I put in Macally Enclosures to work on my Barracuda internal Hard Drive externally http://tinyurl.com/clg8yjo I already have like 5 x 1,5 TB that works perfectly well wi

  • How can I insert an existing ApDiv into a tab in the Spry Tabbed Panel?

    I have 5 of them all containing nested Apdiv within nested ApDivs (a long storie ) that I would like to insert into 5 tabs in the Spry Tabbed Panel. Please help.

  • Am I able to change my greeting message on a lost iphone 5?

    I lost my iphone.. I put it in Lost Mode..hopeing an honest person will return it. My greeting needs to be changed so that my customers know the phone has been lost.  I would like to leave an alternative number for them to call.

  • What is field symbols?

    Hi all, Can anyone explains what is Fiels symbol and significance of that with examples? Thanks Shiva

  • Vertical page swipe stutters

    when testing on an ipad, my folio has a pronounced visual stutter each time i try to swipe to the next page. this only happens with vertical swiping, and if i specify horizontal, it's smooth. any suggestions?