Bubble sort problem:ArrayIndexOutOfBoundsException,

I'm supposed to calculate most and least rainfall but my method goes out of bounds? I think mabey Its cause my count starts at zero...It was functioning before I switched out variables.It was not working accurately. After 4 hours Im stumpted.Am i overlooking something syntaxal of are my loops not logical? Thanks Stars!
import java.util.Scanner;
public class Rainfall2
   public static void main(String[]args)
           double []mrt = new double[12];  
            getRainfall(mrt);
            getAvgrainfall(mrt);
            getMonthMostrain(mrt);
            getMonthLeastrain(mrt);
    public  static void getRainfall(double []mrt)
          for (int i = 0; i < mrt.length; i++)
              Scanner keyboard=new Scanner(System.in);
              System.out.println("Input Monthy Rain Total for month #" +(i+1));
             mrt=keyboard.nextInt();
          System.out.println(" Monthy Rain Total for month #" +(i+1)+ " is " +mrt[i] + " inches");
          if(mrt[i]<0)
          { System.out.println("Input Monthly Rain Total of Zero or greater!!!");
               System.out.println("Input Monthy Rain Total for month #" +(i+1));
               mrt[i]=keyboard.nextInt();
public static void getAvgrainfall(double []mrt)
               int month=0;
          double avg;
          avg=0.0;     
                         for (int i=0;i<mrt.length;i++)
                    avg=avg+mrt[i];
                    avg=avg/12;
               System.out.println("Average rainfall is " + avg + " inches.");
               public static void getMonthMostrain(double []mrt)
                    int rC=0;
                    double temp;
                    temp =mrt[0];
               for (int i=0;i<12;i++)
                    if (mrt[i] >mrt[(i+1)])
               temp =i;
               System.out.println("The most rainfall fell in Month # "+ rC);
               public static void getMonthLeastrain(double []mrt)
                    int rC=0;
               for (int i = 0; i < 11; i++)
                         if (mrt[i] < mrt[i+1])
                    rC = i;
                    System.out.println("The least rainfall fell in Month # "+ rC);

I changed the 12 to 11
when values 1 to12 inches are entered it says
The most rainfall fell in Month # 1
The least rainfall fell in Month # 11
when i enter 12 inches 11...10 to 1 it reads
The most rainfall fell in Month # 1
The least rainfall fell in Month # 1
On top of that what if 2 rainfall months were the same or 0
I guess theres supposed to be much more to this loop...
Is it typical to have to work on this for 6 hours or does it depend on your
apptitude for logic or something????Thanks again for your suggestions!
import java.util.Scanner;
public class Rainfall4
   public static void main(String[]args)
           double []mrt = new double[12];  
            getRainfall(mrt);
            getAvgrainfall(mrt);
            getMonthMostrain(mrt);
            getMonthLeastrain(mrt);
    public  static void getRainfall(double []mrt)
          for (int i = 0; i < mrt.length; i++)
              Scanner keyboard=new Scanner(System.in);
              System.out.println("Input Monthy Rain Total for month #" +(i+1));
             mrt=keyboard.nextInt();
          System.out.println(" Monthy Rain Total for month #" +(i+1)+ " is " +mrt[i] + " inches");
          if(mrt[i]<0)
          { System.out.println("Input Monthly Rain Total of Zero or greater!!!");
               System.out.println("Input Monthy Rain Total for month #" +(i+1));
               mrt[i]=keyboard.nextInt();
public static void getAvgrainfall(double []mrt)
               int month=0;
          double avg;
          avg=0.0;     
                         for (int i=0;i<mrt.length;i++)
                    avg=avg+mrt[i];
                    avg=avg/12;
               System.out.println("Average rainfall is " + avg + " inches.");
               public static void getMonthMostrain(double []mrt)
                    int rC=0;
                    double temp;
                    temp =mrt[0];
               for (int i=0;i<11;i++)// changed to 11
                    if (mrt[i] >mrt[(i+1)])
               temp =i;
               System.out.println("The most rainfall fell in Month # "+ (rC+1));//changed to rC +1
               public static void getMonthLeastrain(double []mrt)
                    int rC=0;
               for (int i = 0; i < 11; i++)
                         if (mrt[i] < mrt[i+1])
                    rC = i;
                    System.out.println("The least rainfall fell in Month # "+ (rC+1));//changed to rC+1

Similar Messages

  • File and bubble sort problem

    hey, I'm in a bit of a pickle.
    I'm trying to read from a file then bubble sort the file then write that to another file. Any suggestions how I can go about this. I've managed to read from the file, but have no idea how to bubble sort it.
    Any useful suggestions would be appreaciated

    Find the code below to read the numbers from nonsorted.txt frile in d: Drive and outputs the sorted into sorted.txt
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    public class BubbleSort {
         static StringBuffer newFile;
         static String FileNamewithpath = "d:/nonsorted.txt";
         static String NewFileNamewithpath = "d:/sorted.txt";
         static ArrayList numberList;
          * @param args
              public static void main(String args[]) {
                   newFile = new StringBuffer();
                   numberList = new ArrayList<Integer>();
                   try {
                        FileInputStream fstream = new FileInputStream(FileNamewithpath);
                        DataInputStream in = new DataInputStream(fstream);
                        StringBuffer sb = new StringBuffer();
                        // there are still some left to read
                        while (in.available() != 0) {
                             getNumbers(in.readLine());
                        in.close();
                        System.out.println(numberList);
                        numberList =  bubbleSortElements(numberList);
                        for (int i =0; i< numberList.size(); i++) {
                             newFile.append(Integer.parseInt(""+numberList.get(i)) + " ");
                        FileOut();
                   } catch (Exception e) {
                        e.printStackTrace();
                        System.err.println("File input error");
              public static void getNumbers(String str) {
                   StringTokenizer st = new StringTokenizer(str);
                   int i =0;
                   while (st.hasMoreTokens()) {
                        String word = st.nextToken();
                        numberList.add(word);
                        i++;
                   //return null;
              public static void FileOut() {
                   FileOutputStream out; // declare a file output object
                   PrintStream p; // declare a print stream object
                   try {
                        out = new FileOutputStream(NewFileNamewithpath);
                        p = new PrintStream(out);
                        p.println(newFile);
                        p.close();
                   } catch (Exception e) {
                        System.err.println("Error writing to file");
         public static  ArrayList bubbleSortElements(ArrayList numList ){
         try {
              int tmp;
              for (int i=0; i<numList.size()-1; i++) {
                     for (int j=0; j<numList.size()-1-i; j++)
                       if (Integer.parseInt(""+numList.get(j+1)) < Integer.parseInt(""+numList.get(j))) {  /* compare the two neighbors */
                         tmp = Integer.parseInt(""+numList.get(j));         /* swap a[j] and a[j+1]      */
                         numList.set(j,numList.get(j+1));
                         numList.set(j+1,tmp);
         } catch(Exception e) {
              e.printStackTrace();
              return numList;
    }

  • Problem Bubble sorting random array

    For my CompSci class I have to create an array with random number in it and then do a bubble sort. I was able to create the array and input the variables in it but when it bubble sorts the array none of the values in the sorted array correlate to the original integers in the array.
    Any help would be greatly appreciated.
    public class RandomSort {
    public static void main(String[] args) {
        final int ARRAY_SIZE = 20;
        final int RAND_MIN = 0;
        final int RAND_MAX = 100;
        int [] randomSort = new int [ARRAY_SIZE];
        int i;
        for (i = 0; i < randomSort.length; i++)
            randomSort[i] = (int) (Math.random()*(((RAND_MAX - RAND_MIN)+1)+RAND_MIN));
        for (i=0; i<ARRAY_SIZE; i++)
                for (int j = 0; j <=i-1; j++)
                        if (randomSort[j] > randomSort [j+1])
                            int temp = randomSort[j];
                            randomSort[j] = randomSort[j+1];
                            randomSort[j+1] = temp;
                System.out.println(randomSort);

    Mmmhhh....
    for (i = 0; i < ARRAY_SIZE; i++) {
         for (int j = ARRAY_SIZE - 1; j >= i + 1; j--) {
              if (randomSort[j - 1] > randomSort[j]) {
                   final int temp = randomSort[j - 1];
                   randomSort[j - 1] = randomSort[j];
                   randomSort[j] = temp;
         System.out.println(randomSort);
    Pffff....9
    31
    32
    33
    34
    36
    37
    39
    45
    63
    64
    81
    84
    85
    86
    91
    94
    94
    99
    100Aarrfff...  [http://en.wikipedia.org/wiki/Bubble_sort|http://en.wikipedia.org/wiki/Bubble_sort]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Multidimensional Array and Bubble Sorting

    Goal:
    Bubble sort the array. I want to keep the data organized. So, 70 with aa, 20 with cc, 40 with ee and so foth.
    Example output....
    aa 70
    bb 30
    cc 40
    dd 90
    then..... by number
    ee 10
    cc 20
    bb 30
    ee 40
    Problem:
    I dont know how to bubble sort by letters. AND, a big and..., and I have not done a double array like this. (can you tell?) :)
    package bubleexample;
    public class BubbleSort
         public BubbleSort ()
         public void sortIntArray (int []  pIntArr)
              int     cnt;
              int     tmp = -1;
              for (int a = 0; a < pIntArr.length - 1; a++)
                   for (cnt = 0; cnt < pIntArr.length - 1; cnt++)
                        if (pIntArr [cnt] > pIntArr [cnt + 1])
                             tmp = pIntArr [cnt];
                             pIntArr [cnt] = pIntArr [cnt + 1];
                             pIntArr [cnt + 1] = tmp;
         public void displayArray (int [] pIntArray)
              for (int cnt = 0; cnt < pIntArray.length; cnt++)
                   System.out.println ("Array[" + cnt + "]: " + pIntArray [cnt]);
         public static void main (String []  args)
              int []  myNumberList = { 70, 20, 40, 10, 80, 60, 30 , 50, 30, 90 };
            String [] myLetterList = { "aa", "cc", "ee", "xx", "bb", "tt", "gg", "rr", "jj", "dd" };
              BubbleSort sortIntArray = new BubbleSort ();
              System.out.println ("Before Sorting");
              sortIntArray.displayArray (myNumberList);
            //sortStringtArray.displayArray (myLetterList);
              sortIntArray.sortIntArray (myNumberList);
            //sortStringArray.sortStringArray (myLetterList);
              System.out.println ("\nAfter Sorting");
              sortIntArray.displayArray (myNumberList);
            //sortStringArray.displayArray (myLetterList);
              System.exit (0);
    }If something is unclear, please let me know.

    incomplete example:
    class Movie
         private String name;
         private int rating;
         public Movie( String name, int rating )
              this.name = name;
              this.rating = rating;
         public String getName() { ..... }
         public int getRating() { ...... }
         public String toString() {} // recommended but you don't have to
    } // end of class Movie
    public class SortString2
         public static sort(..) {...}
         public static void main( String args[] )
              String[] names = {"Meet the Fockers","Blade",...};
              int[] ratings = {5,3,4,...}
              Movie[] movies = makeMovieArray( names, ratings );
              sort( movies );
              System.out.println(...);
              for ( Movie movie : movies )
                   System.out.printf( "movie:  %s\nrating:  %d\n\n", movie.getName(), movie.getRating() );
         public static Movie[] makeMovieArray( String[] names, int[] ratings )
              Movie[] movies;
              if ( names.length == ratings.length )
                   movies = new Movie[names.length];
                   for ( int i=0; i<names.length; i++ )
                        movies[i] = new Movie(names,ratings[i]);
                   return movies;
              else
                   return;
    } // end of class SortString2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Two D bubble sort

    hello i'm trying to program a bubble sort with two D arrays..
    i have one-D array bubble sort but i couldn't figure out how the two D would work with the counter ..in my case..count1.
    public class BubbleSort {
    final int NUM = 20;
    int num[] = new int [NUM];
    int temp;
    public void input (){
    for (byte count = 0; count < NUMELEM; count ++)
         num[count] = (int)(Math.random()*2000)+1;
    public void BubbleSorting (){
         boolean swap = true;
         byte count1 = 0;
         while ((swap) && (count1 < NUM-1)){
         swap = false;
         for (byte count2 = 0; count2 < ((NUM-1)-count1); count2++){
              if (num[count2] > num[count2+1]){
                   temp = num[count2];
                   num[count2] = num[count2+1];
                   num[count2+1] = temp;
                   swap = true;
         count1 ++;
         System.out.println ("List After Pass Number " + count1 + " :");
         output();
    thanks in advance!

    please explain ur problem.
    i couldn't understand ur problem

  • My bubble sort doesn't work, and does anyone know

    how to count and print the scores of a certain grade.... all the 90's with a's, all the 80's with b's etc.... This is my first java program with two classes. I've been messing with it for about 24hours over the last week. :O. Any suggestions?
    import java.util.Scanner;
    public class GradeSort {
         public static void main(String [] args){
              //Scanner keyboard = new Scanner(System.in);
              System.out.println("How many students took the test?");
              Scanner kbd = new Scanner(System.in);
              int NUM_STUDENTS = kbd.nextInt();
              double [] grades = new double[NUM_STUDENTS];//Assn array
              readReadingsInto(grades);
              System.out.printf( "\nThe average is %.3f%n", average(grades));
              print(grades);}
              private static void readReadingsInto(double [] array){
                   Scanner keyboard = new Scanner(System.in);
                   for (int i =0; i < array.length; i++) {
                   System.out.print("enter grade # " + (i+1)+ "/" );
              array[i] = keyboard.nextInt();
         public static double average(double [] anArray){
              double sum = 0.0;
              for (double item : anArray){
                   sum += item;
              return sum/anArray.length;
    public static void bubbleSort ( double [] anArray )
    for (double i = anArray.length-1; i > 0; i-- )
    for ( int j = 0; j < i; j++ )
    if ( anArray[j] > anArray[j+1] )
    double temp = anArray[j];
    anArray[j] = anArray[j+1];
    anArray[j+1] = temp;}
    public static void print(double [] arr) {
         for (int i = 0; i < arr.length; i++){
              Grade gRade = new Grade(arr);
              System.out.println("Reading #" + (i+1)+" " + arr[i] + " " + gRade.letter() );
              //Grade gRade = new Grade(reading);
              //System.out.println( gRade.letter() );
              //System.out.print ( grades[1] );
    public class Grade {
         public static final double MIN = 0.0;
         public static final double MAX = 100.0;
         public Grade(double gRade){
              if (gRade < MIN || gRade > MAX){
                   System.err.println("Grade(): bad argument recievived: " + gRade);
              } else {
                   myValue = gRade;
    public String letter(){
         if (myValue < MIN || myValue > MAX){ return "error";}
    else if (myValue >= 90){return "A";}
    else if (myValue >= 80){return "B";}
    else if (myValue >= 70){return "C";}
    else return "Fail";     }
    private double myValue;

    Let me see if I can fix the formatting for you. The bubble sort, isn't sorting? The print after the sort is in the same order as I input the data.
    import java.util.Scanner;
    public class GradeSort {
         public static void main(String [] args){
              //Scanner keyboard = new Scanner(System.in);
              System.out.println("How many students took the test?");
              Scanner kbd = new Scanner(System.in);
              int NUM_STUDENTS = kbd.nextInt();
              double [] grades = new double[NUM_STUDENTS];//Assn array
              readReadingsInto(grades);
              System.out.printf( "\nThe average is %.3f%n", average(grades));
              print(grades);}
              private static void readReadingsInto(double [] array){
                   Scanner keyboard = new Scanner(System.in);
                   for (int i =0; i < array.length; i++) {
                   System.out.print("enter grade # " + (i+1)+ "/" );
              array[i] = keyboard.nextInt();
         public static double average(double [] anArray){
              double sum = 0.0;
              for (double item : anArray){
                   sum += item;
              return sum/anArray.length;
    public static void bubbleSort ( double [] anArray )
            for (double i = anArray.length-1; i > 0; i-- )
              for ( int j = 0; j < i; j++ )
                  if ( anArray[j] > anArray[j+1] )
                        double temp = anArray[j];
                        anArray[j] = anArray[j+1];
                        anArray[j+1] = temp;}
    public static void print(double [] arr) {
         for (int i = 0; i < arr.length; i++){
              Grade gRade = new Grade(arr);
              System.out.println("Reading #" + (i+1)+" " + arr[i] + " " + gRade.letter() );
              //Grade gRade = new Grade(reading);
              //System.out.println( gRade.letter() );
              //System.out.print ( grades[1] );
    The other class is:
    public class Grade {
         public static final double MIN = 0.0;
         public static final double MAX = 100.0;
         public Grade(double gRade){
              if (gRade < MIN || gRade > MAX){
                   System.err.println("Grade(): bad argument recievived: " + gRade);
              } else {
                   myValue = gRade;
    public String letter(){
         if (myValue < MIN || myValue > MAX){ return "error";}
    else if (myValue >= 90){return "A";}
    else if (myValue >= 80){return "B";}
    else if (myValue >= 70){return "C";}
    else return "Fail";     }
    private double myValue;

  • How do i add a new data type in this Bubble sort

    i have tried to i add a new String data type (String publisher) but my program has an error.
    please show me
    // libmainsys.java
    // demonstrates bubble sort
    // to run this program: C>java BubbleSortApp
    class ArrayBub
    private String[] a; // ref to array a
    private int nElems; // number of data items
    public ArrayBub(int max) // constructor
    a = new String[max]; // create the array
    nElems = 0; // no items yet
    public void insert(String value) // put element into array
    a[nElems] = value; // insert it
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    System.out.print(a[j] + " "); // display it
    System.out.println("");
    public void bubbleSort()
    int out, in;
    for(out=nElems-1; out>1; out--) // outer loop (backward)
    for(in=0; in<out; in++) // inner loop (forward)
    if( a[in].compareTo(a[in+1])>0 ) // out of order?
    swap(in, in+1); // swap them
    } // end bubbleSort()
    private void swap(int one, int two)
    String temp = new String(a[one]);
    a[one] = a[two];
    a[two] = temp;
    } // end class ArrayBub
    class libmainsys
    public static void main(String[] args)
    int maxSize = 100; // array size
    ArrayBub arr; // reference to array
    arr = new ArrayBub(maxSize); // create the array
    arr.insert("Manuel"); // insert 10 items
    arr.insert("Portillo");
    arr.insert("Kike");
    arr.insert("Pedro");
    arr.insert("Mono");
    arr.insert("Cuca");
    arr.insert("Zoila");
    arr.insert("Karina");
    arr.insert("Joto");
    arr.display(); // display items
    arr.bubbleSort(); // bubble sort them
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys
    /////////////////////////////////////////////

    nope i mean like this
    // libmainsys.java
    // demonstrates bubble sort
    // to run this program: C>java BubbleSortApp
    class ArrayBub
    private String[] a; // ref to array a
    private Sting[] publisher;
    private int nElems; // number of data items
    public ArrayBub(int max) // constructor
    a = new String[max]; // create the array
    nElems = 0; // no items yet
    public void insert(String value) // put element into array
    a[nElems] = value; // insert it
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    System.out.print(a[j] + " "); // display it
    System.out.println("");
    public void bubbleSort()
    int out, in;
    for(out=nElems-1; out>1; out--) // outer loop (backward)
    for(in=0; in<out; in++) // inner loop (forward)
    if( a[in].compareTo(a[in+1])>0 ) // out of order?
    swap(in, in+1); // swap them
    } // end bubbleSort()
    private void swap(int one, int two)
    String temp = new String(a[one]);
    a[one] = a[two];
    a[two] = temp;
    } // end class ArrayBub
    class libmainsys
    public static void main(String[] args)
    int maxSize = 100; // array size
    ArrayBub arr; // reference to array
    arr = new ArrayBub(maxSize); // create the array
    arr.insert("Manuel"); // insert 10 items
    arr.insert("Portillo");
    arr.insert("Kike");
    arr.insert("Pedro");
    arr.insert("Mono");
    arr.insert("Cuca");
    arr.insert("Zoila");
    arr.insert("Karina");
    arr.insert("Joto");
    arr.display(); // display items
    arr.bubbleSort(); // bubble sort them
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys
    but i have no idea what to do next

  • Sorting Problem in FND_MENU_ENTRIES_TL Table

    Hi,
    FND_MENU_ENTRIES_TL Table storing the record FND_MENU_ENTRIES_TL_N1(MENU_ID,PROMPT,LANGUAGE) wise in R12. But whereas in 11i, records stored FND_MENU_ENTRIES_TL_U1(MENU_ID,ENTRY_SEQUENCE,LANGUAGE).
    I am confused, whether i need to recreate the index in R12, so the records will get store MENU_ID,ENTRY_SEQUENCE,LANGUAGE wise.
    Could any one please suggest me how to resolve this problem.
    Thanks,
    Praba T

    815667 wrote:
    Hi,
    FND_MENU_ENTRIES_TL Table storing the record FND_MENU_ENTRIES_TL_N1(MENU_ID,PROMPT,LANGUAGE) wise in R12. But whereas in 11i, records stored FND_MENU_ENTRIES_TL_U1(MENU_ID,ENTRY_SEQUENCE,LANGUAGE).
    I am confused, whether i need to recreate the index in R12, so the records will get store MENU_ID,ENTRY_SEQUENCE,LANGUAGE wise.
    Could any one please suggest me how to resolve this problem.
    Thanks,
    Praba TPl do not abuse the forums by cross-posting in multiple forums
    Sorting Problem in FND_MENU_ENTRIES_TL Table
    Sorting Problem in FND_MENU_ENTRIES_TL Table
    Your issue is related to EBS, not to database upgrades (which is the topic of this forum)
    Srini

  • How do I open a text file to sort using bubble sort?

    Hi,
    I have a text file, which is a list of #'s.. ex)
    0.001121
    0.313313
    0.001334
    how do you open a text file and read a list? I have the bubble sort code which sorts.. thanks

    I wrote this, but am getting a couple errors:
    import java.util.*;
    import java.io.*;
    public class sort
         public static void main(String[] args)
              String fileName = "numsRandom1024.txt";
              Scanner fromFile = null;
              int index = 0;
              double[] a = new double[1024];Don't use double. You should use something that implements Comparable, like java.lang.Double.
              try
                   fromFile = new Scanner(new File(fileName));
              catch (FileNotFoundException e)
    System.out.println("Error opening the file " +
    " + fileName);
                   System.exit(0);
              while (fromFile.hasNextLine())
                   String line = fromFile.nextLine();
                   a[index] = Double.parseDouble(line);Don't parse to a double, create a java.lang.Double instead.
                   System.out.println(a[index]);
                   index++;
              fromFile.close();
              bubbleSort( a, 0, a.length-1 );No. Don't use a.length-1: from index to a.length-1 all values will be null (if you use Double's). Call it like this:bubbleSort(a, 0, index);
    public static <T extends Comparable<? super T>> void
    d bubbleSort( T[] a, int first, int last )
              for(int counter = 0 ; counter < 1024 ; counter++)
    for(int counter2 = 1 ; counter2 < (1024-counter) ;
    ) ; counter2++)Don't let those counter loop to 1024. The max should be last .
                        if(a[counter2-1] > a[counter2])No. Use the compareTo(...) method:if(a[counter2-1].compareTo(a[counter2]) > 0) {
                             double temp = a[counter2];No, your array contains Comparable's of type T, use that type then:T temp = a[counter2];
    // ...Good luck.

  • Sorting problems in Grid View

    Hi, I'm having a bit of a sorting problem when it comes to an artist with name variations. The example I'm going to use is DJ Tiesto.
    There are album I have where he is credited as DJ Tiesto, and others where he is simply Tiesto.
    In the end, I'd like these albums sorted chronologically under one name (say DJ Tiesto), while still preserving and showing the proper artist name for each album. I have it set to sort by "Album by Year", which is working fine.
    The major problem I am having is that I can't get it to display properly across all iTunes viewing methods: List mode, Grid mode, and Coverflow.
    I've tried leaving the Artist field alone, and changing the Sort Artist field to "DJ Tiesto" for all songs, and that almost works:
    -List mode groups them all under "DJ Tiesto", while showing each albums Artist as the correct artist name.
    -Grid mode sorted by Album groups them all under "DJ Tiesto", while showing each albums Artist as the correct artist name.
    -Coverflow sorts them all in chronological order, while showing each albums Artist as the correct artist name.
    Problem is, Grid mode sorted by ARTIST creates two separate artists! Some for DJ Tiesto and some for Tiesto!
    To correct this I tried changing the Album Artist field for all songs to "DJ Tiesto", which solved that problem but created a bunch of new ones:
    -List mode is still correctly grouping them under "DJ Tiesto", while showing each albums Artist as the correct artist name.
    -Grid mode sorted by Album is still correctly grouping them under "DJ Tiesto", *however now it is not displaying the correct Artist name for each album!*
    -Grid mode sorted by Artist is now grouping them all under "DJ Tiesto", *however it is not displaying the correct Artist name for each album!*
    -Coverflow is sorting them in correct chronological order, *however it as well is not displaying the correct Artist name for each album!*
    Using the Album Artist tag has created more problems that it has solved! Is there anyone who knows a way to achieve what I am trying to do? I have tried seemingly every option I can and have still not found a way to do this!!
    Thanks!

    My own method of working involves renaming the files upon import to:
    i "shotdate_sequencenumber"
    Files are therefore typically named
    b 2007-11-25_001
    etc.
    This way, sorting by Filename automatically sorts by Date by default. And it wouldn't even matter if you added a descriptive text in between the date and number (
    b 2007-11-25_Scotland_001

  • Sorting problem in standard vendor search help

    Hi all,
    I'm enhancing the vendor search help.
    I found that there is a sorting problem in the original standard search help.
    The 1st time to search vendor in the search help returns a correct list, then I just sort the vendor in ascending order. This time the column name of the hit list changes and mismatch the actual values.
    Any one faced this problem before?
    What's wrong are there ?
    Thanks.

    Thanks Peluka.
    But even I don't enhance the vendor search help, I still found that the original standard version has this problem after sorting.
    Is that the program bug?
    Have anyone encountered this problem before?

  • Is this Bubble sort? How can I test it?

    Hi all,
    Would someone please confirm that this snippet of code uses the bubble sort algorithm to sort the array it receives? Also, would there be any difference in functionality, efficiency or otherwise if I rewrote the same method using recursion? I would also appreciate it if someone could suggest some test cases to test this code as I am not sure how I can go about doing that.
    Thank you very much.
    public static void sort (float array[]){
            int mIndex = 0;
            float temp;
            int i = 0, j = 0;
            for (i=array.length-1; i>0; i--){
                mIndex = i;
                for (j=0; j<i; j++){
                    if (array[j] > array[mIndex]){
                        mIndex = j;
                if (mIndex != i){
                    temp = array;
    array[i] = array[mIndex];
    array[mIndex] = temp;

    Moon123 wrote:
    Hi all,
    Would someone please confirm that this snippet of code uses the bubble sort algorithm to sort the array it receives? It doesn't. It uses [url http://en.wikipedia.org/wiki/Selection_sort]selection sort.
    Also, would there be any difference in functionality, efficiency or otherwise if I rewrote the same method using recursion? Functionality: By definition, no. That is, if you reimplement the same task using a different algorithm, by definition, it still performs the same function.
    Efficiency: No. The algorithm is still O(n^2). It will use more stack, and might be a tiny bit slower, but you won't be able to see the difference.
    I would also appreciate it if someone could suggest some test cases to test this code as I am not sure how I can go about doing that.Create an array. Stick values into it in varying orders, including: correctly sorted, reverse sorted, random. Pass the array to this method. Compare the result to what you know it should be.

  • Bubble sort wont work

    Hi, I wrote the following code that is supposed
    to sort names alphabetically. It does change
    the order of the names, but it really just
    jumbles them up, they do not come out alpha
    sorted. Can anyone see why? (the names
    are stored in objects that are in turn stored
    in a Vector)
    Object testarray[] = new Object[vector.size()];
       vector.copyInto(testarray);
       for(int j=0; j<testarray.length;j++){
          TestObject myobject = (TestObject)custarray[j];
         // the following method toLastnameString(); is a method defined in TestObject class
          String name = myobject.toLastnameString();
          String lowname = name.toLowerCase();
         for(int i = j+1; i<testarray.length;i++){
            TestObject myobject2 = (TestObject)testarray;
    String name2 = myobject2.toLastnameString();
    String lowname2 = name2.toLowerCase();
    if(lowname2.compareTo(lowname) < 0){
    Object temp = testarray[j];
    testarray[j] = testarray[i];
    testarray[i] = temp;
    } // end of if
    } // end of inner for loop
    } // end of outer for loop

    Hi,
    Is there a reason for why you want to use Bubbel Sort?
    It would be better if you try this.
    Collections.sort(vector, new Comparator() {
            public boolean equals(Object o) {
                return this == o;
            public int compare(Object o1, Object o2) {
                TestObject t1 = (TestObject)o1;
                TestObject t2 = (TestObject)o2;
                return t1.toLastNameString().toLowerCase()
                   .compareTo(t2.toLastNameString()
                   .toLowerCase());
        });This approach would be a lot safer and would out-perform bubble sort.
    Remember to import java.util.Collections and java.util.Comparator.
    /Roger
    Hi, I wrote the following code that is supposed
    to sort names alphabetically. It does change
    the order of the names, but it really just
    jumbles them up, they do not come out alpha
    sorted. Can anyone see why? (the names
    are stored in objects that are in turn stored
    in a Vector)
    Object testarray[] = new Object[vector.size()];
    vector.copyInto(testarray);
    for(int j=0; j<testarray.length;j++){
    TestObject myobject = (TestObject)custarray[j];
    // the following method toLastnameString(); is a
    is a method defined in TestObject class
    String name = myobject.toLastnameString();
    String lowname = name.toLowerCase();
    for(int i = j+1; i<testarray.length;i++){
    TestObject myobject2 =
    ject2 = (TestObject)testarray;
    String name2 = myobject2.toLastnameString();
    String lowname2 = name2.toLowerCase();
    if(lowname2.compareTo(lowname) < 0){
    Object temp = testarray[j];
    testarray[j] = testarray[i];
    testarray[i] = temp;
    } // end of if
    } // end of inner for loop
    } // end of outer for loop

  • Implementing Bubble Sort

    I'm trying to implement the Bubble sort algorithm into my program but I am having trouble I got the source code from "Harrisons" site (http://www.cs.ubc.ca/spider/harrison/Java/) and I get errors when I try to execute it, can anyone give me an example of implementing the bubble sort to sort an array of numbers?

    Here's some error info if it helps.
    "Error: The static method "void sort(int[] a);" cannot hide the instance method "void sort(int[] a);" declared in "SortAlgorithm"."
    The following lines showed errrors:
    public static void sort (int a []) //throws Exception
    if (stopRequested)
    pause (i, j);

  • JTable sorting - problem when adding elements (complete code inside)

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()                   
                public void run()
                    createAndShowGUI();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

    The table listens to the TableModel for changes. Changing the table by adding/removing
    rows or columns has no affect on its table model. If you make changes to the table model
    the table will be notified by its TableModelListener and change its view. So tell
    MyTableModel about the change of data:
    public class TableSorterDemo implements ActionListener
        MyTableModel tableModel;
        public TableSorterDemo()
            defaultListModel = new DefaultListModel();
            init1();
            tableModel = new MyTableModel(defaultListModel);
            TableSorter sorter = new TableSorter(tableModel);
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==clickMe)
                defaultListModel.removeAllElements();
                init2();
                tableModel.fireTableStructureChanged();
    }

Maybe you are looking for

  • ESB -- Routing the fault

    hi, I am new to ESB development. Please share your thoughts on the following: 1. When I register a new/modified ESB process, a dialogbox with the below message comes up, if ok is clicked then shows the Registration Summary window with service registr

  • Have MacBookPro, want to share my iTunes with my wife's account on this machine

    My wife and I have separate accounts, each with password (to keep the kids out) on the machine. Can't get her to have access to my iTunes. She has iPhone and iPad, would like to update them through this, as well as to sync. BTW, she has way more stuf

  • Error 102 when updating customer in dispute case

    Hi Experts, When I try to edit a dispute case I am getting following error: Error 102 during change to record <CustomerNumber> (Customer). Below is the screen shot. Please help. Thanks and Regards Pankaj Pareek

  • URGENT - Migration form 9.0.4 to 10.1.2

    Hello, I have a problem of this type. I'm migrating from forms 9.0.4 to forms 10.1.2. I put the FMB file on the server and compiles without problems but when i launch it on the browser the forms does not start. If instead I make a new form in 10.1.2

  • Floor Plan Manager - Info required

    Hi, Please let me know about floor plan manger in Portal. send me urls/materials. Thanks, Srinivas gumma