Modifying a Jslider

Asked

Viewed 455 times

2

I’d like to do two things:

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

inserir a descrição da imagem aqui

2nd: Make the pointer/indicator of the slider, go to the color according to a certain number typed in the field (in the method below it is clearer to understand)

package pacote01;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Slider extends JFrame {

    public static final Color[] COLORS = {Color.red, Color.orange, Color.yellow, Color.green, Color.blue};
    private static final int COMPRIMENTO = 30;
    private static final int ALTURA = 10;

    private JSlider slider = new JSlider(0, 100, 0);
    public JTextField campo = new JTextField();

    private double valor;

    public Slider() {
        setSize(525, 300);
        add(montaSlider());
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JComponent montaSlider() {
        JPanel jpSlider = new JPanel();

        jpSlider.add(campo);
        campo.setPreferredSize(new Dimension(100, 20));

        campo.addActionListener(new ActionListener()//Caixa consulta é o campo que é digitado o código.
        {
            @Override
            public void actionPerformed(ActionEvent e) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
                    @Override
                    public boolean dispatchKeyEvent(KeyEvent e) {
                        if (e.getID() == KeyEvent.KEY_RELEASED && e.getKeyCode() == KeyEvent.VK_ENTER) {
                            definePonteiro();
                        } else {

                        }
                        return false;
                    }
                });
            }
        });

        int majorSpacing = slider.getMaximum() / (COLORS.length - 1);
        Dictionary<Integer, JLabel> dictionary = new Hashtable<>();
        slider.setMajorTickSpacing(majorSpacing);
        slider.setPaintLabels(true);
        slider.setPaintTicks(true);
        slider.setSnapToTicks(true);
        for (int i = 0; i < COLORS.length; i++) {
            ImageIcon icon = createColorIcon(COLORS[i]);
            JLabel label = new JLabel(icon);
            int key = i * majorSpacing;
            dictionary.put(key, label);
        }
        slider.setLabelTable(dictionary);
        jpSlider.add(slider, BorderLayout.CENTER);
        return jpSlider;
    }

    private ImageIcon createColorIcon(Color color) {
        BufferedImage img = new BufferedImage(COMPRIMENTO, ALTURA, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setColor(color);
        g.fillRect(0, 0, COMPRIMENTO, ALTURA);
        g.dispose();
        return new ImageIcon(img);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Slider s = new Slider();
            }
        });
    }

    public void definePonteiro() {
        valor = Double.valueOf(campo.getText());
        if (valor <= 11.5) {
            //seta o ponteiro na 1ª cor
            System.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ª");
        }
    }
}

1 answer

3


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

Instead of positioning below, I made an alternative way and that changes as little as possible your code, positioning the values internally in the colored Abels.

To do this, you would first need to create an array of the same size as the array COLORS, putting 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 you use to fill the colors, add these values as text in the boxes, 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 be displayed inside the colored flags.

2º: Make the slider pointer/indicator, go to the color according to a certain number typed in the field

Just use the good old math :)

Your slider is started with 100 being its maximum value and 0 being its minimum value, as are 5 colors, so each tick slider is equal to 100/5, that is, the space between each "tracinho" is 25. Knowing this information, just position the Knob as 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:

inserir a descrição da imagem aqui

  • 1

    Thank you, you’re a beast !

  • a doubt, I now tried to do the processing (capture the text) in another class, and tried to pass as parameter to the Slider class, but it did not work. I slider = new Slider(valueDaVarialvel); after calculation.

  • 1

    @Java wouldn’t be right to pass to the method definePonteiro()? The logic is the same as the current one, only instead of capturing from the text field, you pass the received value to ifs.

  • then, it is the same logic, using the system.out I confirmed that the value has, but it is not working, will be that the value is being lost when I pass to the definePonteiro() in the other class?

  • 2

    @Java testing here worked. Test there too: https://pastebin.com/4rUmTxSE

  • 1

    will it be because I’m using float ?

  • 1

    https://pastebin.com/8Pi0FSU4 look how I did it, please.

  • @Java in this code you do not call the method definePonteiro() never. Ai nothing will happen anyway. And Jslider only gets int, you need to cast to int otherwise your code won’t even compile.

  • https://pastebin.com/8Pi0FSU4 converted the value, and called the method in the constructor, maybe the call is wrong ?

  • 1

    @Java no problem in this code, I changed the imc to 50 and the slider started in the last position.

  • this last one I posted ? Here was not no :(

  • 1

    @Complicated Java, tested here and changed normally. Try creating a new project by copying the classes to it, it can be the IDE’s cache.

  • I couldn’t, but I’ll redo here to see if I find the mistake.

  • I believe I know why I made the mistake, but I don’t know what could be done, if that’s really the cause. I spread some system.out and realized that leaving the call of the method in the constructor, it runs only add the component on the screen, but ta td 0. after.

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.