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

Similar Messages

  • JMenu problem

    Hi,
    i'm developing a window consisting of a JMenuBar, y code is as follows..
    mbar=new JMenuBar();
    file=new JMenu("File");
    item1=new JMenuItem("Open");
    item2=new JMenuItem("Exit");
    file.setMnemonic('f');
    file.add(item1);
    file.add(item2);
    mbar.add(file);
    the problem is While clicking JMenu "File", happens nothing,
    is there any problem with this code???
    please help;
    thanks in adv

    Read the Swing tutorial on "How to Use Menus" for working examples:
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Add Drop Shadow to JMenu Problem

    Hi,
    I got this code from "Swing Hacks", for some reason it does not run for me, but throws exceptions. I can not figure out why this is happening. This code straight out of the book, should be runnable. Below is the custom class, then the driver-test class, then the Exception:
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.awt.*;
    public class CustomPopupMenuUI extends BasicPopupMenuUI{
         public static ComponentUI createUI(JComponent c){
              return new CustomPopupMenuUI();
         public Popup getPopup(JPopupMenu popup, int x,
                   int y){
              Popup pp = super.getPopup(popup, x,y);
              JPanel panel = (JPanel)popup.getParent();
              panel.setBorder(new ShadowBorder(3,3));
              panel.setOpaque(false);
              return pp;
    class ShadowBorder extends AbstractBorder{
         int xoff,yoff;
         Insets insets;
         public ShadowBorder(int x, int y){
              this.xoff = x;
              this.yoff = y;
              insets = new Insets(0,0,xoff,yoff);
         public Insets getBorderInsets(Component c){
              return insets;
         public void paintBorder(Component comp, Graphics g,
                   int x, int y, int width, int height){
              g.setColor(Color.BLACK);
              g.translate(x,y);
              // draw right side
              g.fillRect(width-xoff,yoff,xoff,height-yoff);
              // draw bottom side
              g.fillRect(xoff,height-yoff,width-xoff,yoff);
              g.translate(-x,-y);
    // Driver Below
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import java.awt.*;
    public class MenuTest {
         public static void main(String[] args)throws Exception{
              UIManager.put("PopupMenuUI","CustomPopupMenuUI");
              //UIManager.put("MenuItemUI","LucentMenuItemUI");
              JFrame frame = new JFrame();
              JMenuBar mb = new JMenuBar();
              //mb.setUI(new CustomMenuUI());
              frame.setJMenuBar(mb);
              JMenu menu = new JMenu("File");
              mb.add(menu);
              menu.add(new JMenuItem("Open"));
              menu.add(new JMenuItem("Save"));
              menu.add(new JMenuItem("Close"));
              menu.add(new JMenuItem("Exit"));
              menu = new JMenu("Edit");
              mb.add(menu);
              menu.add(new JMenuItem("Cut"));
              menu.add(new JMenuItem("Copy"));
              menu.add(new JMenuItem("Paste"));
              menu.add(new JMenuItem("Paste Special.."));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add("North",new JButton("Button"));
              frame.getContentPane().add("Center",new JLabel("Label"));
              frame.getContentPane().add("South",new JCheckBox("checkbox"));
              frame.pack();
              frame.setSize(200,150);
              frame.show();
    }Exception:
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPopupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
         at javax.swing.UIDefaults.getUIError(Unknown Source)
         at javax.swing.MultiUIDefaults.getUIError(Unknown Source)
         at javax.swing.UIDefaults.getUI(Unknown Source)
         at javax.swing.UIManager.getUI(Unknown Source)
         at javax.swing.JPopupMenu.updateUI(Unknown Source)
         at javax.swing.JPopupMenu.<init>(Unknown Source)
         at javax.swing.JPopupMenu.<init>(Unknown Source)
         at javax.swing.JMenu.ensurePopupMenuCreated(Unknown Source)
         at javax.swing.JMenu.add(Unknown Source)
         at hacks.MenuTest.main(MenuTest.java:23)
    advTHANKSance

    I am also using xp and java version 1.4.2_08, but to no avail.. see below:
    C:\workspace\Swing Hacks\src>java -version
    java version "1.4.2_08"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_08-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
    C:\workspace\Swing Hacks\src>java hacks.MenuTest
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0
    ,0x0,invalid,alignmentX=null,alignmentY=null,border=,flags=0,maximumSize=,minimu
    mSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPo
    pupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:689)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:719)
    at javax.swing.UIManager.getUI(UIManager.java:784)
    at javax.swing.JPopupMenu.updateUI(JPopupMenu.java:204)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:169)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:154)
    at javax.swing.JMenu.ensurePopupMenuCreated(JMenu.java:521)
    at javax.swing.JMenu.add(JMenu.java:556)
    at hacks.MenuTest.main(MenuTest.java:23)
    UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JPopupMenu[,0,0
    ,0x0,invalid,alignmentX=null,alignmentY=null,border=,flags=0,maximumSize=,minimu
    mSize=,preferredSize=,desiredLocationX=0,desiredLocationY=0,label=,lightWeightPo
    pupEnabled=true,margin=,paintBorder=true]
    java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:689)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:719)
    at javax.swing.UIManager.getUI(UIManager.java:784)
    at javax.swing.JPopupMenu.updateUI(JPopupMenu.java:204)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:169)
    at javax.swing.JPopupMenu.<init>(JPopupMenu.java:154)
    at javax.swing.JMenu.ensurePopupMenuCreated(JMenu.java:521)
    at javax.swing.JMenu.add(JMenu.java:556)
    at hacks.MenuTest.main(MenuTest.java:30)
    I don't understand what the issue could be..
    Can anyone reproduce this error??

  • Problems with JMenu

    Hi,
    i have a problem with the JMenu in a project.
    The JMenu starts with a normal behaviour.
    After a time an error occurs:
    One JMenuitem is selected, and every move in the JMenu changes the selection only for a short time.
    Then the selection jumps back to the former
    selection.
    Anyone who knows this problem?
    Thanks
    Guido

    I now know when the trouble starts. When i start a DragnDrop action and then moves above the JMenu the odd behaviour starts. With the same trick this behaviour ends.
    I'm now searching for a way to avoid this trouble.
    The JMenu is not a Droptarget.
    Any suggestions?
    Guido

  • JMenu pop-up SubMenu problem

    Hi,
    I'm having a problem displaying a submenu on a JMenu. My app has a tree with various nodes. After clicking on one of the nodes, you can either view the menu in pop-up form by right clicking on the node, or from a regular menu at the top of the screen. These menu's are identical and are generated by the same functions except one if pop-up and the other is not.
    Everything works fine, EXCEPT, when opening the pop-up menu, the submenu's do not appear - the "Select Files" item does not even have the submenu arrow next to it. I know this methos is entered and run without failure as I have debugged it but the submenus just do not appear.
    Here is the source:
    JMenuItem[] m_actions m_actions = new JMenuItem[actionNames.length];     // items for display in the popup menu for this object
    JMenu m_selectFiles = new JMenu("Select Files");                    // sub menu for select files option
    public void setMenu(JMenu aMenu, boolean aMultipleSelection) {          
         aMenu.removeAll();
         for(int i=0; i<m_actions.length; i++) {
              if (m_actions[i] instanceof JMenu) {
                   if (!m_actions.getText().equals("Select Files"))
                        aMenu.add((JMenu)m_actions[i]);
                   else                         
                        addSelectMenu (aMenu);                                             
              } else     {
                   aMenu.add(m_actions[i]);
                   if(aMultipleSelection & !m_multipleActions[i])
                        m_actions[i].setEnabled(false);
                        if(!aMultipleSelection & m_permittedActions[i])
                        m_actions[i].setEnabled(true);
    private void addSelectMenu (JMenu aMenu) {
         if (m_selectFiles.getItemCount() > 0) {
              m_selectFiles.removeAll();
         templateSubMenus = new JMenu("Output Templates");          
         if (templateNames == null)
              templateNames = getTemplates();
         else {
              templateNames.removeAllElements();
              templateNames = getTemplates();
         if (templateSubMenus.getItemCount() > 0) {
              templateSubMenus.removeAll();
         JMenu[] templateSubOptions = new JMenu[templateNames.size()];          
         for(int j=0; j<templateNames.size(); j++) {               
              templateSubOptions[j] = new JMenu((String)templateNames.elementAt(j));
              templateSubOptions[j].add(new JMenuItem("Modify"));
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).addActionListener(monListener);
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).setActionCommand("TempModify:"+(String)templateNames.elementAt(j));
              templateSubOptions[j].add(new JMenuItem("Copy"));
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).addActionListener(monListener);
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).setActionCommand("TempCopy:"+(String)templateNames.elementAt(j));
              templateSubOptions[j].add(new JMenuItem("Delete"));
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).addActionListener(monListener);
              templateSubOptions[j].getItem(templateSubOptions[j].getItemCount()-1).setActionCommand("TempDelete:"+(String)templateNames.elementAt(j));
              templateSubMenus.add((JMenu)templateSubOptions[j]);               
         templateSubMenus.addSeparator();
         templateSubMenus.add(new JMenuItem("New Template"));          
         templateSubMenus.getItem(templateSubMenus.getItemCount()-1).addActionListener(monListener);          
         m_selectFiles.add(templateSubMenus);
         aMenu.add((JMenu)m_selectFiles);          
    Any ideas would be greatly appreciated.
    Thanks!!!!!

    Hi,
    I have the same problem. Can anybody help please?
    Thanks,
    Kaveh

  • JMenu and Paint Problem

    Hello,
    I have been teaching my self Java and I have become quite proficient with it, however, I have a problem that I can not fix, or get around.
    I have a JMenuBar in a JFrame with some JMenu�s containing JMenuItems. I also have a JPanel that I draw inside (I Know that is probably not the wisest way to draw things, but it was the way I first learned to draw and now my program is too big and it is not worth while to change). Any ways, I draw some graphics inside of this JPanel.
    The menu items change the drawings; this is done by repainting the JPanel Graphic. However, when I click one of the menu items, the JPanel paints but there is a residual of the JMenu in the background that will not disappear.
    The menu is closed and if I open and then close the menu the residual goes away.
    => I would like to know how to prevent the residual from appearing?
    The problem also occurs when I use the popup menus outside of the JmenuBar.
    What I think is wrong.
    I think my problem is with the repaint. I don�t think the JFrame is repainting. I think I am simply repainting all the components in the JFrame but not the JFrame itself and thus the residual is not cleared from the JFrame. I don�t know how to fix this but I believe that is the problem because when I minimize the JFrame then Maximize it the JFrame will not paint, and I can see right through the JFrame, but the components paint fine.
    Sorry for the long question, but I don�t know what would be helpful.
    Any advice would be appreciated,
    Thank you
    Seraj

    // This is the code that listens for the menu item
    private void RBmmActionPerformed(java.awt.event.ActionEvent evt) {                                    
            calc.setIN(false);
            updateData();                    // updates some data
            paint2();                           // my special draw fuction shown below
        public void paint2()                          // this the special paint that draws on the JPanel
            Graphics page = jPanel1.getGraphics();
            if(start_end)
                myPic.draw(page);
            else
                page.setColor(Color.WHITE);
                page.fillRect((int)(OFFSET.getX()), (int)(OFFSET.getY()), (int)(R_BOUND-OFFSET.getX()), (int)(L_BOUND-OFFSET.getY()));
            repaint();             
    public void paint(Graphics g)               // this is the regular paint methode
            MessageHandler();
            ATD_age.repaint();
            StanderdCal.repaint();
            ChildSRF.repaint();
            MessageArea.repaint();
        }I hope that is helpful

  • JMenu and MouseListener problems

    I have a JMenu that is used as a JMenuItem in another JMenu in the menu bar. The same JMenu is added as a popup menu to a button.
    I added a MouseListener to the JMenu because I want to execute some code upon mouseEntered() and mouseExited().
    Problem: the listener is only fired when I enter or exit the menu from the menu bar, never when the popup menu of the button is entered or exited.
    What can I do to trigger the mouse listener?

    I have a JMenu that is used as a JMenuItem in another JMenu in the menu bar.Components can only have a single parent. I don't know how what you are describing is possible.
    If you want to share the ActionEvent then you should be using an Action when creating the menu. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html]How to use Actions.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Problems with disappearing JTextArea when activating JMenu

    Im having trouble with using JTextArea in conjunction with JMenu and JInternalFrame. I have a program that uses JInternalFrames for navigation, when the navigation been used I set the JInternalFrame to setVisible(false) and display a JMenuBar with several components and a JTextArea. The JTextArea gets displayed as it should and so is the JMenuBar but when a JMenuItem has been activated the JTextArea becomes invisible or partly invisible. Anyone have any suggestions?
    //Function that removes the JInternalFrame and adds the JMenuBar and JTextArea to the program
    public void ordBehandlare()
                   ramnav.setVisible(false); //ramnav == JInternalFrame
                   Container cont = getContentPane();
                   cont.add(ordbehandlarArea); //ordbehandlarArea == JTextArea
                   setJMenuBar(ordBehandBar); //ordBehandBar == JMenuBar
    Grateful for any answers...

    From the 5 lines of code you posted I have no idea whats wrong, but I'm sure you can create a 20 line program that we can compile and execute that demonstrates your problem. Chances are while your creating this simple program you will find your error.

  • ActionPerformed problem with jmenu

    hi i am trying to get the action performed for 'exit' in a JMenu but
    i cant seem to find the problem the program will run be nothing hapens when i click exit on the menu. any help would be greatly welcomed
    markimport java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    class MyFrame2 extends JFrame implements ActionListener{
         private JMenuBar bar = new JMenuBar();//create menubar
         private JMenu j1 = new JMenu();
         private JMenu j2 = new JMenu();
         private JMenu j3 = new JMenu();
         private JMenu j4 = new JMenu();
         private JMenu j5 = new JMenu();
         private JMenuItem jm1 = new JMenuItem();
         private JMenuItem jm2 = new JMenuItem();
         Container content;
    public MyFrame2(String str)
    {  super(str);
         content= this.getContentPane();
         content.setLayout(new FlowLayout());
    setSize(220,250);
         bar.add(j1);
         bar.add(j2);
         bar.add(j3);
         bar.add(j4);
         bar.add(j5);
         j1.setText("Register");
         j2.setText("Not Connected");
         j3.setText("New DB");
         j4.setText("Admin");
         j5.setText("Exit");
         j5.addActionListener(this);
         jm1.setText("Server Info");
         jm2.setText("User Admin");
         j4.add(jm1);
         j4.add(jm2);
         setJMenuBar(bar);
         setVisible(true); }
         public void actionPerformed(ActionEvent e){
         Object target=e.getSource();
              if (target== j5){System.exit(0);}
         public class Db4
         public static void main(String args[]) {
    MyFrame2 fr= new MyFrame2("Account Example");

    The problem is that your "j5" is a JMenu not a JMenuItem. JMenu objects respond to mouseclicks by displaying a popup menu not by calling an actionlistener. I changed "j5" to be a JMenuItem and it worked fine, although I won't advice placing JMenuItems directly on a menubar.

  • 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);}
    }

  • JMenu is behind Canvas. problem ?

    I have created a JFrame with a JMenuBar,
    I have added a ImageCanvas (sub class of Canvas) in the center of the JFrame
    but whenever i click on Menu it appears behind the canvas
    what to do pls help?

    Hey,
    Canvas is an awt component meaning it is a heavyweight
    component. The swing components are lightweight.
    Thats the problem.
    Have a look at the following URL.
    http://java.sun.com/products/jfc/tsc/articles/mixing/
    It should explain about mixing heavyweight/lightweight
    components
    Basically you either need to use Frame, Menu and
    canvas or JFrame, JMenu and JPanel.
    nesAnd heres the important part:
    "When a lightweight component overlaps a heavyweight component, the heavyweight component is always on top,
    regardless of the relative z-order of the two components."
    Use JPanel instead of canvas if your using swing.
    regards,
    Tim

  • 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();
    }

  • 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.

Maybe you are looking for

  • I have an error with the hpe363xa instrument driver. Where do I go from here?

    I have the latest versions of labview, max, gpib, ivi engine,... I downloaded the hpe363xa driver (for Agilent E3633A power supply). MAX configured the gpib ok (can communicate with instrument and gpib tests run ok). When I run the hpe363xa Getting S

  • IBook G3 & iWork

    I am starting college on Monday and I have a gliding instructor job coming up in the summer. As a result, I have been looking at getting an iBook to make my time more productive and portable. I want it to run Panther and need it to run Microsoft Offi

  • To read data from tape

    Hi All, can we read the data file or data from the tape ( magnetic tape) If yes then How? Thanks Neeraj

  • I'm looking for a computer with these specifications, can anyone help me?

    I need to know if anyone can give me the names of a few laptops that have these MINIMUM specifications: Intel Pentium 4 or AMD Athlon 64 Processor or any better processor 4 GB of RAM Windows 7 1280 X 800 or more with qualified hardware-accelerated Op

  • Restore a Time Machine backup on a newer version of the OS

    My MacBook running Leopard (10.5.5) was recently stolen, but fortunately I have a Time Machine backup. I'll make do with an old iBook running Tiger for now, but when I 've saved up a bit, and when Snow Leopard is released (and preferably a new versio