Modifying a JSlider

2

I'd like to do two things:

1st: add a label, or anything, that allows me to put a "text" below the colors. Example in the illustration:

2nd:Makethepointer/pointerofslider,gotocoloraccordingtoacertainnumberenteredinthefield(inthemethodbelowisclearertounderstand)p>

packagepacote01;importjava.awt.BorderLayout;importjava.awt.Color;importjava.awt.Dimension;importjava.awt.Graphics;importjava.awt.KeyEventDispatcher;importjava.awt.KeyboardFocusManager;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.KeyEvent;importjava.awt.image.BufferedImage;importjava.util.Dictionary;importjava.util.Hashtable;importjavax.swing.ImageIcon;importjavax.swing.JComponent;importjavax.swing.JFrame;importstaticjavax.swing.JFrame.EXIT_ON_CLOSE;importjavax.swing.JLabel;importjavax.swing.JPanel;importjavax.swing.JSlider;importjavax.swing.JTextField;importjavax.swing.SwingUtilities;publicclassSliderextendsJFrame{publicstaticfinalColor[]COLORS={Color.red,Color.orange,Color.yellow,Color.green,Color.blue};privatestaticfinalintCOMPRIMENTO=30;privatestaticfinalintALTURA=10;privateJSliderslider=newJSlider(0,100,0);publicJTextFieldcampo=newJTextField();privatedoublevalor;publicSlider(){setSize(525,300);add(montaSlider());setLocationRelativeTo(null);setVisible(true);setDefaultCloseOperation(EXIT_ON_CLOSE);}privateJComponentmontaSlider(){JPaneljpSlider=newJPanel();jpSlider.add(campo);campo.setPreferredSize(newDimension(100,20));campo.addActionListener(newActionListener()//Caixaconsultaéocampoqueédigitadoocódigo.{@OverridepublicvoidactionPerformed(ActionEvente){KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(newKeyEventDispatcher(){@OverridepublicbooleandispatchKeyEvent(KeyEvente){if(e.getID()==KeyEvent.KEY_RELEASED&&e.getKeyCode()==KeyEvent.VK_ENTER){definePonteiro();}else{}returnfalse;}});}});intmajorSpacing=slider.getMaximum()/(COLORS.length-1);Dictionary<Integer,JLabel>dictionary=newHashtable<>();slider.setMajorTickSpacing(majorSpacing);slider.setPaintLabels(true);slider.setPaintTicks(true);slider.setSnapToTicks(true);for(inti=0;i<COLORS.length;i++){ImageIconicon=createColorIcon(COLORS[i]);JLabellabel=newJLabel(icon);intkey=i*majorSpacing;dictionary.put(key,label);}slider.setLabelTable(dictionary);jpSlider.add(slider,BorderLayout.CENTER);returnjpSlider;}privateImageIconcreateColorIcon(Colorcolor){BufferedImageimg=newBufferedImage(COMPRIMENTO,ALTURA,BufferedImage.TYPE_INT_RGB);Graphicsg=img.getGraphics();g.setColor(color);g.fillRect(0,0,COMPRIMENTO,ALTURA);g.dispose();returnnewImageIcon(img);}publicstaticvoidmain(String[]args){SwingUtilities.invokeLater(newRunnable(){@Overridepublicvoidrun(){Sliders=newSlider();}});}publicvoiddefinePonteiro(){valor=Double.valueOf(campo.getText());if(valor<=11.5){//setaoponteirona1ªcorSystem.out.println("1ª");
        } else if (valor <= 20) {
            //seta o ponteiro na 2ª cor
            System.out.println("2ª");
        } else if (valor <= 30) {
            //seta o ponteiro na 3 cor
            System.out.println("3ª");
        } else if (valor <= 40) {
            //seta o ponteiro na 4ª cor
            System.out.println("4ª");
        } else if (valor <= 50) {
            //seta o ponteiro na 5ª cor
            System.out.println("5ª");
        }
    }
}
    
asked by anonymous 28.05.2017 / 00:32

1 answer

3
  

1st: add a label, or anything, that allows me to put a "text" below the colors.

Instead of positioning below, I've made an alternate form that changes as little as possible your code, placing the values internally on the colored labels.

For this, you would first need to create an array of the same size as the array COLORS , putting the values in it:

public static final Color[] COLORS = {Color.red, Color.orange, Color.yellow, Color.green, Color.blue};
//5 cores, 5 valores
public static final String[] valuesColor = {"10", "20","30","40","50"};

Then, taking advantage of the loop that you use to fill the colors, add these values as text in the labels, aligning horizontally in the center then:

for (int i = 0; i < COLORS.length; i++) {
    ImageIcon icon = createColorIcon(COLORS[i]);
    JLabel label = new JLabel(icon);
    //aqui você vai adicionar o valor
    //correspondente a cor de mesmo indice
    label.setText(valuesColor[i]);
    label.setForeground(Color.white);//altere a cor dos números como quiser aqui
    label.setHorizontalTextPosition(JLabel.CENTER);//centraliza o texto
    int key = i * majorSpacing;
    dictionary.put(key, label);
}

With these changes, the values will appear inside the colored labels.

  

2nd: Make the slider pointer / indicator go to the color according to a certain number entered in the

Just use the good old math:)

Your slider starts with 100 being its maximum value and 0 being its minimum value, as they are 5 colors, so each tick of the slider is equal to 100/5 , that is, the space between each "draw" is 25. Knowing this information, simply position the knob according to the label below it:

public void definePonteiro() {

    valor = Double.valueOf(campo.getText());
    //variavel que armazenará a posicao do knob
    int sliderPos = 0;

    if (valor <= 11.5) {          
        sliderPos = 0;
    } else if (valor <= 20) {
        sliderPos = 25;
    } else if (valor <= 30) {
        sliderPos = 50;
    } else if (valor <= 40) {
        sliderPos = 75;
    } else if (valor <= 50) {
        sliderPos = 100;
    }
    slider.setValue(sliderPos);
}

See the result of the two changes in operation:

    
28.05.2017 / 01:37