JSlider using double values instead of INT

I need to create a slider that uses double values instead of ints...
the default constructor is JSlider temp = new JSlider(JSlider.HORIZONTAL, int, int, int)....but i need to use
JSlider temp = new JSlider(JSlider.HORIZONTAL, double,double,double)
I want my slider to go from like 1.0 to 10.0 ....any ideas?
thanks

me has ritten a sample code fur ya... mite help...
sorrie... not commented properly...
import java.awt.event.*;
import java.util.Vector;
import javax.swing.event.*;
import java.awt.*;
import javax.swing.*;
public class Test extends JPanel {
     //Variable Declarations...
     JPanel valuesPanel;
     public JSlider slider;
     public JTextField midText;
     public JTextField lowText;
     public JTextField highText;
     int precision=1000;//to convert to double...(100-> 2decimal places, 1000->3decimal places.......)
     double lowLimit = 0;
     double midLimit = 5;
     double highLimit = 10;
     public Test() {
          initialize();
          addListeners();
          initComponents();
          addComponents();
     public void initialize() {
          valuesPanel = new JPanel();
          highText = new JTextField();
          midText = new JTextField();
          lowText = new JTextField();
          slider = new JSlider();
     public void addListeners() {
          addTextListenerTo( highText );
          addTextListenerTo( midText );
          addTextListenerTo( lowText );
          // if the slider is moved, the value of the mid will be updated in the testbox.
          // Sliders work on integers and not on double. so the limits are divided by precision to get a double number.
          slider.addChangeListener(
               new ChangeListener() {
                    public void stateChanged( ChangeEvent e ) {
                         double n = ( double ) ( ( JSlider ) e.getSource() ).getValue();
                         midLimit = n / precision;
                         midText.setText( Double.toString( midLimit ) );
     * Sets different attributes and properties of the components
     public void initComponents() {
          highText.setText( Double.toString( highLimit ) );
          midText.setText( Double.toString( midLimit ) );
          lowText.setText( Double.toString( lowLimit ) );
          slider.setPaintTrack( true );
          slider.setPaintTicks( true );
          slider.setMinimum( ( int ) ( lowLimit * precision ) );
          slider.setValue( ( int ) ( lowLimit * precision ) );
          slider.setMaximum( ( int ) ( highLimit * precision ) );
     * Add all the components to the container (Panel).
     public void addComponents() {
          setLayout( new BorderLayout() );
          valuesPanel.setLayout( new GridLayout( 3, 3, 5, 5 ) );
          valuesPanel.add( new JLabel("Low") );          
          valuesPanel.add( highText );
          valuesPanel.add( new JLabel("Mid") );
          valuesPanel.add( midText );
          valuesPanel.add( new JLabel("High") );
          valuesPanel.add( lowText );
          add( valuesPanel, BorderLayout.CENTER);
          add( slider, BorderLayout.SOUTH);
     * Adds Focus and Action Listeners to the TextFields
     public void addTextListenerTo( JTextField textField ) {
          textField.addFocusListener(
               new FocusAdapter() {
                    public void focusLost( FocusEvent evt ) {
                         updateLimits( ( JTextField ) evt.getSource() );
                    public void focusGained( FocusEvent evt ) {
                         String tempOldString = ( ( JTextField ) evt.getSource() ).getText();
          textField.addActionListener(
               new ActionListener() {
                    public void actionPerformed( ActionEvent evt ) {
                         updateLimits( ( JTextField ) evt.getSource() );
     * This function is called when any action is performed on the text. It checks
     * if the value is valid and if not it displays a message. Also it updates the
     * slider value.
     *@param textField
     public void updateLimits( JTextField textField ) {
          double tempN = 0;
          try {
               tempN = Double.parseDouble( textField.getText() );
               if ( textField.equals( lowText ) ) {
                    lowLimit = tempN;
                    slider.setMinimum( ( int ) ( lowLimit * precision ) );
               else if ( textField.equals( highText ) ) {
                    highLimit = tempN;
                    slider.setMaximum( ( int ) ( highLimit * precision ) );
               else if ( textField.equals( midText ) ) {
                    midLimit = tempN;
                    slider.setValue( ( int ) ( midLimit * precision ) );
          } catch ( Exception ex ) {
               JOptionPane.showMessageDialog( this, "Not a Number", "Error !!!", JOptionPane.WARNING_MESSAGE );
               textField.setText( "0" );
     public static void main(String args[]) {
     JFrame f=new JFrame("test Frame");
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     f.getContentPane().add(new Test());
     f.pack();
     f.setVisible(true);

Similar Messages

  • JSlider with double values?

    Hi All.
    Is is possible to create JSliders that use double instead of int?
    I need the values to be from 0 to 1, incremented by 0.1.
    I have searched but haven't found a solution.
    Anyone know of anything?
    Cheers.

    JSlider doesn't use int. It uses a Hashtable which is filled with JComponent's vs int. You can put whatever you want (say icons) there. By default the tabel holds JLabel's of int.
    here is smal piece of code to get what you want (I setup a simple frame in NetBeans and added few lines)
    import java.awt.Font;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    public class SliderFrame extends javax.swing.JFrame {
        /** Creates new form SliderFrame */
        public SliderFrame() {
            initComponents();
            //prepare labels, the only hand edited piece
            Format f = new DecimalFormat("0.0");
            Hashtable<Integer, JComponent> labels = new Hashtable<Integer, JComponent>();
            for(int i=0;i<=10;i++){
                JLabel label = new JLabel(f.format(i*0.1));
                label.setFont(label.getFont().deriveFont(Font.PLAIN));
                labels.put(i,label);
            slider.setLabelTable(labels);
            //end of my own code, the rest is done by NetBeans
        /** 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() {
            slider = new javax.swing.JSlider();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            slider.setMajorTickSpacing(1);
            slider.setMaximum(10);
            slider.setPaintLabels(true);
            slider.setPaintTicks(true);
            slider.setPreferredSize(new java.awt.Dimension(400, 46));
            getContentPane().add(slider, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new SliderFrame().setVisible(true);
        // Variables declaration - do not modify
        protected javax.swing.JSlider slider;
        // End of variables declaration
    }

  • Creating polygons with an array of doubles instead of ints

    Hi,
    I want to create a polygon using:
    Polygon u = new Polygon(xPoints, yPoints, numTs);
    my problem is that my x & y points are stored in double arrays not ints. Is there a way to create a polygon using double arrays instead of ints?
    cheers,
    elmicko

    or cast them as int. imaginr posX, posY, width and height are doubles.
    Rectangle rect = new Rectangle( (int)posX, (int)posY, (int)width,(int)height );or, with an array of doubles:
    Rectangle rect = new Rectangle( (int)array[0], (int)array[1], (int)array[2],(int)array[3] );

  • Using Characteristic value with Replacement path variable

    Hi All,
    Could you please let me know if it is possible to use charecteristic value instead of key figure with replacement path variable. My requirement is to use factory calendar id as the replacement variable on plant characteristic, now when I choose replcaement variable with Attribute value, the dropdown menu only gives the list of key figures assigned as an attributes to Plant.
    Now I am looking for a solution to use factory calendar id as the attribute.
    Thanks for your help in advance.
    Regards
    SS

    Hi sachin
    U can use it
    Look at these links
    Re: Customer exit &  Replacement path........?
    Variable with Replacement Path
    Re: Replacement Path for Charastrictics Variable
    http://help.sap.com/saphelp_nw04/helpdata/en/03/6ba03cc24efd1de10000000a114084/frameset.htm
    Regards
    KR

  • Read from a .db file and use the values within a program

    each account has 3 values.. (password, balance,id_number)
    my .db file contains the following.
    pass201 250 9885 pass202 300 5547 pass203 700 1123
    (this is 3 accounts)
    I need to be able to read from this file and use each attribute within my program... HELP!

    String[][] accounts = null;
    try
         // Open a file input stream
         FileInputStream fileContents = new FileInputStream("filename");
         byte[] data = new byte[fileContents.available()];
         fileContents.read(data);
         fileContents.close();
         String contents = new String(data);
         StringTokenizer values = new StringTokenizer(data); // using space character as delimiter
         // Using 3 values per line
         int lines = (int)(values.countTokens()/3);
         int columns = 3;
         accounts = new String[lines][columns];
         for(int i=0; i<lines; i++)
              for(int j=0; j<columns; j++)
                   accounts[i][j] = values.nextToken();
    catch(Exception error)
         // debug stuff
    }

  • DrawLine using double instead of int

    I'm trying to use the java.awt to draw a line but I would like to use doubles instead of ints.
    the normal way would be to use drawline(int x, int y , int x2 , int y2);
    but i cant find a way to drawline( double x, double y, double x2, double y2)
    any idea's?
    Some more detail about this is I�m trying to create a package to draw a graph and my points are in double (and I would like them to stay that way) is there a way?
    Many Thanks, John

    if you want to keep it in doubles you could use Line2D.Double from the java.awt.geom package. Then instead of a call to drawLine(int, int, int, int) call draw(line2D) passing in the line2D. As it implements the shape interface it will know what to do. Note to do this call you'll have to cast the Graphics object to a Graphics2D.
    Hope this helps
    Mike

  • Unable to display double values in Excel sheet using JExcel API

    Hi
    I am writing code to generate report in the form of Excel Sheet using JExcel API.
    Everything is going fine but whenever I want to put some double values in a cell it is only showing 2 decimal places. My problem is "I want to show upto five decimal places".
    Any kind of reply might help me lot.
    Thank U.

    If you enable the submit zero option, it still happens? This is a new feature on the display tabl
    #NumericZero Enhancements
    To display a numeric zero in place of an error message, you can enter #NumericZero in any of the three Replacement text fields. When you use the #NumericZero option:
    · Excel formatting for the cell is retained.
    · All calculations with dependency on the cell will compute correctly and will take the value of this cell as zero.
    · This numeric zero is for display only. When you submit, the zero value is NOT submitted back to the data source.
    You cannot set display strings for cells that contain an invalid member or dimension name (metadata error). Metadata errors produce standard descriptive error messages.
    Errors are prioritized in the following order from highest to lowest. The error message for a higher-priority error takes precedence over that for a lower-priority error.
    1. (Highest) Metadata errors
    2. #No access
    3. #Invalid/Meaningless
    4. #No data\Missing

  • Why can't I open my emails by double clicking on it, I now have to use cntrl/O instead.

    Up until a few days ago I could open emails by double clicking on it. Now I have to use control/O instead. I have not changed any settings that I am aware of. What happened and how can I change it back?

    ''cjaquith [[#question-1040162|said]]''
    <blockquote>
    Up until a few days ago I could open emails by double clicking on it. Now I have to use control/O instead. I have not changed any settings that I am aware of. What happened and how can I change it back?
    </blockquote>
    ''Airmail [[#answer-674273|said]]''
    <blockquote>
    Try a different mouse. There is no setting in Thunderbird.
    </blockquote>
    I am using a laptop, which didn't have a mouse, just a mouse pad, so I added a corded mouse via a USB port, and it does the same thing.

  • How to use a value int the DAT file as name of the PDF file

    I need to use a value present in my DAT file as name of the PDF File.
    I am using the ,u argument in the Print Agent and I know this causes the pdf document to get a generic filename.
    Please help me.
    Thanks

    See my response to this same question you posed in the Output Designer forum.
    http://www.adobeforums.com/webx/.59b585c2/0

  • Using double/floats for co ordinates?

    hi is it possible to use float/double values for the following code or simlar?
    g.drawImage(cards, 0.5, 0.8, this);
    does the drawimage on support ints?

    Update and demo: Am I the only one who is forever tweaking rendering hints
    to get the right effect? Anyhowdy, I think INTERPOLATION was the hint I needed
    to tweak to get subpixel shifting of images:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class ShiftyExample extends JPanel {
        private BufferedImage image;
        private float delta;
        public ShiftyExample(BufferedImage image, float delta) {
            this.image = image;
            this.delta = delta;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawRenderedImage(image, null);
            g2.drawRenderedImage(image, AffineTransform.getTranslateInstance(delta, 0));
            g2.dispose();
        public static void main(String[] args) {
            EventQueue.invokeLater(new GuiBuilder());
        static class GuiBuilder implements Runnable {
            public void run() {
                BufferedImage image = createImage();
                JPanel cp = new JPanel(new GridLayout(1,0));
                cp.add(new ShiftyExample(image, 0f));
                cp.add(new ShiftyExample(image, 0.5f));
                cp.add(new ShiftyExample(image, 1f));
                cp.add(new ShiftyExample(image, 1.5f));
                cp.add(new ShiftyExample(image, 2f));
                JFrame f = new JFrame("ShiftyExample");
                f.setContentPane(cp);
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setSize(300,200);
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            BufferedImage createImage() {
                BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.BLACK);
                g.drawLine(10,0,10,100);
                g.dispose();
                return image;
    }Explanation: the image is a vertical black line on a clear background.
    What you see on the frame are five versions of the image displayed
    against a shifted copy of itself, shift 0, 0.5, 1, 1.5 and 2 units. If you really stare at the
    fractional examples, you will see gray pixels being used instead of just black
    and white. Woop-de-doo...

  • Is it possible to use the value of a string to reference a component in the

    I'm fairly new to Java so this may be a stupid question!
    Is it possible to use the value of a string to reference a component in the code? For example in the code below, Wall is a class holding 3 different arrays. The Robot class has an array called finishBricks. When the buildWall method is run it receives the integers width and height which are used to construct the dimensions string. I want to use this string to then load the appropriate Wall array into the finishBricks array.
    I hope this makes sense! Any help would be greatly appreciated!
    class Robot {
    public double[][] finishBricks;
    public void buildWall(int width, int height) {
    Wall w = new Wall();
    String dimensions = "Wall" width "x" +height;
    this.finishBricks = w.xxxx; // where xxxx is replaced by whatever the String dimensions is
    class Wall {
         public double[][] Wall4x2 = {
              {-30.00,-01.60,27.45},
              {-30.00,-06.75,27.45},
              {-30.00,-13.55,27.45},
              {-30.00,-20.35,27.45},
              {-30.00,-22.00,28.65},
              {-30.00,-16.85,28.65},
              {-30.00,-10.05,28.65},
              {-30.00,-03.25,28.65}
         public double[][] Wall3x3 = {
              {-30.00,-01.60,27.45},
              {-30.00,-06.75,27.45},
              {-30.00,-13.55,27.45},
              {-30.00,-15.20,28.65},
              {-30.00,-10.05,28.65},
              {-30.00,-03.25,28.65},
              {-30.00,-01.60,29.85},
              {-30.00,-06.75,29.85},
              {-30.00,-13.55,29.85},
         public double[][] Wall2x4 = {
              {-30.00,-01.60,27.45},
              {-30.00,-06.75,27.45},
              {-30.00,-08.40,28.65},
              {-30.00,-03.25,28.65},
              {-30.00,-01.60,29.85},
              {-30.00,-06.75,29.85},
              {-30.00,-08.40,31.05},
              {-30.00,-03.25,31.05},

    Map walls = new HashMap ();
    walls.put ("2x2", new double[][] {
        new double[] {
            1,
            0
        new double[] {
            0,
            1
    double[][] wall = (double[][]) walls.get ("2x2");

  • Can j2me draw line with double values.

    Hi,
    Can any body know how to darw line in j2me with double values.
    I don't want use draw Line with int.
    Shall i use svg or j2me has solution.
    Thanks and regards,
    Rakesh.

    not possible
    graphics.drawLine(float,float,float,float);...there's no such method in MIDP API: [click here for javadoc of Graphics class methods|http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Graphics.html#drawLine(int,%20int,%20int,%20int)]

  • Error adding double values

    Processing in my application requires adding huge double values,
    for instance i am adding 36561584400629760 and 1152062986011661
    and instead of getting 37713647386641421 I get 37713647386641424.
    Does somebody have a clue as to what the problem could be?
    I tried using BigInteger and primitive double datatypes.
    Thanks

    doubles precision is about 16 digits. Try this     BigDecimal bd1 = new BigDecimal("36561584400629760"),
                  bd2 = new BigDecimal("1152062986011661");
         System.out.println(bd1.add(bd2));
    or
         BigInteger bi1 = new BigInteger("36561584400629760"),
                  bi2 = new BigInteger("1152062986011661");
         System.out.println(bi1.add(bi2));

  • Fast scaling of double values?

    So far, I use my own method to scale double values:
         * Scale decimal number via the rounding mode BigDecimal.ROUND_HALF_UP.
         * @param value Decimal value.
         * @param scale New scale.
         * @param roundingMode Optional rounding mode from BigDecimal.ROUND_... constants. (Default: BigDecimal.ROUND_HALF_UP)
         * @return Scaled number.
         * @since 1.8.3
        static public double getScaled(double value, final int scale, final int... roundingMode) {
            double result = value; //default: unscaled
            value = (Double.isNaN(value) || Double.isInfinite(value)) ? 0.0 : value; //reser NaN
            //use BigDecimal String constructor as this is the only exact way for double values
            int rm = BigDecimal.ROUND_HALF_UP;
            if (roundingMode != null && roundingMode.length > 0) {
                rm = roundingMode[0];
            result = new BigDecimal(""+value).setScale(scale, rm).doubleValue();
            return result;
        }//getScaled()BigDecimal offers scale methods, so I use them. The String constructor is also the only way to convert a double into a BigDecimal.
    This works fine but is quite slow on heavy number crunching with lots of scales. Is there a faster way?

    After heavy profiling of our number crunching apps, I replaced my former scaling method (with BigDecimal) with a costum version:
         * Get scaled decimal value with a fixed rounding method 'ROUND_HALF_UP'.
         * <p>
         * Note: there's also a getScaled() version that supports more rounding modes but is slower.
         * @param value Value to scale.
         * @param scale New scale.
         * @return Scaled values.
         * @since 2.14.0
         * @see #getScaled(double, int, int) Scaling with custom rounding mode.
        static public double getScaled(double value, final int scale) {
            double result = 0.0; //default: unscaled
            if (value != 0.0 && !Double.isNaN(value) && !Double.isInfinite(value)) {
                final BigDecimal bd = new BigDecimal(""+value);
                final int signum = bd.signum();
                final long l = bd.unscaledValue().abs().longValue();
                final int s = scale - bd.scale();
                if (s < 0) { //new scale is smaller than old scale
                    long l2 = l / (long) Math.pow(10.0, -s); //cut old unrequired scale
                    final long roundDigit = (l / (long) Math.pow(10.0, -s -1)) % 10;
                    if (roundDigit >= 5) {
                        l2 +=1;
                    result = l2 / Math.pow(10.0, scale);
                } else { //new scale is equal or greater than old scale
                    result = (l * Math.pow(10.0, s)) / Math.pow(10.0, scale);
                if (signum == -1) {
                    result = -result;
            }//else: Nan/Infinite => 0.0
            return result;
        }//getScaled()And even though it looks a bit scary, it make the whole application more than twice as fast (4 Minutes compared to 9 Minutes with the former BigDecimal scaling). As our app does lots of different calculations with lots of interim scaling and storing, this performance gain is quite surprising, as it shows that BigDecimal is not very usefull for massive math calculations ...

  • Double value of mouse click

    hi, I am making a program in which I need to get the Double value of the point where I clicked on my JPanel. Is it possible to get the Double or float value of the point at which mouse click event occur.

    The mouse pointer is always exactly on one physical pixel, hence the integer coordinates are most accurate. You could pretend that the user means some other point (like the center of the pixel instead of the upper left corner) than the one s/he is pointing, that's your own business.
    You may actually lose accuracy when you cast the ints to doubles or floats.

Maybe you are looking for