Hi, I am trying to write some code which uses a JSlider to specify the number of lables to be displayed on a frame. I know how to create the JSlider and display it, but I am not sure how to implement different numbers of lables. I hope someone can help.
Thank you!

Hi, I am trying to write some code which uses a JSlider to specify the number of lables to be displayed on a frame. I know how to create the JSlider and display it, but I am not sure how to implement different numbers of lables. I hope someone can help.
Thank you!

You need to set up a ChangeListener and add that ChangeListener to your JSlider object. When the JSlider object is changed, the stateChanged function will be called. Within that function, you:

1) Get the value of the JSlider.
2) Do something with that value. In this case, change the number of labels displayed in the frame based on that value.

I have written this code but I still does not work. I'm still not too sure on how to display lables according to the value on the slider. Here is what I have written:

/*
 * RunProgram.java
 *
 */
package project;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.event.*;

/**
 *
 *
 */
public class RunProgram extends JPanel implements ActionListener, ChangeListener {

    static JMenuBar bar;
    private JMenuItem fileOpen;
    private JPanel phasePanel;
    static JPanel contentPane;
    private JPanel picture1;
    private JPanel picture2;
    private JFileChooser fileChooser;
    File file;
    private JLabel leftPic;
    private JLabel rightPic;
    private JPanel toolPanel;
    JButton openButton;
    JSlider phaseSlider;
    private JButton openRight,  openLeft;

    /** Creates a new instance of RunProgram */
    public RunProgram() {
        setLayout(new BorderLayout());

        bar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        bar.add(fileMenu);

        fileOpen = new JMenuItem("Open");
        fileMenu.add(fileOpen);
        fileOpen.addActionListener(this);

        //Create a panel and make it the content pane.
        contentPane = new JPanel(new BorderLayout());
        contentPane.setBorder(BorderFactory.createRaisedBevelBorder());

        //create panel to show original pictures
        picture1 = new JPanel();
        picture1.setBackground(Color.BLUE);
        picture1.setBorder(BorderFactory.createLoweredBevelBorder());
        picture1.setPreferredSize(new Dimension(450, 1000));

        picture2 = new JPanel();
        picture2.setBackground(Color.GREEN);
        picture2.setBorder(BorderFactory.createLoweredBevelBorder());
        picture2.setPreferredSize(new Dimension(450, 1000));

        JPanel controlPanel = new JPanel();
        controlPanel.setBackground(Color.GRAY);
        controlPanel.setPreferredSize(new Dimension(800, 50));
        controlPanel.setLayout(new FlowLayout());

        openLeft = new JButton("<<<Open");
        openLeft.addActionListener(this);
        openRight = new JButton("Open>>>");
        openRight.addActionListener(this);
        picture1.add(openLeft);
        picture2.add(openRight);


        toolPanel = new JPanel();
        toolPanel.setPreferredSize(new Dimension(100, 50));

        //create panel to show the phases
        phasePanel = new JPanel();

        //JScrollPane scroller = new JScrollPane(phasePanel);
        phasePanel.setBackground(Color.DARK_GRAY);
        phasePanel.setBorder(BorderFactory.createRaisedBevelBorder());
        phasePanel.setLayout(new FlowLayout());
        phasePanel.setPreferredSize(new Dimension(1000, 200));

        JToolBar toolBar = new JToolBar("Still draggable");
        toolBar = new JToolBar(null, JToolBar.VERTICAL);
        toolBar.setFloatable(false);

        //Create the label
        JLabel sliderLabel = new JLabel("Number of Phases", JLabel.CENTER);
        toolBar.add(sliderLabel);

        phaseSlider = new JSlider(1, 5);
        phaseSlider.setMajorTickSpacing(1);
        phaseSlider.setPaintTicks(true);
        phaseSlider.setPaintLabels(true);
        phaseSlider.addChangeListener(this);

        toolBar.add(phaseSlider);

        toolBar.setPreferredSize(new Dimension(100, 50));
        openButton = new JButton("Open");
        toolBar.add(openButton);
        openButton.addActionListener(this);

        JButton p = new JButton();
        p.setPreferredSize(new Dimension(150, 150));
        //phasePanel.add(p);

        JButton q = new JButton();
        q.setPreferredSize(new Dimension(150, 150));
        //phasePanel.add(q);

        JButton r = new JButton();
        r.setPreferredSize(new Dimension(150, 150));
        //phasePanel.add(r);

        JButton s = new JButton();
        s.setPreferredSize(new Dimension(150, 150));
        //phasePanel.add(s);

        JButton t = new JButton();
        t.setPreferredSize(new Dimension(150, 150));
        //phasePanel.add(t);


        contentPane.add(phasePanel, BorderLayout.SOUTH);
        contentPane.add(toolBar, BorderLayout.NORTH);
        contentPane.add(picture1, BorderLayout.WEST);
        contentPane.add(picture2, BorderLayout.EAST);
        contentPane.add(bar, BorderLayout.NORTH);
        contentPane.add(toolBar, BorderLayout.CENTER);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        JFrame frame = new JFrame("ImageViewer");
        //UIManager.setLookAndFeel(napkinlaf);
        //SwingUtilities.updateComponentTreeUI(frame);
        frame.add(new RunProgram());
        frame.setSize(1100, 900);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setJMenuBar(bar);
        frame.setContentPane(contentPane);
        frame.setVisible(true);
    }

    /** Listen to the slider. */
    public void stateChanged(ChangeEvent e) {
        //JSlider source = (JSlider) e.getSource();
        if (!phaseSlider.getValueIsAdjusting()) {
            int noPP = (int) phaseSlider.getValue();
            if (noPP == 0) {
            } else {
                if (noPP == 1) {
                    createPhases(1);
                }
                if (noPP == 2) {
                    createPhases(2);
                }
                if (noPP == 3) {
                    createPhases(3);
                }
                if (noPP == 4) {
                    createPhases(4);
                }
                if (noPP == 5) {
                    createPhases(5);
                }
            }
        }
    }

    public void createPhases(int noOfPhases) {

        for (int i = 0; i < noOfPhases; i++) {
            JButton t = new JButton();
            t.setPreferredSize(new Dimension(150, 150));
            phasePanel.add(t);
        }
    }

    public void actionPerformed(ActionEvent e) {
        
        if (e.getSource() == fileOpen) {
            fileChooser = new JFileChooser(".");

            fileChooser.addChoosableFileFilter(new ImageFilter());
            fileChooser.setAcceptAllFileFilterUsed(false);

            fileChooser.setAccessory(new ImagePreview(fileChooser));
            int directory = fileChooser.showOpenDialog(RunProgram.this);
            if (directory == JFileChooser.APPROVE_OPTION) {

                file = fileChooser.getSelectedFile();
                ImageIcon largeImage = new ImageIcon(file.getAbsolutePath());
                leftPic = new JLabel(largeImage);
                leftPic.setBorder(new OvalBorder());
                leftPic.setPreferredSize(new Dimension(largeImage.getIconWidth(), largeImage.getIconHeight()));
                rightPic = new JLabel(largeImage);
                rightPic.setBorder(new OvalBorder());
                rightPic.setPreferredSize(new Dimension(largeImage.getIconWidth(), largeImage.getIconHeight()));
                picture1.add(leftPic);

            }
            picture1.revalidate();
            picture2.revalidate();
        }

        if (e.getSource() == openLeft) {
            fileChooser = new JFileChooser(".");

            fileChooser.addChoosableFileFilter(new ImageFilter());
            fileChooser.setAcceptAllFileFilterUsed(false);

            fileChooser.setAccessory(new ImagePreview(fileChooser));
            int directory = fileChooser.showOpenDialog(RunProgram.this);
            if (directory == JFileChooser.APPROVE_OPTION) {

                file = fileChooser.getSelectedFile();
                ImageIcon largeImage = new ImageIcon(file.getAbsolutePath());
                leftPic = new JLabel(largeImage);
                leftPic.setBorder(new OvalBorder());

                leftPic.setPreferredSize(new Dimension(largeImage.getIconWidth(), largeImage.getIconHeight()));
                rightPic = new JLabel(largeImage);
                rightPic.setBorder(new OvalBorder());
                rightPic.setPreferredSize(new Dimension(largeImage.getIconWidth(), largeImage.getIconHeight()));
                picture1.add(leftPic);
            }
            picture1.revalidate();
            picture2.revalidate();
        }
        if (e.getSource() == openRight) {
            fileChooser = new JFileChooser(".");

            fileChooser.addChoosableFileFilter(new ImageFilter());
            fileChooser.setAcceptAllFileFilterUsed(false);

            fileChooser.setAccessory(new ImagePreview(fileChooser));
            int directory = fileChooser.showOpenDialog(RunProgram.this);
            if (directory == JFileChooser.APPROVE_OPTION) {

                file = fileChooser.getSelectedFile();
                ImageIcon largeImage = new ImageIcon(file.getAbsolutePath());
                leftPic = new JLabel(largeImage);
                leftPic.setBorder(new OvalBorder());

                leftPic.setPreferredSize(new Dimension(largeImage.getIconWidth(), largeImage.getIconHeight()));
                rightPic = new JLabel(largeImage);
                rightPic.setBorder(new OvalBorder());
                rightPic.setPreferredSize(new Dimension(largeImage.getIconWidth(), largeImage.getIconHeight()));
                picture2.add(rightPic);
            }
            picture1.revalidate();
            picture2.revalidate();
        }
    }
}

There are two separate issues.

One, get the JSlider working, calling the stateChanged function, grabbing the value from the JSlider, then doing something with that value (in this case, I guess you are calling the createPhases function and passing it the value)?

Two, adjusting the number of JLabels to show in the frame.


You need to figure out which step is not working. You can do that pretty quickly. If you are using an IDE with a debugger, stick a breakpoint at the top of stateChanged and at the top of createPhases. Make sure those functions are being called when the JSlider moves. Further, in stateChanged, check the value of the variable that is passed to that function and verify that it is correct. If you're not using a debugger, stick some System.out.println commands in there to see where you are. If all that is happening correctly, the problem is not in step 1, but rather in step 2.

I see nothing in createPhases that has anything to do with labels. This function deals with JButtons.

public void createPhases(int noOfPhases) {

        for (int i = 0; i < noOfPhases; i++) {
            JButton t = new JButton();
            t.setPreferredSize(new Dimension(150, 150));
            phasePanel.add(t);
        }
    }

Thank you, I have tried what you said and it seems the problem is displaying the buttons (I originally was going to use labels but I changed it to buttons, I can't remember why now). Debugging it showed that the the values were being read from the slider and correctly stored in the variables. The createPhases method also correctly received the number of buttons to be created however it does not display the buttons. I am not sure why there is a problem here?

I can't run your code. There are classes missing, so it looks like it's part of something much larger. Looks like you're adding these buttons to a JPanel called phasePanel, not a frame. It probably wouldn't hurt to set phasePanel to have some background color, like blue, and make sure it's visible on the frame. If not, you have a Panel problem that needs to be solved first. I don't know what the exact problems you are having are, but there's a lot of code here. You may need to slim down the program to something smaller that gets to the issue you are having, so we can run it.

I slimmed down the code and then realised something, I wasn't redrawing the panel so the creation of the buttons weren't being applied. So I used the revalidate method. Now it works. Thanks for your help!

I slimmed down the code and then realised something, I wasn't redrawing the panel so the creation of the buttons weren't being applied. So I used the revalidate method. Now it works. Thanks for your help!

You're welcome. Glad you were able to solve it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.