Combining JSlider with JMenu - Volume Component

JMenu and JSlider Coded Together

Let us code two JMenu and JSlider together to make a volume component in swing. That's dead simple. Here is a program demonstrating it.

As said in the post Creating MenuButtons in Swing this example is much related to it.

MenuSlider Volume

* - Swing JSlider in JMenu - Coded together.
* Copyright (C) 2012  Gowtham Gutha. All Rights Reserved.
* Website:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MenuSlider extends JFrame
JMenuBar mbar;
JMenu menu;
JSlider js;
public MenuSlider()
setTitle("Menu Slider");
setLayout(new FlowLayout());

js=new JSlider();
mbar=new JMenuBar();
menu=new JMenu("Volume");

public static void main(String args[])
new MenuSlider();

js=new JSlider(): Create a new JSlider using the first constructor.

mbar=new JMenuBar(): Create a JMenuBar.

menu=new JMenu("Volume"): Create a JMenu menu with text Volume

menu.add(js): Add JSlider to the JMenu.

mbar.add(menu): Add JMenu (menu) to JMenuBar.

add(mbar): Add JMenuBar to frame. Don't set it. If you do, the menubar appears from starting to end of the frame. It spreads over. That may not be good. However, for a Volume like component it the adding looks better. If you wish to, it's your wish. You can change it. Note that, the license is about not to change & publish it on other sites, it doesn't restrict you to change and use it in your application.

You can download the entire source code(.java) file from Google Code here.

Other swing examples can be found at
Also see 4 ways to create JSlider

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

Posted by at on

Tags: Swing Hacks,