JSlide problem

Hi,
I would like to know wether is possible inside stateChanged JSlider event to know why it is firing.
I mean, to know wether the user is dragging the thumb or just clicking at the slide. I know about valueIsAdjusting, but both return true.
If it's not possible here in this event, where could I get it?
Thanks a lot

Did you ever figure this out? I am running into the same thing...

Similar Messages

  • JSlider problem

    Hi everybody
    I have just a small problem with JSlider, if ye bare with me i'll try to expalin it. Basically i have created a time line, ie when you scroll to the max of the slider it will keep updating the max (increasing the max value)thus creating some sort of dynamic slider.
    Example:
    if the max is 60 initially and you scroll to 60 it will increase the max by 10 and increase the min by 10 thus giving the appearance of a dynamic timeline.
    My problem is when it does update (increase by 10) the labels don't appear on the slider (eg 70, 80 etc).
    I have pasted the class below if that is any help to anybody!
    Any help is appreciated!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TimeLine extends JSlider implements BoundedRangeModel, ChangeListener
    {   public TimeLine(DefaultBoundedRangeModel brm,int theGUIMin, int theGUIMax, int theRealMin, int theRealMax)
    {   super(brm);
    realMax = theRealMax;
    realMin = theRealMin;
    currentMax = theGUIMax;
    currentMin = theRealMin;
    this.setMajorTickSpacing(10);
         this.setMinorTickSpacing(1);
    this.setPaintTicks(true);
         this.setPaintLabels(true);
    this.addChangeListener(this);
    public void setRangeProperties(int x, int y, int z,int a, boolean b)
    public void stateChanged(ChangeEvent ce)
    {   int currentValue = getValue();
    System.out.println("Current Value = " + currentValue);
    if(currentValue > (currentMax - 1) && currentValue < realMax)
    {   currentMax += sliderIncrement;
    currentMin += sliderIncrement;
    // System.out.println("Current Max = " + currentMax);
    // System.out.println("Current Min = " + currentMin);
    timeModel = new DefaultBoundedRangeModel(currentMax,0,currentMin,currentMax);
    setModel(timeModel);
    setMajorTickSpacing(10);
         setMinorTickSpacing(1);
    setPaintTicks(true);
         setPaintLabels(true);
    else if(currentValue < (currentMin+1) && currentValue > realMin )
    {   System.out.println("Reducing TimeLine");
    currentMax -= sliderIncrement;
    if(currentMin > realMin)
    {   currentMin -= sliderIncrement;
    System.out.println("Current Max = " + currentMax);
    System.out.println("Current Min = " + currentMin);
    timeModel = new DefaultBoundedRangeModel(currentMin,0,currentMin,currentMax);
    setModel(timeModel);
    else
    private final int INITIAL_MIN = 0;
    private final int INITIAL_MAX = 60;
    private int guiMax, guiMin, currentMin, currentMax,realMax,realMin, sliderIncrement = 5;
    private DefaultBoundedRangeModel timeModel;
    private TimeLine timeLine;
    public static void main(String[] args)
    {   JFrame frame = new JFrame("Time Line");
    Container contentPane = frame.getContentPane();
    DefaultBoundedRangeModel dbrm = new DefaultBoundedRangeModel(0,0,0,60);
         //TimeLine t = new TimeLine(0,60,0,240);
    TimeLine t = new TimeLine(dbrm,0,60,0,240);
         contentPane.add(t);
    frame.setSize(250,150);
         frame.show();
    }

    Hi everybody
    I have just a small problem with JSlider, if ye bare with me i'll try to expalin it. Basically i have created a time line, ie when you scroll to the max of the slider it will keep updating the max (increasing the max value)thus creating some sort of dynamic slider.
    Example:
    if the max is 60 initially and you scroll to 60 it will increase the max by 10 and increase the min by 10 thus giving the appearance of a dynamic timeline.
    My problem is when it does update (increase by 10) the labels don't appear on the slider (eg 70, 80 etc).
    I have pasted the class below if that is any help to anybody!
    Any help is appreciated!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TimeLine extends JSlider implements BoundedRangeModel, ChangeListener
    {   public TimeLine(DefaultBoundedRangeModel brm,int theGUIMin, int theGUIMax, int theRealMin, int theRealMax)
    {   super(brm);
    realMax = theRealMax;
    realMin = theRealMin;
    currentMax = theGUIMax;
    currentMin = theRealMin;
    this.setMajorTickSpacing(10);
         this.setMinorTickSpacing(1);
    this.setPaintTicks(true);
         this.setPaintLabels(true);
    this.addChangeListener(this);
    public void setRangeProperties(int x, int y, int z,int a, boolean b)
    public void stateChanged(ChangeEvent ce)
    {   int currentValue = getValue();
    System.out.println("Current Value = " + currentValue);
    if(currentValue > (currentMax - 1) && currentValue < realMax)
    {   currentMax += sliderIncrement;
    currentMin += sliderIncrement;
    // System.out.println("Current Max = " + currentMax);
    // System.out.println("Current Min = " + currentMin);
    timeModel = new DefaultBoundedRangeModel(currentMax,0,currentMin,currentMax);
    setModel(timeModel);
    setMajorTickSpacing(10);
         setMinorTickSpacing(1);
    setPaintTicks(true);
         setPaintLabels(true);
    else if(currentValue < (currentMin+1) && currentValue > realMin )
    {   System.out.println("Reducing TimeLine");
    currentMax -= sliderIncrement;
    if(currentMin > realMin)
    {   currentMin -= sliderIncrement;
    System.out.println("Current Max = " + currentMax);
    System.out.println("Current Min = " + currentMin);
    timeModel = new DefaultBoundedRangeModel(currentMin,0,currentMin,currentMax);
    setModel(timeModel);
    else
    private final int INITIAL_MIN = 0;
    private final int INITIAL_MAX = 60;
    private int guiMax, guiMin, currentMin, currentMax,realMax,realMin, sliderIncrement = 5;
    private DefaultBoundedRangeModel timeModel;
    private TimeLine timeLine;
    public static void main(String[] args)
    {   JFrame frame = new JFrame("Time Line");
    Container contentPane = frame.getContentPane();
    DefaultBoundedRangeModel dbrm = new DefaultBoundedRangeModel(0,0,0,60);
         //TimeLine t = new TimeLine(0,60,0,240);
    TimeLine t = new TimeLine(dbrm,0,60,0,240);
         contentPane.add(t);
    frame.setSize(250,150);
         frame.show();
    }

  • Java swing player progress JSlider problem

    Hello every body. Basically i m creating a player type of application using JMF API.
    Now the problem with me is that i want to create a jslider so that while playing a file, when i drag the slider, the media should be than forwarded.
    I have successfully created the JSlider and it is working absolutely correct but the problem is that i want to update the jslider with the song or track playback.
    I have used the while loop as well but it hangs my whole application.
    Thanx and regards
    immediate help would be appreciated.
    Salman.

    hiii guys.... u had created the java media player can u give me the code for that its urgent thanks in advance plsss give me that code

  • Jslider problem help please!!!

    Could any one tell me how to have two different label tables on both sides(vertival slider).
    Thanks in advance

    I haven't done alot with the JSlider, nor have I attempted to do what you want, but I am fairly certain the JSlider does not have have the functionality to display two labels on opposite sides of the slider.
    These idea is not guarenteed, if you are interested you might want to try it:
    descend an object from JPanel
    use a grid layout in the JPanel
    place a second custom JPanel in the main JPanel next to the JSlider
    Do some custom painting in the custom JPanel to draw your second label
    This is what I would try myself if I was in need of what you are looking for.
    Best of luck,
    Dan Hughes

  • JSlider in JMenu problem.

    I have recently switched to using jdk1.5.0_04 and have some problem.
    I have a JSlider contained in a JMenu. But I cannot drag the slider anymore, this worked in java 1.4. I can only click on a tick on the slider and the sldier will move to the location i clicked, but it is very slow.
    Anyone have any suggestions?
    Also, how do you disable selection in a JTextPane?

    Components that respond to MouseEvents and are embedded in a JMenu are broken in 1.5.
    Take a look at the last 3 messages in this thread, which includes a link to the bug report
    http://forum.java.sun.com/thread.jspa?threadID=654329&messageID=3849153

  • Problems with JSlider

    Hi, I have created a JSlider and have put 5 lables on it that represent rotations. My problem is, I do not know how to set up my program to actually rotate my shape when the slider is moved to that particular rotation. I have the snap to ticks set to true. I'm thinking that I will have to do it using an ActionListener, but not sure if this is the correct path. Any Suggestion?
    This is what my slider looks like:
    Right Left Up Down

    here's something that might start you off.
    adding a mouseListener (mouseReleased) will give you the value of the slider.
    as your labels are not in the order of the natural angles, perhaps a switch
    statement to set the angle of the rotation, then call repaint()
    mouseReleased is working OK in this (java 1.4.0_01) i.e. displays only 0,90,180 or 270,
    but it might be safer to wrap the slider.getValue() in a SwingUtilities.invokeLater()
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      JSlider slider = new JSlider(0,270,0);
      public Testing()
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(200,100);
        slider.setMajorTickSpacing(90);
        java.util.Hashtable labelTable = new java.util.Hashtable();
        labelTable.put(new Integer(0), new JLabel("Right"));
        labelTable.put(new Integer(90), new JLabel("Left"));
        labelTable.put(new Integer(180), new JLabel("Up"));
        labelTable.put(new Integer(270), new JLabel("Down"));
        slider.setLabelTable(labelTable);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setSnapToTicks(true);
        JPanel jp = new JPanel();
        jp.add(slider);
        getContentPane().add(slider);
        pack();
        slider.addMouseListener(new MouseAdapter(){
          public void mouseReleased(MouseEvent me){
            int value = slider.getValue();
            //use value to determine/set the angle (via switch statement),
            //then call repaint()
            System.out.println(value);
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • JProgressBar/JSlider error problem

    Hi there,
    I am attempting to integrate either a JProgressBar or JSlider into a user interface. The component will be updated in real time and will represent the height of a viewplatform in a virtual universe. The problem is, every time I run it, when the value of the height changes from one int to the next I get the following errors,
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlShadow(MetalLookAndFeel.java:1075)
    at javax.swing.plaf.metal.MetalProgressBarUI.paint(MetalProgressBarUI.java:67)
    at javax.swing.plaf.ComponentUI.update(ComponentUI.java:39)
    at javax.swing.JComponent.paintComponent(JComponent.java:398)
    at javax.swing.JComponent.paint(JComponent.java:739)
    at javax.swing.JComponent.paintWithBuffer(JComponent.java:4393)
    at javax.swing.JComponent._paintImmediately(JComponent.java:4336)
    at javax.swing.JComponent.paintImmediately(JComponent.java:4187)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(System
    EventQueueUtilities.java:205)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:317)
    at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:106)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:84)
    I don't have any changelisteners attached to either component. Any and all help would be greatly appreciated,
    thanks,
    old_noakes

    I have this code to update my JProgressBar:
    public void updateStatus(final int i) {
    Runnable doSetProgressBarValue = new Runnable() {
    public void run() {
    progressBar.setValue(i);
    SwingUtilities.invokeLater(doSetProgressBarValue);
    You need to do it in separate thread. In case of JProgressBar you need to do so in event-dispatching thread. It's why you have thread related exceptions when running your prog.
    In method where you change height you call updsateStatus() method, this method when called place the request into event queque meaning that it does not clash with any other thread but wait for best time (very short).
    void changeHeight(...) {
    height = ...;
    updateStatus(height?);
    and then the code above.
    Try it, it should work just fine.

  • Tough JSlider TableCellRenderer Problem!

    Hi,
    Ive been doing some work with tables and it involved using alot of different components in them. The only one that i cant get to work is JSlider. Using JSlider as a custom TableCellEditor seems to work fine, but it doesnt see to draw itself as a TableCellRenderer. Below I have some code that seems to illustrate the problem.
    So my question is : has anyone ever used JSlider suceesfully as a TableCellRenderer? If so, got a demonsration or something you had to do? If you have problems too can you think of any way around it (either a hack to get it to work or some other component that looks/works the same)?
    Well I hope this doesnt come down to writing my own JSlider... Anyway, thanks in advance for any help...
    Joshua
    Here is the code. What it does is makes a simple application with a table in it, with integers as values in the center panel. The cell renderer is a panel with a button and a JSlider in it (the slider has a border and the background is set to white to show where is should be). In the bottom panel of the app is the slider panel how it is drawn when it is not in a table.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JSlider;
    import javax.swing.JScrollPane;
    import javax.swing.JButton;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import java.awt.FlowLayout;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Color;
    import javax.swing.BorderFactory;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    * A main frame with a table in it... wish it painted sliders in the table
    public class TestSliderTable extends JFrame
        public TestSliderTable()
            addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent evt)
                    System.exit(0);
            setUpTable();
        private void setUpTable()
            JTable table = new JTable(new SomeDumbTableModel())
                public TableCellRenderer getCellRenderer(int row, int column)
                    return new JSliderTableCellRenderer();
            table.setRowHeight(50);
            //make a center panel, with a ScrollPane with the table in it
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            JScrollPane pane = new JScrollPane(table);
            JPanel flowPanel = new JPanel();
            flowPanel.setLayout(new FlowLayout());
            flowPanel.add(pane);
            panel.add(flowPanel, BorderLayout.CENTER);
            //make a panel on the bottom to just show the component
            panel.add(new JSliderTableCellRenderer(), BorderLayout.SOUTH);
            setContentPane(panel);
            pack();
        public static void main(String[] args)
            TestSliderTable frame = new TestSliderTable();
            frame.setVisible(true);
    * A simple cell renderer that should render sliders...
    class JSliderTableCellRenderer extends JPanel
        implements TableCellRenderer
        JSlider slider;
        JButton button;
        /** Creates new JSliderTableCellRenderer */
        public JSliderTableCellRenderer()
            super();
            slider = new JSlider(0, 10, 5);
            slider.setBackground(Color.white); //did this so you can see where the slider should be
            button = new JButton(">>>");
            setLayout(new FlowLayout());
            add(button);
            add(slider);
            add(button);
            slider.setBorder(BorderFactory.createLineBorder(Color.black));
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                        boolean p3, boolean p4,
                                                        int row, int column)
            int newValue = ((Integer)value).intValue();
            slider.setValue(newValue);
            return this;
    * a simple table model with Integers as values...
    class SomeDumbTableModel extends AbstractTableModel
        public SomeDumbTableModel() { }
        public int getRowCount() { return 10; }
        public int getColumnCount() { return 1; }
        public Object getValueAt(int row, int column) { return new Integer(row); }
    }

    I tried adapting this from a JButtonTable example, but gave up.
    http://forum.java.sun.com/thread.jsp?forum=57&thread=121545
    It's got a problem in that the slider doesn't show up until the cell has focus. I was going to set the value field too, but I'm going home to dinner. Good Luck!
    package test;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class JButtonTableExample extends JFrame {
      public static void main(String[] args) {
        JButtonTableExample frame = new JButtonTableExample();
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        frame.setSize( 400, 100 );
        frame.setVisible(true);
      public JButtonTableExample() {
        super( "JButtonTable Example" );
        DefaultTableModel dm = new DefaultTableModel() {
          public boolean isCellEditable(int rowIndex, int columnIndex) {
         if (columnIndex == 1) return false;
         return true;
        dm.setDataVector(new Object[][]{{"x","1"},
         {"y","2"}},
         new Object[]{"Slider","Value"});
        JTable table = new JTable(dm);
    //    editor.addCellEditorListener(new MyListener(table, 1, "Side A", "Side B"));
        table.getColumn("Slider").setCellRenderer(new SliderRenderer());
        SliderEditor seditor = new SliderEditor(50);
        table.getColumn("Slider").setCellEditor(seditor);
        getContentPane().add(new JScrollPane(table));
      class SliderRenderer extends JSlider implements TableCellRenderer {
        public SliderRenderer() {
          this.setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value,
           boolean isSelected, boolean hasFocus, int row, int column) {
          if (isSelected) {
         setForeground(table.getSelectionForeground());
         setBackground(table.getSelectionBackground());
          } else{
         setForeground(table.getForeground());
         setBackground(UIManager.getColor("Button.background"));
    //      this.setText( (getValue()==null) ? "" : getValue.toString() );
          return this;
      class SliderEditor extends DefaultCellEditor {
        protected JSlider slider;
        public SliderEditor(int Value) {
          super(new JCheckBox());
          slider = new JSlider();
          slider.setOpaque(true);
          slider.setValue(Value);
    //      slider.addActionListener(new ActionListener() {
    //     public void actionPerformed(ActionEvent e) {
    //       fireEditingStopped();
        public Component getTableCellEditorComponent(JTable table, Object value,
           boolean isSelected, int row, int column) {
          if (isSelected) {
         slider.setForeground(table.getSelectionForeground());
         slider.setBackground(table.getSelectionBackground());
          } else{
         slider.setForeground(table.getForeground());
         slider.setBackground(table.getBackground());
          return slider;
        public Object getCellEditorValue() {
          return new Integer(slider.getValue());
        public boolean stopCellEditing() {
          return super.stopCellEditing();
        protected void fireEditingStopped() {
          super.fireEditingStopped();
    }

  • JSLider changeListener problem

    Hello,
    I'm having a problem with a JApplet I'm writing. I have 2 Jsliders and a checkbox. If I check the box then one of the sliders should become disabled, if I uncheck the box then it should become active. I have sloved parts of the problem: I can disable the JSlider. The code works fine, except that once disabled it doesn;t enable anymore. So I tried writing code to enable it, but then after a few clicks on the JSlider my Applet freezes up!
    Here is the code snippet:
              //initialize the eventlisteners
              adjustZperc.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                        wu.changeZiektePerc((double)((JSlider) e.getSource()).getValue()/100.0);
                        su.changeZiektePerc((double)((JSlider) e.getSource()).getValue()/100.0);
                        fillAllSetValues();
                        if (chbIVA.isSelected()) {
                             adjustZperc.removeChangeListener(this);
                        else adjustZperc.addChangeListener(this);
              adjustVCperc.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                        wu.changeBenuttingVC((double)((JSlider) e.getSource()).getValue()/100.0);
                        su.changeBenuttingVC((double)((JSlider) e.getSource()).getValue()/100.0);
                        fillAllSetValues();
              chbIVA.addItemListener(new ItemListener() {
                   public void itemStateChanged(ItemEvent e) {
                        wu.changeIVA((e.getStateChange() == ItemEvent.SELECTED));
                        su.changeIVA((e.getStateChange() == ItemEvent.SELECTED));
                        if (e.getStateChange() == ItemEvent.SELECTED) adjustZperc.setValue(100);
              });Any ideas??
    Thanks in advance
    Benoit
    Edited by: benoize on Jun 1, 2008 2:00 PM

    Thanks for the tip, but I already did that to a certain extent.There's no such thing as a code snippet which is an SSCCE "to a certain extent". Either it's and SSCCE or it isn't. Posting a SSCCE will definitely help you to get better help sooner, but it's your choice.
    if I remove the line ... then everything works fine,You may be unwittingly kicking off an infinite loop. Add a Sysout to observe whether this is the case:else {
      System.out.println("addChangeListener");
      adjustZperc.addChangeListener(this);
    }Perhaps you could use a boolean field in stateChanged to determine whether or not to process the ChangeEvent, instead of repeatedly adding and removing the ChangeListener.

  • Problems calling JSlider.setValue() from ChangeListener.stateChanged()

    G'day,
    I want to restrict the value a JSlider can take on according to the value of another JSlider, for example I have two sliders, min and max and I want to ensure that min.getValue() <= max.getValue().
    Fairly straightforward, here's the code to do it:
    public class SliderProblem
            extends JFrame
        public SliderProblem()
            // Set-up sliders.
            final JSlider min = new JSlider(0, 1000, 0);
            final JSlider max = new JSlider(0, 1000, 1000);
            min.setMajorTickSpacing(200);
            max.setMajorTickSpacing(200);
            min.setMinorTickSpacing(50);
            max.setMinorTickSpacing(50);
            min.setPaintLabels(true);
            min.setPaintTicks(true);
            max.setPaintLabels(true);
            max.setPaintTicks(true);
            /* This fixes the problem.
           min.setSnapToTicks(true);
           max.setSnapToTicks(true); */
            // Layout frame.
            final Container pane = getContentPane();
            pane.setLayout(new GridLayout(0, 1));
            pane.add(min);
            pane.add(max);
            // Create listener.
            final ChangeListener listener = new ChangeListener()
                public void stateChanged(final ChangeEvent e)
                    final Object source = e.getSource();
                    if (min.equals(source))
                        // Ensure min <= max.
                        final int limit = max.getValue();
                        if (min.getValue() > limit)
                            min.setValue(limit);
                    else if (max.equals(source))
                        // Ensure max >= min.
                        final int limit = min.getValue();
                        if (max.getValue() < limit)
                            max.setValue(limit);
            // Listen up.
            min.addChangeListener(listener);
            max.addChangeListener(listener);
        public static void main(String args[])
            final SliderProblem frame = new SliderProblem();
            frame.pack();
            frame.setVisible(true);
    }The problem is that even though the ChangeListener calls JSlider.setValue(limit) the thumb of the JSlider is not repositioned to the limit value.
    If I resize the JFrame holding the sliders then the thumbs are correctly repainted.
    I've tried calling repaint() explicitly (including within SwingUtilities.invokeLater()), and working directly with the BoundedRangeModel underlying the JSliders but all to no avail.
    The only thing that does work is to call setSnapToTicks(true). However, for the specific application I'm working on I need setSnapToTicks(false).
    All suggestions appreciated.
    Thanks,
    Chris.

    Ok, I didn't understand what you exactly want.
    So change your listener like this:
    public void stateChanged(final ChangeEvent e)
         final Object source = e.getSource();
         if (min == source)
              if (min.getValueIsAdjusting())
                   return;
              // Ensure min <= max.
              final int limit = max.getValue();
              if (min.getValue() > limit)
                   SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                             min.setValue(limit);
         else if (max == source)
              if (max.getValueIsAdjusting())
                   return;
              // Ensure max >= min.
              final int limit = min.getValue();
              if (max.getValue() < limit)
                   SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                             max.setValue(limit);                                        
    }

  • Problem with JSlider

    I have a JSlider whose minimum value can be -50 and maximum value +50. Why function setValue(int n) doesn't work?
    Advance thanks!
    Best Regards!

    Come on, you've posted here enough to know you should put the exception your message. Without it you're asking, "I'm getting an error, can someone tell me how to fix it?". Need more information. Post the stack trace. Post some code (using the code tag as shown at http://forum.java.sun.com/faq.jsp#format).

  • Centering JButton in JPanel below JSlider, layout problem.

    Hi,
    I am tring to put together a configuration dialog for mouse double click speed. What I want is a largish JButton centered below a JSlider in the JPanel. So people can try double clicking on it :)
    I have written the code but am a novice to Swing layout. There does not seem to be a layout manager to do the job.
    How do I go about this ?
    Do I have to write my own layout manager, use abosolute positioning or is there a simpler way ?
    Many thanks in advance,
    Aaron Gray - [email protected]

    I apologize. I was not completely correct in what I told you in an earlier post. The BoxLayout always respects a component's minimum and maximum sizes. This means that if you set the preferred size to be bigger that the maximum size, it will not make it larger than the maximum size. To ensure that you get the correct size you should set both the preferred size and the maximum size to the size you want the button to be.
    When I created a layout I got something that seemed to be what you wanted. Below is some code describing what I did, then under that is a crude ascii diagram of what the layout looks like.
    JButton button;
    //Code to inialize button ...
    JSlider slider;
    //Code to initialize slider ...
    JPanel content = new JPanel();
    BoxLayout layout = new BoxLayout(content, BoxLayout.Y_AXIS);
    content.setLayout(layout);
    slider.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    button.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    content.add(slider);
    content.add(button);Ascii diagram
         |                             |
         | <-------[|]---------------> |
         |        ____________         |
         |       |            |        |
         |       | Click Here |        |
         |       |____________|        |
         |_____________________________|Is this what you were thinking of ???

  • Problem with jpanel size

    Hi I want to add a view port to a JPanel
    the main problem is that the Jpanel change size as the frame.
    how can i make it independent from the frame so having it; own w, h
    thanks
    package help;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private static JButton drawCircle, drawRectangle, drawSquare, drawStar, start, clear,quit,back, screenshoot;
    static final int FPS_MIN = 0;
    static final int FPS_MAX = 150;
    static final int FPS_INIT = 0;
    static int fps;
    double x1,x2;
    double y1,y2;
    int dr =1;
    int dy= 1;
    int Selection=0;
    boolean click=true; //check if start has been clicked
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;     //screen higth
    protected static int count;
    int R,G,B;  //color
    Cursor c;                    //cursor object
    private static ShapePanel bpnl;
    public MyFrame()
            R=G=B=0;
            int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
            int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            frame.setTitle("Game");
            //panel to hold buttons
            JPanel upPanel = new JPanel();
            upPanel.setLayout(new FlowLayout());
            upPanel.setSize(width, height/5);
            //panel to hold SLIDERS
            JPanel leftPanel = new JPanel();
            leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
            leftPanel.setSize(50, height);
            //initialize buttons and add to the upPanel
            drawCircle=new JButton("Draw Circle");
            upPanel.add(drawCircle);
            drawStar=new JButton("Draw Star");
            upPanel.add(drawStar);
            drawRectangle=new JButton("Draw Rectangle");
            upPanel.add(drawRectangle);
            drawSquare=new JButton("Draw Square");
            upPanel.add(drawSquare);
            start=new JButton("Start");
            start.setBackground(Color.GREEN);
            //upPanel.add(start);
            clear=new JButton("Clear");
            upPanel.add(clear);
            back=new JButton("Back");
            upPanel.add(back);
            quit=new JButton("Quit");
            quit.setBackground(Color.red);
            upPanel.add(quit);  
            screenshoot=new JButton("ScreenShoot");
            c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
         this.setCursor (c);
            //new object spanel to hold TIMER
            JPanel spanel=new JPanel();
                spanel.setLayout(new GridLayout());
                //slider dimension construction
                JSlider sDimension = new JSlider(JSlider.HORIZONTAL,FPS_MIN, FPS_MAX, FPS_INIT);
                sDimension.setMajorTickSpacing(30);
                sDimension.setMinorTickSpacing(3);
                sDimension.setPaintTicks(true);
                sDimension.setPaintLabels(true);
                Font font = new Font("Serif", Font.ITALIC, 15);
                sDimension.setFont(font);
                sDimension.setBorder(BorderFactory.createTitledBorder("Shape Dimension"));
                //slider speed construction
                int FPS_MIN_s = 0;
                int FPS_MAX_s = 60;
                int FPS_INIT_s = 0;    //initial frames per second
                JSlider sSpeed = new JSlider(JSlider.HORIZONTAL,FPS_MIN_s, FPS_MAX_s, FPS_INIT_s);
                sSpeed.setBorder(BorderFactory.createTitledBorder("Shape Speed"));
             ////////////////////////// // slider colors////////////////////////////////////////////////////
                int FPS_MIN_C = 0;
                int FPS_MAX_C = 250;
                int FPS_INIT_C = 0;  
                JSlider sliderR= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderR.setBorder(BorderFactory.createTitledBorder("Red Channel"));
                JSlider sliderG= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderG.setMajorTickSpacing(50);
                sliderG.setMinorTickSpacing(25);
                sliderG.setPaintTicks(true);
                sliderG.setPaintLabels(true);
                sliderG.setFont(font);
                sliderG.setBorder(BorderFactory.createTitledBorder("Green Channel"));
                JSlider sliderB= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderB.setBorder(BorderFactory.createTitledBorder("Blue Channel"));
              //     spanel.add(sSpeed,BorderLayout.EAST);
                  frame.add(upPanel,BorderLayout.NORTH);
                  frame.add(leftPanel,BorderLayout.WEST);
                  bpnl = new ShapePanel(3000,3000);
                        System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
                        bpnl.setFocusable(true);
                  upPanel.setBackground(Color.DARK_GRAY);
                  upPanel.setBorder(BorderFactory.createLineBorder(Color.white));
            frame.add(spanel,BorderLayout.SOUTH);       
            frame.add(bpnl, BorderLayout.CENTER);
            frame.setSize(width, height);
            frame.setVisible(true);               
               leftPanel.add(sliderR);
               leftPanel.add(sliderB);
               leftPanel.add(sliderG);
               leftPanel.add(sDimension,BorderLayout.WEST); 
                 System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private javax.swing.Timer animationTmr;
         private float heigth;
         private float width;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
        thanks

    sorry i hope this is better
    package help;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    int dr =1;
    int dy= 1;
    int Selection=0;
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;     //screen higth
    private static ShapePanel bpnl;
    public MyFrame()
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            bpnl = new ShapePanel(3000,3000);
            System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
            bpnl.setFocusable(true);
              frame.add(bpnl);
            frame.setSize(width, height);
               pack();
            frame.setVisible(true);               
    System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
       

  • JSlider + Display value in a text tool tip box

    Hello,
    I am new to Java. I want to display the value in a text tool tip box of the JSlider as the user moves the knob . Is there any way to achieve this.
    I tried setting up the value of text tool tip in the stateChanged method. But that didn't helped
    Ritesh

    Finally Got it working. Below I am attaching the code for reference
    Thanks for your code. It came very handy
    The only problem is that toolTextTip is appearing on one side rather than below the cursor.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class EventTest
    public static void main(String[] args)
    JFrame f = new JFrame();
    System.out.println("starting application");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new setSlider(),"North");
    JSlider slide = new JSlider();
    slide.setToolTipText("Hello");
    f.getContentPane().add(slide,"South");
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
    class setSlider extends JSlider implements ChangeListener, MouseMotionListener{
    public setSlider(){
    setToolTipText("hello " + new Integer(getValue()).toString());
    this.setMaximum(10);
    this.setMinimum(0);
    this.setValue(2);
    this.setMajorTickSpacing(2);
    this.setMinorTickSpacing(1);
    this.setPaintTicks(true);
    this.setPaintLabels(false);
    this.addMouseMotionListener(this);
    this.addChangeListener(this);
    public void stateChanged(ChangeEvent e) {
    setToolTipText(new Integer(getValue()).toString());
    System.out.println(this.getToolTipText());
    KeyStroke controlF1 = KeyStroke.getKeyStroke("control F1");
    ActionListener toolTipAction = getActionForKeyStroke( controlF1 );     
    if (toolTipAction != null)     {          
    ActionEvent postTip = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "");
    toolTipAction.actionPerformed( postTip );
    public void mouseDragged(MouseEvent e){
    System.out.println("here");
    setToolTipText(new Integer(getValue()).toString());
    System.out.println(this.getToolTipText());
    KeyStroke controlF1 = KeyStroke.getKeyStroke("control F1");
    ActionListener toolTipAction = getActionForKeyStroke( controlF1 );     
    if (toolTipAction != null)     {          
    ActionEvent postTip = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "");
    toolTipAction.actionPerformed( postTip );
    public void mouseMoved(MouseEvent e){

  • How to disable (grey-out) the ticks of a JSlider?

    Hi everyone,
    In my GUI, I have a JSlider that I want to be disabled (greyed out)
    because it should be only actived on my application next version.
    (It is important though to have it to preserve GUI appearence).
    Problem is that I was unable to greyout the ticks even though
    already managed to grey out the slider and the number labels.
    Right now, it is pretty uggly to have a partial disabled slider,
    because due to ticks not being disabled.
    Questions:
    1) Does anyone have an idea of how to do it?
    A small part of my code is shown below:
    JSlider dynSl = new JSlider();
    dynSl.setMajorTickSpacing(1);
    dynSl.setValue(0); //Default
    dynSl.setMaximum(7);
    dynSl.setMinimum(0);
    dynSl.setPaintLabels(true);
    dynSl.setPaintTicks(true);
    dynSl.setFont(new java.awt.Font("Dialog", 0, 9));
    dynSl.setSnapToTicks(true);
    dynSl.setEnabled(false);
    // small code just to put the numbers of the slider smaller
    Enumeration enum = dynSl.getLabelTable().elements();
    while (enum.hasMoreElements()) {
    JLabel elem = (JLabel)enum.nextElement();
    elem.setFont(new Font("Dialog",0,8));
    elem.setEnabled(false);
    2) If not possible, how do I change the colour of a JSlider (including
    the Ticks)?
    My idea is to change Slider's colour to the same grey colour one used
    to disable it, making at the end the slider look as if it was disabled.
    Thanks in advance,
    Jorge

    Hi again,
    Thanks for the help.
    I was trying to avoid not having the ticks at all but it seems to be
    the best choise because I could not solve the problem of greying out
    them.
    I did some more troubleshooting though and for my surprise, if I use
    the same code alone, i.e, a simple frame with just the slider it works
    fine. I even thought that it was related with having Windows LnF as
    opposed to Metal (Java) LnF, but that was not the problem.
    The only thing it comes to mind, is that there may be some problem by including the slider on a GridBagLayout !?!?!?
    Anyway,
    What has no simple solution, solved is! :-)
    Jorge

Maybe you are looking for