12

I'd like to add an on/off like toggle switch in a Java app. Do I need to build them up from Swing Sliders or is there something closer already?

http://www.premiumpixels.com/freebies/onoff-switches-and-toggles-psd/

http://modmyi.com/forums/iphone-2g-3g-3gs-ipod-touch-1g-2g-3g-new-skins-themes-launches/447951-release-off-slider-lockscreen.html

Apple uses toggle switches of the kind I'm describing in it's Desktop Applications too

Google uses toggle switches of the kind I'm describing in it's Web Applications too

1
  • Such a thing does not exist in the standar swing library. Try searching a 3rd party library or make one yourself. I'd use the JCheckBox. IPhone controls are intended for small touchscreens, swing ones are intended for large desktop screens sizes with a mouse. Sep 5, 2011 at 8:10

3 Answers 3

21

Just a little example, perhaps it help you.

enter image description here

public class Popup extends JFrame {

    public Popup() {
        setBounds( 100, 100, 300, 120 );
        setDefaultCloseOperation( 3 );
        getContentPane().setLayout( new FlowLayout( FlowLayout.LEADING, 10, 10 ) );
        getContentPane().add( new JSwitchBox( "on", "off" ));
        getContentPane().add( new JSwitchBox( "yes", "no" ));
        getContentPane().add( new JSwitchBox( "true", "false" ));
        getContentPane().add( new JSwitchBox( "on", "off" ));
        getContentPane().add( new JSwitchBox( "yes", "no" ));
        getContentPane().add( new JSwitchBox( "true", "false" ));
    }

    public static void main( String[] args ) {
        SwingUtilities.invokeLater( new Runnable() {
            @Override
            public void run() {
                new Popup().setVisible( true );
            }
        });
    }

    public class JSwitchBox extends AbstractButton{
        private Color colorBright = new Color(220,220,220);
        private Color colorDark = new Color(150,150,150);
        private Color black  = new Color(0,0,0,100);
        private Color white = new Color(255,255,255,100);
        private Color light = new Color(220,220,220,100);
        private Color red = new Color(160,130,130);
        private Color green = new Color(130,160,130);
        private Font font = new JLabel().getFont();
        private int gap = 5;
        private int globalWitdh = 0;
        private final String trueLabel;
        private final String falseLabel;
        private Dimension thumbBounds;
        private Rectangle2D bounds;
        private int max;


        public JSwitchBox(String trueLabel, String falseLabel) {
            this.trueLabel = trueLabel;
            this.falseLabel = falseLabel;
            double trueLenth = getFontMetrics( getFont() ).getStringBounds( trueLabel, getGraphics() ).getWidth();
            double falseLenght = getFontMetrics( getFont() ).getStringBounds( falseLabel, getGraphics() ).getWidth();
            max = (int)Math.max( trueLenth, falseLenght );
            gap =  Math.max( 5, 5+(int)Math.abs(trueLenth - falseLenght ) ); 
            thumbBounds  = new Dimension(max+gap*2,20);
            globalWitdh =  max + thumbBounds.width+gap*2;
            setModel( new DefaultButtonModel() );
            setSelected( false );
            addMouseListener( new MouseAdapter() {
                @Override
                public void mouseReleased( MouseEvent e ) {
                    if(new Rectangle( getPreferredSize() ).contains( e.getPoint() )) {
                        setSelected( !isSelected() );
                    }
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(globalWitdh, thumbBounds.height);
        }

        @Override
        public void setSelected( boolean b ) {
            if(b){
                setText( trueLabel );
                setBackground( green );
            } else {
                setBackground( red );
                setText( falseLabel );
            }
            super.setSelected( b );
        }
        @Override
        public void setText( String text ) {
            super.setText( text );
        }

        @Override
        public int getHeight() {
            return getPreferredSize().height;
        }

        @Override
        public int getWidth() {
            return getPreferredSize().width;
        }

        @Override
        public Font getFont() {
            return font;
        }

        @Override
        protected void paintComponent( Graphics g ) {
            g.setColor( getBackground() );
            g.fillRoundRect( 1, 1, getWidth()-2 - 1, getHeight()-2 ,2 ,2 );
            Graphics2D g2 = (Graphics2D)g;

            g2.setColor( black );
            g2.drawRoundRect( 1, 1, getWidth()-2 - 1, getHeight()-2 - 1, 2,2 );
            g2.setColor( white );
            g2.drawRoundRect( 1 + 1, 1 + 1, getWidth()-2 - 3, getHeight()-2 - 3, 2,2 );

            int x = 0;
            int lx = 0;
            if(isSelected()) {
                lx = thumbBounds.width;
            } else {
                x = thumbBounds.width;
            }
            int y = 0;
            int w = thumbBounds.width;
            int h = thumbBounds.height;

            g2.setPaint( new GradientPaint(x, (int)(y-0.1*h), colorDark , x, (int)(y+1.2*h), light) );
            g2.fillRect( x, y, w, h );
            g2.setPaint( new GradientPaint(x, (int)(y+.65*h), light , x, (int)(y+1.3*h), colorDark) );
            g2.fillRect( x, (int)(y+.65*h), w, (int)(h-.65*h) );

            if (w>14){
                int size = 10;
                g2.setColor( colorBright );
                g2.fillRect(x+w/2-size/2,y+h/2-size/2, size, size);
                g2.setColor( new Color(120,120,120));
                g2.fillRect(x+w/2-4,h/2-4, 2, 2);
                g2.fillRect(x+w/2-1,h/2-4, 2, 2);
                g2.fillRect(x+w/2+2,h/2-4, 2, 2);
                g2.setColor( colorDark );
                g2.fillRect(x+w/2-4,h/2-2, 2, 6);
                g2.fillRect(x+w/2-1,h/2-2, 2, 6);
                g2.fillRect(x+w/2+2,h/2-2, 2, 6);
                g2.setColor( new Color(170,170,170));
                g2.fillRect(x+w/2-4,h/2+2, 2, 2);
                g2.fillRect(x+w/2-1,h/2+2, 2, 2);
                g2.fillRect(x+w/2+2,h/2+2, 2, 2);
            }

            g2.setColor( black );
            g2.drawRoundRect( x, y, w - 1, h - 1, 2,2 );
            g2.setColor( white );
            g2.drawRoundRect( x + 1, y + 1, w - 3, h - 3, 2,2 );

            g2.setColor( black.darker() );
            g2.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
            g2.setFont( getFont() );
            g2.drawString( getText(), lx+gap, y+h/2+h/4 );
        }
    }
}
4
  • +1 for versatility. I was thinking of just clipping the icons provided, but this is easier to localize.
    – trashgod
    Sep 5, 2011 at 15:55
  • 1
    +1 for sexiness. But the slider feeling is absent. To immediately try the code mvn install; mvn exec:java -Dexec.mainClass="com.mysimpatico.sexybutton.Popup" dl.dropbox.com/u/23278095/SexyButton.zip
    – simpatico
    Sep 6, 2011 at 12:39
  • maybe you would want to answering this question
    – mKorbel
    Oct 9, 2013 at 14:23
  • @oliholz How can I set color for text?
    – sk786
    Dec 19, 2016 at 13:12
2

use built-in component JCheckBox.

JCheckBox cb = new JCheckBox(createImageIcon("off-image.gif", "Click To Turn On"));
cb.setSelectedIcon(createImageIcon("on-image.gif", "Click To Turn Off"));
3
  • +1 for re-use :-) just a small beware: you'll need localized icons - but that shouldn't be a big deal
    – kleopatra
    Sep 5, 2011 at 9:02
  • What do you mean with localized icons? Please share, I'm still learning with java :) Sep 5, 2011 at 9:10
  • there are more languages than English (as shown in the pic :)
    – kleopatra
    Sep 5, 2011 at 9:17
1

maybe by using JScrollBar, here is just and incompleted idea, up to you

enter image description here

import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Sliders {

    private JFrame frame;
    private JPanel main;
    private JPanel scrollBarPanel = new JPanel();
    private JPanel sliderPanel;

    public Sliders() {
        frame = new JFrame();
        main = new JPanel(new GridLayout(2, 1));
        final JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 100, 0, 200);
        int height = scrollBar.getPreferredSize().height;
        scrollBar.setPreferredSize(new Dimension(175, height));
        scrollBarPanel.add(scrollBar);
        main.add(scrollBarPanel);
        sliderPanel = new JPanel();
        final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
        slider.setMajorTickSpacing(48);
        slider.setMinorTickSpacing(16);
        slider.setPaintTicks(true);
        sliderPanel.add(slider);
        main.add(sliderPanel);
        frame.add(main, BorderLayout.CENTER);
        scrollBar.addAdjustmentListener(new AdjustmentListener() {

            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                System.out.println("JScrollBar's current value = " + scrollBar.getValue());
            }
        });
        slider.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                System.out.println("JSlider's current value = " + slider.getValue());
            }
        });
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Sliders sliders = new Sliders();
            }
        });
    }
}
4
  • wouldn't - you'll have to implement the selection logic (aka: ButtonModel) as well
    – kleopatra
    Sep 5, 2011 at 9:01
  • @kleopatra hmmm good well, ...., I' lost somewhere, no idea only this way stackoverflow.com/questions/4218117/…, and more than illusions could be possible, don't hesitage to update code that I posted,
    – mKorbel
    Sep 5, 2011 at 11:18
  • +1 interesting. I would have used JToggleButton with icons, but BoundedRangeModel works in a new JSlider(JSlider.HORIZONTAL, 0, 1, 0).
    – trashgod
    Sep 5, 2011 at 12:13
  • @trashgod right, ... or java-sl.com/tip_slider.html, but as his endless layzyness as you can see here stackoverflow.com/questions/4218117/…
    – mKorbel
    Sep 5, 2011 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.