Transfer value to an external method in Java

So I have a program that’s meant to update a thermometer bar (using drawRect) dynamically based on the position of a JSlider. What I’m trying to do is to pass that value to an external method so I can use it to update the size of the rectangle. I’m a VB guy so I’m having trouble figuring out how to do it.

Here’s my main class:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;

public class ThermoProject extends JApplet
    JSlider mySlider;
    JPanel sliderPanel;
    JPanel northernPanel = new NorthPanel();
    JLabel printLabel = new JLabel("");
    static int fillSize = 0;
    int topSize = 100;

    public void init() //init is the "main" for an applet
        add(northernPanel, BorderLayout.NORTH); //separate class
        add(printLabel, BorderLayout.WEST); //add label to top
        add(sliderPanel, BorderLayout.SOUTH); //add the panel to the south of the borderLayout

    private void buildSliderPanel()
        sliderPanel = new JPanel();
        //JSlider(direction, beginning, end, initial location)
        mySlider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);

        //add listener
        mySlider.addChangeListener(new SliderListener());

        //add to panel


    public class SliderListener implements ChangeListener

        public void stateChanged(ChangeEvent e)
            //change when slider is moved
            //topSize = 100 - fillSize;
            //drawRect(x, y, width, height)
            //fillRect(x, y, width, height)

And here’s my subclass, which is mostly used to build a separate JPanel.

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;

public class NorthPanel extends JPanel
    JPanel theNorthernPanel;
    int fillSize = 0;

    public void paint(Graphics g)
        //drawRect() and fillRect() args are x, y, width, height
        g.drawRect(90, 90, 200, 30);
        g.fillRect(90, 90, fillSize, 30);

    public NorthPanel()
        JPanel theNorthernPanel = new JPanel();
        setPreferredSize(new Dimension(200, 200));
        JLabel printLabel = new JLabel(String.valueOf(fillSize));


    public void updateThermo(int temperature)
        fillSize = temperature;



try this:

NorthPanel northernPanel = new NorthPanel(); // to declare

and then,

northernPanel.updateThermo(mySlider.getValue()); //to call

Leave a Reply

Your email address will not be published. Required fields are marked *