Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Using a Slider value with another class

  1. #1
    Member
    Join Date
    May 2013
    Posts
    42
    Thanks
    0
    Thanked 5 Times in 1 Post

    Default Using a Slider value with another class

    Hey, I have a Java assignment which I'm stuck on, I'm not looking for anyone to do the assignment for me, I would just like a little help and guidance in the right direction, here are my classes, and what my problem is:

    MyShape Class

    package calculations;
     
    public class MyShape 
    {
           public double getArea(double length)       
           {
               return 0;
           }//end of getArea
     
           public double getBoundaryLength(double length)
           {
               return 0;
           }//end of getBoundaryLength

    Circle Class - There is also a Triangle class and a Square class, same format just different calculations.
    package calculations;
     
    public class Circle extends MyShape
    {   
        public double getArea(double length)
        {
            return length * length * Math.PI;
        }//end of getArea
     
        public double getBoundaryLength(double length)
        {
            return 2 * length * Math.PI;
        }//end of getBoundaryLength
    }//end of class


    Main class - I used this for the last part of my assignment, this provides the user with a simple menu to enter a length and calculate a shape of their choice. I'm not sure if it is still needed
    package calculations;
     
    import java.util.Scanner;
     
    public class Main 
    {
        private static double boundaryLength;
        private static double area;
        private static double length;
     
        static MyShape myShape;
     
        public static Scanner scan = new Scanner(System.in);
     
        public static int Menu()//creates a menu for the user
        {
            System.out.println("\nSelect a Shape or Exit: \n");
            System.out.println("1. Square");
            System.out.println("2. Circle");
            System.out.println("3. Triangle");
            System.out.println("4. Exit");
            int option;
     
            System.out.println("Enter choice: ");
            option = scan.nextInt();
     
            return option;
        }// end menu
     
        public static void main(String[] args) //switch
        {       
            int option = 0;
            boolean test = true;
     
            while (option != 4)
            {
                option = Menu();
     
                switch(option)
                {
                    case 1:
                        myShape = new Square();
                        test = true;
                        break;
                    case 2:
                        myShape = new Circle();
                        test = true;
                        break;
                    case 3:
                        myShape = new Triangle();
                        test = true;
                        break;
                    case 4:
                        System.out.println("\n---System Shutdown---\n");
                        test = false;
                        break;
                    default:
                        System.out.println("\nInvalid option!");
                        test = false;
                        break;
                }//end of switch
     
                   if(test == true)
                   {
                        do
                        {
                            System.out.println("Enter the length: ");
                            while (!scan.hasNextDouble())
                            {
                                System.out.println("That is not a valid number!\n");
                                System.out.println("Enter the length: ");
                                scan.next();
                            }//end of while loop
                            length = scan.nextDouble();
                            if(length <= 0)
                            {
                                System.out.println("You must enter a positive number!\n");
                            }//end of if statement
                        }
                        while (length <= 0);
     
                        boundaryLength = myShape.getBoundaryLength(length);
                        area = myShape.getArea(length);
     
                        System.out.println("\nBoundary Length = " +Math.round(boundaryLength));
                        System.out.println("Area = " +Math.round(area));
                    }//end of if statement
            }//end of while loop
        }//end of public
    }//end of class

    MyControlPanel class
    package calculations;
     
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
     
    public class MyControlPanel extends javax.swing.JPanel 
    {
        static int min = 0;
        static int max = 100;
        static int initial = 0;
     
        JSlider jSlider;
        JLabel jLabel1;
        JLabel jLabel2;
        JLabel jLabel3;
        JTextField jText1;
        JTextField jText2;
     
        public MyControlPanel() 
        {
            initComponents();
     
            jSlider = new JSlider(JSlider.HORIZONTAL, min, max, initial);
            jSlider.setMajorTickSpacing(10);
            jSlider.setMinorTickSpacing(1);
            jSlider.setPaintLabels(true);
            jSlider.setPaintTicks(true);
            jSlider.setValue(70);
     
            jSlider.addChangeListener(new MyChangeAction());
            jText1 = new JTextField("Displaying JSlider value");
     
            jText1 = new JTextField();
            jText2 = new JTextField();
     
            jText1.setText("        ");
            jText2.setText("        ");
     
            jLabel1 = new JLabel();
            jLabel2 = new JLabel();
            jLabel3 = new JLabel();
     
            jLabel1.setText("Shape Dimension");
            jLabel2.setText("Boundary Length = ");
            jLabel3.setText("Area = ");
     
            this.add(jSlider) ;
            this.add(jLabel1) ;
            this.add(jLabel2) ;
            this.add(jText1) ;
            this.add(jLabel3) ;
            this.add(jText2) ;
     
            setLayout(new FlowLayout());
        }
            public class MyChangeAction implements ChangeListener
            {
                @Override
            public void stateChanged(ChangeEvent ce) 
            {
                int value = jSlider.getValue();
                String str = Integer.toString(value);
                jLabel1.setText(str);
            }
     
            }
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            );
        }// </editor-fold>                        
        // Variables declaration - do not modify                     
        // End of variables declaration                   
    }

    MyFrame class
    package calculations;
     
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
     
    public class MyFrame extends javax.swing.JFrame implements ActionListener
    {
        MyShape myShape = new MyShape();
     
        public MyFrame() 
        {
            initComponents();
     
            JMenuBar jMenuBar = new JMenuBar();
     
            JMenu Shape = new JMenu();
     
            Shape.setText("Shape");
     
            JMenuItem Square = new JMenuItem();
            Square.addActionListener(new MySquareAction());
     
            JMenuItem Triangle = new JMenuItem();
            Triangle.addActionListener(new MyTriangleAction());
     
            JMenuItem Circle = new JMenuItem();
            Circle.addActionListener(new MyCircleAction());
     
            Square.setText("Square");
            Triangle.setText("Triangle");
            Circle.setText("Circle");
     
            jMenuBar.add(Shape);
     
            Shape.add(Square);
            Shape.add(Triangle);
            Shape.add(Circle);
     
            setJMenuBar(jMenuBar);
     
            MyControlPanel controlPanel = new MyControlPanel();
     
            setLayout(new FlowLayout());
     
            this.add(controlPanel);
        }
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            );
     
            pack();
        }// </editor-fold>                        
        public static void main(String args[]) 
        {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url] 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() 
            {
                @Override
                public void run() 
                {
                    new MyFrame().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        // End of variables declaration                   
     
        @Override
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
     
    public class MySquareAction implements ActionListener
        {
        @Override
            public void actionPerformed(ActionEvent e)
            {
                myShape = new Square();
            }  
        }
     
    public class MyTriangleAction implements ActionListener
        {
        @Override
            public void actionPerformed(ActionEvent e)
            {
                myShape = new Triangle();
            }
        }
     
    public class MyCircleAction implements ActionListener
        {
        @Override
            public void actionPerformed(ActionEvent e)
            {
                myShape = new Circle();
            } 
        }
     
    }

    program.jpg
    This is what my program looks like so far.
    When the slider is moved the label, Shape Dimension, changes to the value at which the slider is moved to.
    The JMenu Shape, has three jMenuItems Circle, Square and Triangle. Lets say the circle was selected, the slider value would be used to calculate the boundary length and area of the circle, same for each of the other shapes.

    Okay, I'm sorry for all the code! But my problem is, how can I use the value which is given from the slider to calculate the shapes boundary length and area. So that both the boundary length and area are shown in the text boxes, jText1 and jText2.

    Any help would be appreciated, Thanks!


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Using a Slider value with another class

    Sounds like you need to add a listener that detects changes to your gui components (the slider). When those listeners trigger, you need to take the appropriate action (calling a setter on the other components or your custom painting, whatever the case may be). Which part of this is giving you trouble?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member
    Join Date
    May 2013
    Posts
    42
    Thanks
    0
    Thanked 5 Times in 1 Post

    Default Re: Using a Slider value with another class

    So this is the action listener i have on my Circle menu item, I'm not sure where to go from here,
    how would I send the value from the slider, to the Circle class, and then return the boundary length and area to go into the desired text boxes

            JMenuItem Circle = new JMenuItem();
            Circle.addActionListener(new MyCircleAction());

    public class MyCircleAction implements ActionListener
        {
        @Override
            public void actionPerformed(ActionEvent e)
            {
                myShape = new Circle();
            } 
        }

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Using a Slider value with another class

    You need a reference to the instance you want to manipulate. You can pass the reference through the constructor or through a setter. Some more info here: Action Listeners - Tutorials - Static Void Games
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Member
    Join Date
    May 2013
    Posts
    42
    Thanks
    0
    Thanked 5 Times in 1 Post

    Default Re: Using a Slider value with another class

    I'm really clueless here, I can't seem to get my head around this.

    So, I have my ChangeListener on my slider, which finds the value that the slider is currently at, and shows it in jLabel1:

    public class MyChangeAction implements ChangeListener
            {
                @Override
                public void stateChanged(ChangeEvent ce) 
                {
                   double sliderValue = jSlider.getValue();
                   String str = Double.toString(sliderValue);
                   jLabel1.setText(str);
                }
     
            }

    and I have my ActionListener's on my menuItem's:

    public class MyCircleAction implements ActionListener
        {
        @Override
            public void actionPerformed(ActionEvent e)
            {
                myShape = new Circle();
            } 
        }

    though how do I send the value of the slider to the specific class, e.g. Square.java, so that it carry's out the calculation and shows it in the jTextBox's

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Using a Slider value with another class

    That's what getter (or accessor) methods are for to pull the value or setter (mutator) methods to push the value. Getters and setters provide a communication path or an interface between classes. Are you familiar with those?

  7. #7
    Member
    Join Date
    May 2013
    Posts
    42
    Thanks
    0
    Thanked 5 Times in 1 Post

    Default Re: Using a Slider value with another class

    package calculations;
     
    public class Circle extends MyShape
    {   
        public double getArea(double length)
        {
            return length * length * Math.PI;
        }//end of getArea
     
        public double getBoundaryLength(double length)
        {
            return 2 * length * Math.PI;
        }//end of getBoundaryLength
    }//end of class

    I have these getters in my Circle class, and these in my myShape class:

    package calculations;
     
    public class MyShape 
    {
           public double getArea(double length)       
           {
               return 0;
           }//end of getArea
     
           public double getBoundaryLength(double length)
           {
               return 0;
           }//end of getBoundaryLength

    from what i remember, i used myShape.getArea(length) or myShape.getBoundaryLength, which would pass in length variable, and return the area and boundary length of the shape, although i cant get my head around how i would implement this into this program so that the boundary length and area are shown in the text boxes.

    --- Update ---

            public class MyChangeAction implements ChangeListener
            {
                @Override
                public void stateChanged(ChangeEvent ce) 
                {
     
                   [B]myShape = new Circle();[/B]
                   double sliderValue = jSlider.getValue();
     
                   double area;
                   double boundaryLength;
     
                   String str = Double.toString(sliderValue);
                   jLabel1.setText(str);
     
                   area = myShape.getArea(sliderValue);
                   boundaryLength = myShape.getBoundaryLength(sliderValue);
     
                   jText1.setText(Double.toString(Math.round(boundaryLength)));
                   jText2.setText(Double.toString(Math.round(area)));
                }
     
            }

    This code below works because i have forced myShape to equal circle, although i cant seem to figure out how to set myShape to which menuItem has been selected, each menuItem has a action listener which sets myShape to the equivalent shape, as seen here:

    public class MyCircleAction implements ActionListener
        {
        @Override
            public void actionPerformed(ActionEvent e)
            {
                myShape = new Circle();
            } 
        }

    Could I get some help with this, how would i send the currently selected menuItem from the MyFrame class to the MyControlPanel class ?

    thanks.

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Using a Slider value with another class

    I should have studied your code before asking rhetorical questions. Your Circle class (and probably others) demonstrates that your understanding of classes, objects, and mutators/accessor methods is still developing. That's okay. My understanding develops everyday.

    Here's your Circle class:
    public class Circle extends MyShape
    {   
        public double getArea(double length)
        {
            return length * length * Math.PI;
        }//end of getArea
     
        public double getBoundaryLength(double length)
        {
            return 2 * length * Math.PI;
        }//end of getBoundaryLength
    }//end of class
    Here's what's wrong with it:
    1. It has no fields (or instance variables)
    2. It has no constructor
    3. Accessor methods (getters) don't typically take parameters
    4. It has no mutator methods (setters)

    This is your class improved, but there's still work to do:
    public class Circle extends MyShape
    {
        // instance variables
        double length;
        double area;
        double boundaryLength;
     
        // Circle() constructor that accepts the parameter length
        public Circle( double length )
        {
            this.length = length;
            area = length * length * Math.PI;
            boundaryLength = 2 * length * Math.PI;
        }
     
        // length getter/setter - provided as examples
        public double getLength()
        {
            return length;
        }
     
        public void setLength( double length )
        {
            this.length = length;
        }
     
        // may not want these or if included, recalculate length
        // with area/boundaryLength changes
        // area getter/setter
        // (write your own)
     
        // boundaryLength getter/setter
        // (write your own)
     
    }//end of class
    Review your classes and fix them.

    I don't understand how the bits of code you've posted work together or are connected, but here's the concept in general terms:

    1. Shapes draw themselves. Pass the shape object a Graphics object and the parameters necessary to define itself, and the Shape draws itself on the Graphics object.

    2. The slider varies a value

    3. The slider change listener determines which shape is selected, reads the slider's value, passes the value with the graphics object to the chosen shape instance which then draws itself, and then sets the slider value in the appropriate text area.

    I know this is a bit mysterious at first, and it's a pretty complex project for your first combined OOP/graphics/GUI attempt, but you'll figure it out. Come back when you've made some of the above changes and are stuck, needing more help. Try to post working code - even one shape and a slider that registers its value in a text area - and ask any questions you have about moving on from there.

    --- Update ---

    Cross posted here.

  9. #9
    Member
    Join Date
    May 2013
    Posts
    42
    Thanks
    0
    Thanked 5 Times in 1 Post

    Default Re: Using a Slider value with another class

    I will try doing my three shape classes like this, although I already had that part of my program looked at by my lecturer, and he said it was correct.

    I think its the way I'm explaining my problem that it isn't making any sense to you.

    The MyShape class and the Circle, Triangle and Square classes all work fine when I used my simple menu system, surely they should work just fine with this GUI?

    I just need to figure out how to tell the MyControlPanel class, which menuItem(shape) has been chosen by the user, the menuItem ActionListeners are in the MyFrame class.

    And then, pass the sliders value into the corresponding shapes class, which will do you calculation and return the boundaryLength and area.

    Which will in turn, set the text of jText1 to the boundaryLength and jText2 to the area.


    This ChangeListener for the slider sends the sliders value to the Circle class(since i have used myShape = new Circle();) by using area = myShape.getArea(sliderValue); and boundaryLength = myShape.getBoundaryLength(sliderValue); and then returns it and sets the boundaryLength and area to the correct jTextboxes.

    public class MyChangeAction implements ChangeListener
            {
                @Override
                public void stateChanged(ChangeEvent ce) 
                {
                   myShape = new Circle();
                   double sliderValue = jSlider.getValue();
     
                   double area;
                   double boundaryLength;
     
                   String str = Double.toString(sliderValue);
                   jLabel1.setText(str);
     
                   area = myShape.getArea(sliderValue);
                   boundaryLength = myShape.getBoundaryLength(sliderValue);
     
                   jText1.setText(Double.toString(Math.round(boundaryLength)));
                   jText2.setText(Double.toString(Math.round(area)));
                }            
            }

    Here you can see it is working for the Circle:
    werg.jpg

    but how can i do this without having to set a single shape like this: myShape = new Circle(); ?

    edit: also, i thought cross posting was allowed on this forum, maybe I am thinking of another forum, sorry.

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Using a Slider value with another class

    I already had that part of my program looked at by my lecturer, and he said it was correct.
    Then I learned a different Java so don't know how to help. Don't despair. Someone who learned the Java your instructor is teaching should come by.

    Cross posting is allowed, but it's asked to be declared.

  11. #11
    Member
    Join Date
    May 2013
    Posts
    42
    Thanks
    0
    Thanked 5 Times in 1 Post

    Default Re: Using a Slider value with another class

    Is this not a simple problem though ? it seems simple, well not for me, is there not a way to send the currently selected menuItem, from one class to the other? meaning the program would know which shape to use for the calculation, for example,

    in the slider changeListener, add an if statement, or something along them lines

    public class MyChangeAction implements ChangeListener
            {
                @Override
                public void stateChanged(ChangeEvent ce) 
     
                   if (MyFrame.menuItem == Circle)
                   {
                   myShape = new Circle();
     
                   double sliderValue = jSlider.getValue();
     
                   double area;
                   double boundaryLength;
     
                   String str = Double.toString(sliderValue);
                   jLabel1.setText(str);
     
                   area = myShape.getArea(sliderValue);
                   boundaryLength = myShape.getBoundaryLength(sliderValue);
     
                   jText1.setText(Double.toString(Math.round(boundaryLength)));
                   jText2.setText(Double.toString(Math.round(area)));
                   }
            }

Similar Threads

  1. need to make basic class and implementation class (base class without void main)
    By javanewbie101 in forum Object Oriented Programming
    Replies: 1
    Last Post: September 19th, 2012, 08:03 PM
  2. Replies: 3
    Last Post: June 17th, 2012, 06:22 PM
  3. Java slider blocking my homepage
    By TheUpcoming in forum Other Programming Languages
    Replies: 1
    Last Post: June 5th, 2012, 07:48 AM
  4. updating SWT Slider from separate java class
    By ppmckee in forum AWT / Java Swing
    Replies: 0
    Last Post: April 14th, 2011, 03:23 PM
  5. set the slider's models (range)
    By chronoz13 in forum AWT / Java Swing
    Replies: 1
    Last Post: November 28th, 2009, 11:59 PM