Results 1 to 19 of 19
  1. #1
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default Give Button sort factionality

    I'd like to give a button the functionality to sort. The info is getting taken out of a field, sorted and presented in another field. I created a GUI (swing) interface and it would be great if someone can show me how to add the sort functionality to a Batton. Please excuse, I have not much understanding of Java yet, I just started taking a Java course at my univ.

    I know it is a awful lot of code so please just focus on the two bolded where i would like to include the sort code at the end of this post.
    Java Code:
    /*
     * GUI.java
     *
     * Created on April 24, 2008, 6:43 PM
     */
    
    package learn;
    
    /**
     *
     * @author  alexander
     */
    public class GUI extends javax.swing.JFrame {
        
        /** Creates new form GUI */
        public GUI() {
            initComponents();
        }
        
        /** 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() {
    
            Label1 = new javax.swing.JLabel();
            Label2 = new javax.swing.JLabel();
            numberField = new javax.swing.JTextField();
            NumberText = new javax.swing.JLabel();
            SortButton = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            sortBox = new javax.swing.JTextPane();
            exitButton = new javax.swing.JButton();
            clearButton = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setAlwaysOnTop(true);
            setBackground(new java.awt.Color(200, 200, 100));
            setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    
            Label1.setFont(new java.awt.Font("Lucida Grande", 0, 18));
            Label1.setText("Java Programming");
    
            Label2.setText("Assignment 3");
    
            numberField.setText("Enter number here");
            numberField.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    numberFieldActionPerformed(evt);
                }
            });
    
            NumberText.setText("Enter random number:");
    
            SortButton.setText("Sort");
            SortButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    SortButtonActionPerformed(evt);
                }
            });
    
            jScrollPane1.setViewportView(sortBox);
    
            exitButton.setText("Exit");
            exitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    exitButtonActionPerformed(evt);
                }
            });
    
            clearButton.setText("Clear");
            clearButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clearButtonActionPerformed(evt);
                }
            });
    
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(146, 146, 146)
                            .add(Label2))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .add(NumberText))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(SortButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                                .add(numberField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(111, 111, 111)
                            .add(Label1))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                    .add(clearButton)
                                    .add(66, 66, 66)
                                    .add(exitButton))
                                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(20, 20, 20)
                    .add(Label1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(Label2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(46, 46, 46)
                    .add(NumberText)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(numberField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(SortButton)
                    .add(18, 18, 18)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(exitButton)
                        .add(clearButton))
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        private void numberFieldActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
    }
    
       [B] private void SortButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    
            // TODO add your handling code here:[/B]
        }                                          
    
        private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {
    System.exit (0);       
        }
    
        private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
         numberField.setText("");
         sortBox.setText("");
         // TODO add your handling code here:
    }
        
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new GUI().setVisible(true);
                }
            });
        }
        
        // Variables declaration - do not modify
        private javax.swing.JLabel Label1;
        private javax.swing.JLabel Label2;
        private javax.swing.JLabel NumberText;
        private javax.swing.JButton SortButton;
        private javax.swing.JButton clearButton;
        private javax.swing.JButton exitButton;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField numberField;
        private javax.swing.JTextPane sortBox;
        // End of variables declaration
        
    }
    and the sort code i'd like to included in the two bolded lines:
    Java Code:
    public void sort(int b[]) {
            int temp;
            for (int i = 0; i < b.length - 1; i++) {
                for (int j = i + 1; j < b.length; j++) {
                    if (b[i] > b[j]) {
                        temp = b[i];
                        b[i] = b[j];
                        b[j] = temp;
                    }
                }
    
            }
        }
    
        public void print(Graphics g, String head, int b[], int x, int y) {
            g.drawString(head, x, y);
            x += 15;
            y += 15;
            for (int i = 0; i < b.length; i++) {
                g.drawString(String.valueOf(b[i]), x, y);
                x += 20;
            }
        }

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    Hi,
    Welcome to our community. :)

    It's not much difficult pal. What you have to do is, call the function with correct arguments. Something like this,

    Java Code:
        private void SortButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    
            // TODO add your handling code here:
            sort(correct_array);
        }
    You have to define the correct_array in right place. Actually define in class level, then you can manipulated at anywhere. Got it?

  3. #3
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default TX Erange for your reply

    I included the sort function, now I am trying to get the correct arguments for the "sortButton". My idea is that the numbers (array) come from the "numberField" and than getting printed in the "sortBox"

    /*
    * GUI.java
    *
    * Created on April 24, 2008, 6:43 PM
    */

    package learn;
    import java.awt.Graphics;
    import learn.b;
    import learn.b;
    /**
    *
    * @author alexander
    */
    public class GUI extends javax.swing.JFrame {

    /** Creates new form GUI */
    public GUI() {
    initComponents();
    }
    public void sort(int b[]) {
    int temp;
    for (int i = 0; i < b.length - 1; i++) {
    for (int j = i + 1; j < b.length; j++) {
    if (b[i] > b[j]) {
    temp = b[i];
    b[i] = b[j];
    b[j] = temp;
    }
    }

    }
    }


    /** 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.
    */
    Generated Code (Hiden)

    private void numberFieldActionPerformed(java.awt.event.ActionEv ent evt) {

    // TODO add your handling code here:
    }

    private void sortButtonActionPerformed(java.awt.event.ActionEve nt evt) {
    numberField.getInputContext();
    sort (b);
    sortBox.print( b + "sorted");


    }

    private void exitButtonActionPerformed(java.awt.event.ActionEve nt evt) {
    System.exit (0);
    }

    private void clearButtonActionPerformed(java.awt.event.ActionEv ent evt) {
    numberField.setText("");
    sortBox.setText("");
    // TODO add your handling code here:
    }

    private void numberFieldActionPerformed1(java.awt.event.ActionE vent evt) {

    }

    private void sortBoxActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new GUI().setVisible(true);
    }
    });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton clearButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel firstLabel;
    private javax.swing.JTextField numberField;
    private javax.swing.JLabel numberText;
    private javax.swing.JLabel secondLabel;
    private javax.swing.JTextField sortBox;
    private javax.swing.JButton sortButton;
    // End of variables declaration

    }

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

  5. #5
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    are you just sorting arrays? look up merge sort or bogo sort. I personally like bogo sort its order (n-1)*n!. Heres a link to both. bogo sort and Merge Sort
    My IP address is 127.0.0.1

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    I think sorted using a simple way. Just comparing values. Not bad actually. But have to check about the performance on an array which have large number of elements.

  7. #7
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default

    Thanks so far. Zosden, this is some homework for school and they want me to use the same sort I have been using at prior homeworks. I know it is working but I don't get it to work with this interface I constructed. Eranga, that's why performance is not so important. Anyway, can u guys give me tips how I am getting this to work? I'd like to get this sort performed when ...:
    Java Code:
     public void sort(int b[]) {
            int temp;
            for (int i = 0; i < b.length - 1; i++) {
                for (int j = i + 1; j < b.length; j++) {
                    if (b[i] > b[j]) {
                        temp = b[i];
                        b[i] = b[j];
                        b[j] = temp;
                    }
                }
    
            }
        }
    ... this button is getting clicked ...
    Java Code:
      private void sortButtonActionPerformed(java.awt.event.ActionEvent evt) {
    ... and the sorted array is than getting displayed in:
    Java Code:
     private void sortBoxActionPerformed(java.awt.event.ActionEvent evt) {
    The sort should be taking the array from this field:
    Java Code:
     private void numberFieldActionPerformed(java.awt.event.ActionEvent evt) {

  8. #8
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    OMG that looks like bubble sort I love you newbie. LOL please tell me your teacher is either an idiot or just trying to prove something. I think you should use bogo sort its my favorite. just read it and be amazed at its awesome power. just say call this.sort(myArray). By the way I love bubble sort its my second favorite sorting algorithm next bogo sort. it grows a n^2, which by the way is terrible compared to nlgn, which is merge sort and quick sort.
    My IP address is 127.0.0.1

  9. #9
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default

    I love you too if you going to help me understand this. I can be amazed by any sort but the result will be the same. I need an interface that accepts numbers and sorts them. I even don't care so much how I am going to do that but I started out with bubble sort, yes my professor loves it, and I was amazed by swing. (Using NetBeans).

  10. #10
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    Just a tip never use a program to create your GUI for you. It is much better if you make it yourself because that way you can have more control over resizing of everything. I would just have a while loop that kept asking the user for input numbers, and then just add each of the answers to the vector.

    Java Code:
    /**
     * @(#)BubbleSort.java
     *
     *
     * @author 
     * @version 1.00 2008/4/29
     */
    import java.util.Vector;
    
    import javax.swing.JOptionPane;
    
    public class BubbleSort 
    {
        Vector<Integer> myVector;
    
        public BubbleSort() 
        {
            myVector = new Vector<Integer>();
            String tempStr = JOptionPane.showInputDialog("Please Enter a number.");;
            while(!tempStr.equals(""))
            {
                int tempInt = Integer.parseInt(tempStr);
                myVector.add(new Integer(tempInt));
                tempStr = JOptionPane.showInputDialog("Please Enter a number.");
            }
            this.sort();
        }
        
        private void sort()
        {
            // put your sort in here
            
            this.display();
        }
        
        private void display()
        {
            // how ever you want to display it.
            for(int i = 0; i < myVector.size(); i++)
            {
                System.out.println(myVector.get(i));
            }
        }
        public static void main(String[] args)
        {
            BubbleSort myBubbleSort = new BubbleSort();
        }            
    }
    My IP address is 127.0.0.1

  11. #11
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    For your case just use your GUI, and have the user input a string that represents a number then have them push a button that adds that text to your vector then after they finish have the user push a different button that will call your sorting algorithm
    My IP address is 127.0.0.1

  12. #12
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default

    Great, Let's see if I understand this, I am working on it soon. TX

  13. #13
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    Try to implement other sorting algorithms and compare speed you will be surprised also use bogo sort if your teacher is at all competent he or she will laugh and give you a better grade.
    My IP address is 127.0.0.1

  14. #14
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default

    Zosden, I have seen other posts of you, I know you love Bogo sort. Well I have to admit, I can see some "beauty" in it, to stop the loop with a break Finally I had some time to go over this. The vector is a great idea, I am not sure though if my prof wants that all in one window. I tried to make this work what you showed me, still having trouble ... ahhh

    Java Code:
    package test;
    
    /**
     * @(#)BubbleSort.java
     *
     *
     * @author 
     * @version 1.00 2008/4/29
     */
    import java.util.Vector;
    
    import javax.swing.JOptionPane;
    
        
    public class IntArrayTableModel 
    {
        Vector<Integer> myVector;
    
        public BubbleSort() 
        {
            myVector = new Vector<Integer>();
            String tempStr = JOptionPane.showInputDialog("Please Enter a number.");;
            while(!tempStr.equals(""))
            {
                int tempInt = Integer.parseInt(tempStr);
                myVector.add(new Integer(tempInt));
                tempStr = JOptionPane.showInputDialog("Please Enter a number.");
            }
            this.sort();
        }
    
        private void sort() {
            throw new UnsupportedOperationException("Not yet implemented");
        }
        
       private void sort(int b[]) {
            int temp;
            for (int i = 0; i < b.length - 1; i++) {
                for (int j = i + 1; j < b.length; j++) {
                    if (b[i] > b[j]) {
                        temp = b[i];
                        b[i] = b[j];
                        b[j] = temp;
                    }
                }
    
            }
        }
            
            this.display();
        }
        private void display()
        {
            // how ever you want to display it.
            for(int i = 0; i < myVector.size(); i++)
            {
                System.out.println(myVector.get(i));
            }
        }
        public static void main(String[] args)
        {
            BubbleSort myBubbleSort = new BubbleSort();
        }            
    }

  15. #15
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    your constructor should be called the same thing as the class just to let you know.
    My IP address is 127.0.0.1

  16. #16
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default

    true, I changed the class to BuubleSort. Why does it say "Class "test.BubbleSort" does not have main method" when I try to run the file?

  17. #17
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    what are you trying to run it in ex. command prompt, eclipse, net beans
    My IP address is 127.0.0.1

  18. #18
    Java_Student is offline Member
    Join Date
    Apr 2008
    Posts
    8
    Rep Power
    0

    Default

    NetBeans gives me that message.

    Can Swing GUI be implemented in a website?

  19. #19
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    if you make it into an applet I think so, but don't quote me on it.
    My IP address is 127.0.0.1

Similar Threads

  1. How to sort a list using Bubble sort algorithm
    By Java Tip in forum Algorithms
    Replies: 3
    Last Post: 04-29-2008, 08:04 PM
  2. anyone can give idea 2 my assignment?
    By chen8735 in forum Advanced Java
    Replies: 2
    Last Post: 03-08-2008, 06:03 PM
  3. Replies: 0
    Last Post: 01-19-2008, 09:04 AM
  4. give me a advise
    By sireesha in forum New To Java
    Replies: 3
    Last Post: 12-11-2007, 01:38 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •