JLayeredPane in JScrollPane!

here I am again, I thought I had solved it but apparently not so I'm trying some other way. Now what I have is the JLayeredPane inside the JScrollPane but the problem is that if I don't do this:
layeredPane.setPreferredSize(new Dimension(1500, 1500));this is okay but when I want to insert info beyond this dimension it gets invisible. so what I wanted is the layeredPane' size to be dynamic..can anyone help me please?
thanx a lot really
iland

Constructor
// JLayeredPane   
    jlayeredPane = new JLayeredPane();
    jspLayered = new JScrollPane(jlayeredPane);
    jlayeredPane.addComponentListener(this);
    add(jspLayered, BorderLayout.CENTER);
    jlayeredPane.setPreferredSize(new Dimension(1000, 1000));
    jlayeredPane.add(graph, JLayeredPane.DEFAULT_LAYER);
public void componentResized(ComponentEvent e) {
    Component c = e.getComponent();
    graph.setSize(c.getSize());
    graph.validate();
    c.repaint();
  }can u tell me pleasewhere do i revalidate the scrollpane and how , i really don't know
thanx iland

Similar Messages

  • JLayeredPane with JScrollPane inside

    Hi all,
    I am making an applet with a fairly complex gui. The main part is a content window that has a jpanel with another jpanel and a jscrollpane inside, each of which have a bunch of components. From there I wanted to add a help window that popped up when you hit the help button. What I did is I got the JLayeredPane from the applet using getLayeredPane(), and I added the help window to the popup layer, and the content window to the default layer. I'm using a null layout and manually setting the bounds of everything. All the panels draw correctly, but when I open the help window, it displays inside the JScrollPane; i.e. it moves when I scroll, and the contents of the scroll pane are displayed on top of the help window. Here is some of my code, if I wasn't clear:
              //this grabs the applet's layered pane. The wrapper pane (with all the traces)
              //is on the default layer, and the help window (and any other popups) will go in the popup layer
              appletLayered = getLayeredPane();
              appletLayered.setLayout(null);
              //create the help window that will be displayed when someone presses help
              helpWindow = new HelpWindow(getCodeBase().toString());
              appletLayered.add(helpWindow, JLayeredPane.POPUP_LAYER);
              helpWindow.setBounds(50,50,400,450);
              appletLayered.add(wrapperPane, JLayeredPane.DEFAULT_LAYER);
              wrapperPane.setBounds(0,20,700,550);Does anyone know why it is doing this? Should I just do this whole thing a different way, or is there an easy solution that I'm missing.

    Swing related questions should be posted in the Swing forum.
    From there I wanted to add a help window* that popped up when you hit the help button.Then use a JDialog (or a JWindow), not a layered pane.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • JLayeredPane inside JScrollPane - please help!!

    Hi everyone!
    i'm having the following problem: I need to add a JLayeredPane to a JScrollPane. this JLayeredPane contains a JGraph and this is what I'm doing:
      jlayeredPane = new JLayeredPane();
        jlayeredPane.add(graph, JLayeredPane.DEFAULT_LAYER);
        jlayeredPane.setPreferredSize(new Dimension(1000,1000));
        jlayeredPane.setMinimumSize(new Dimension(1000,1000));
        jsp = new JScrollPane(jlayeredPane);
       add(jsp);
    [/code
      but the graph doesn't show up at all. can anyone help me please. i have a deadline today and really need to figure this out. thanx a lot

    here's some of my code:
    inside the construtor of a panel
    graph = new Graph(new DefaultGraphModel(), new GraphLayoutCache());
        // JLayeredPane
        jlayeredPane = new JLayeredPane();
        // jlayeredPane.setMinimumSize(new Dimension(400,400));
        jlayeredPane.setPreferredSize(new Dimension(400, 400));
        jlayeredPane.add(graph, JLayeredPane.DEFAULT_LAYER);
        jsp= new JScrollPane(jlayeredPane); 
        jsp.addComponentListener(this);
        add(jsp, BorderLayout.CENTER);
    public void componentResized(ComponentEvent e) {
        int layeredPaneWidth = jlayeredPane.getWidth();
        int layeredPaneHeight = jlayeredPane.getHeight();
        int viewportwidth = jspLayered.getViewport().getWidth();
        int viewportheight = jspLayered.getViewport().getHeight();
        int width = Math.max(layeredPaneWidth, viewportwidth);
        int height = Math.max(layeredPaneHeight, viewportheight);
        jspLayered.getViewport().setSize(new Dimension(width, height));
        graph.setSize(width, height);
        graph.setPreferredSize(new Dimension(width, height));   
      }

  • JTable, JScrollPane, and JinternalFrame problems.

    I have this internal frame in my application that has a scrollpane and table in it. Some how it won't let me selelct anything in the table. Also it scrolls really weird. There's a lot of chopping going on. Here's my code for the internal frame:
    public class BCDEObjectWindow extends javax.swing.JInternalFrame{
        private Vector bcdeObjects = new Vector();
        private DefaultTableModel tModel;
        public BCDEObjectWindow(JavaDrawApp p) {
            initComponents();
            this.setMaximizable(false);
            this.setClosable(false);
            this.setIconifiable(true);
            this.setDoubleBuffered(true);
            objectTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            listScrollPane.setColumnHeaderView(new ObjectWindowHeader());
            pack();
            this.setVisible(true);
            parent = p;
            getAllBCDEFigures();
            setPopupMenu();
            tModel = (DefaultTableModel) objectTable.getModel();
            objectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        public void getAllBCDEFigures() {
            bcdeObjects.removeAllElements();
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
        public void addBCDEFigure(BCDEFigure b) {
            bcdeObjects.add(b);
            tModel.addRow(new Object[]{b.BCDEName, "incomplete"});
        public void changeLabelName(BCDEFigure b) {
            if (bcdeObjects.contains(b)) {
                int index = bcdeObjects.indexOf(b);
                tModel.removeRow(index);
                tModel.insertRow(index, new Object[]{b.BCDEName, "incomplete"});
        public void removeBCDEFigure(BCDEFigure b) {
            int index = 0;
            if (bcdeObjects.contains(b)) {
                index = bcdeObjects.indexOf(b);
                bcdeObjects.remove(b);
                tModel.removeRow(index);
        public void removeAllBCDEFigures(){
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
            bcdeObjects.removeAllElements();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            listScrollPane = new javax.swing.JScrollPane();
            objectTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setBackground(new java.awt.Color(255, 255, 255));
            setIconifiable(true);
            setTitle("BCDE Objects");
            listScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            listScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            listScrollPane.setPreferredSize(new java.awt.Dimension(250, 150));
            objectTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Name", "Status"
                boolean[] canEdit = new boolean [] {
                    true, false
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
            objectTable.setColumnSelectionAllowed(true);
            listScrollPane.setViewportView(objectTable);
            jPanel1.add(listScrollPane);
            getContentPane().add(jPanel1);
            pack();
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane listScrollPane;
        private javax.swing.JTable objectTable;
        // End of variables declaration
    }and this is how i create the object in my JFrame:
    bcdeOW = new BCDEObjectWindow(this);
            bcdeOW.setLocation(400, 0);
            if (getDesktop() instanceof JDesktopPane) {
                ((JDesktopPane)getDesktop()).setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                ((JDesktopPane)getDesktop()).add(bcdeOW, JLayeredPane.PALETTE_LAYER);
            } else
                getDesktop().add(bcdeOW);Any help would be great. Thanks a lot.

    Rajb1 wrote:
    to get the table name to appear
    create a scollpane and put the table in the scrollpane and then add the the scollpane to the component:
    //declare
    scrollpane x;
    //body code
    scrollpane x - new scrollpane();
    table y = new table();
    getContentPane().add(x(y));What language is this in, the lambda calculus -- add(x(y))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • How to keep a label at the left side of a JScrollPane

    Hi all
    I am essentially trying to make a text block that doesn't move as the scrollpane scrolls (horizontally in my case)
    Here's my code trying to do this simply using Graphics.drawString (not compilable - tell me if you need something that compiles):
              g.setFont(getTaskFont());
              g.setColor(getTaskLabelForeground());
              g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              JScrollPane sp = ComponentUtilities.getJScrollPaneAncester(this);
              for (int i = 0; i < tasks.size() - 1; i++) {
                   Task t = tasks.get(i + 1);
                   FontMetrics fm = g.getFontMetrics();
                   int y = i * (rowHeight + rowSpace) + fm.getAscent() + (rowHeight - fm.getHeight()) / 2;
                   int strlen = fm.stringWidth(t.getName().toUpperCase());
                   int start = getXLocationForTime(t.getStart());
                   int end = getXLocationForTime(t.getFinish());
                   int len = end - start;
                   int x = 0;
                   //System.out.println("task: " + t.getName());
                   if (strlen < len) {
                        x = Math.min(end + 5, Math.max(start + 3, sp.getHorizontalScrollBar().getValue()));
                   else {
                        x = end + 5;
                   g.drawString(t.getName().toUpperCase(), x, y);
              }Here's my code trying to do this using a JLabel
                   JScrollPane sp = ComponentUtilities.getJScrollPaneAncester(this);
                   int y = i * (rowHeight + rowSpace); //+ fm.getAscent() + (rowHeight - fm.getHeight()) / 2;
                   int strlen = fm.stringWidth(t.getName().toUpperCase());
                   int start = getXLocationForTime(t.getStart());
                   int end = getXLocationForTime(t.getFinish());
                   int len = end - start;
                   int x = 0;
                   //System.out.println("task: " + t.getName());
                   if (strlen < len) {
                        x = Math.min(end + 5, Math.max(start + 3, sp.getHorizontalScrollBar().getValue()));
                   else {
                        x = end + 5;
                   floaters.setLocation(x, y + (rowHeight - fm.getHeight()) / 4);
                   floaters[i].repaint();
    Both [i]almost work, but the scrolling is not smooth (blinks back & forth). It seemed like a double buffering problem, but when I added code to paint first to an image and then to screen the issue remained.
    I also tried adding labels to the JLayeredPane popup layer, but I this solution is problematic also, as labels start drawing all over the place. Plus, I'd rather not have to keep track of the labels and be repositioning them in the first place.
    Any advice on this is sincerely appreciated.
    Thanks!
    -Tom
    Anyone know how to fix this?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Darryl Burke wrote:
    a label at the left side of a JScrollPaneI take it <tt>setRowHeader</tt> / <tt>setRowHeaderView</tt> don't do what you want?
    dbThat's a very helpful suggestion, and I think would solve the problem as stated, however in reading your answer I see now that I didn't state my problem well, and that what I am trying to do is much more complex than I originally thought it was.
    Thanks tho, you have helped me gain clarity in what I am trying to do.

  • Help with JScrollPane

    I have a JScrollPane that I need to add multiple components to. That includes 5 JButtons, and 5 Jtree's.
    I need to add all of the components at once, making the JTree's visible and invisible by clicking the JButton's. My first problem is when I try to add multiple objects to the JScrollPane using the default layout manager. The last object added is always stretched to fill the entire viewport. This makes the objects first added un-viewable. So I decided to first add all of the objects to a Box then add the Box to the scrollpane.
    My second problem occurs when I make a JTree visible, aftering adding it to the Box. It draws the tree completely from top to bottom as it should, but clips the right end of titles on the nodes. The horizontal scroll adjusts enought so that you can scroll far enough to the right, but the titles are cut off.
    If I add one of the JTree's directly to the JScrollPane it behaves as it should, showing the complete node titles.
    I've tried revalidating, updating, and repainting without success.
    So, first question is can multiple objects be added to a JScrollPane using the default layout manager, without having the last object hide the previously added objects?
    Secondly, does anyone know why nodes in a JTree would be clipped when added to a Box then added the Box added to a JScrollPane. And more importantly how to fix it.
    Any help would be appreciated,
    Thanks,
    Jim

    Hi there
    Im not sure on exactly what you are trying to do.
    But if you want multiple components in one JScrollPane
    I would use a JPanel that I would add to the JScrollPane
    On that JPanel I would then add my components.
    I would also use GridBagLayout instead of any other layout manager. Thats because it is the most complex
    layout manager and it will arrange the components as I whant.
    If you whant to be able to remove a component from the view by making them invisible. I think I would consider
    JLayeredPane.
    on a JLayeredPane you add components on different layers. Each component is positionend exactly with setLocation or setBounds. This is the most exact thing to use. The JLayeredPane uses exact positioning of its components. which can be usefull when you use
    several components that will be visible at different times
    /Markus

  • Create an image of a JLayeredPane 's content

    hi there,
    we have a problem here: we'd like to create one image out of a JLayeredPane`s content. but the only thing we get is a gray box which size is the size of the JLayeredPane.
    the purpose is: we're developing a graphic tool where you can draw and arrange objects in the JLayeredPane(which is in a JScrollPane). and now we're implementing the print-function which allows to print the graphs over several pages, therefore it is neccessary to have an image(*.jpeg) for our printpreview-window. the preview-window and the printfuntion are nearly implemented and the only problem is that we cant make an image of the JLayerdPane's content.
    maybe you have an idea or codesamples...
    thanks a lot in advance!!
    george

    1. Getting any JComponent to render onto a buffered image isn't a problem -- just call paint, passing it a graphics object backed by that buffered image.
    2. Writing an image to a file isn't a problem: use javax.imageio.ImageIO.
    Some code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Ex {
        public static void main(String[] args) {
            JFrame f = new JFrame("Ex");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final JLayeredPane pane = new JLayeredPane();
            Border b = BorderFactory.createEtchedBorder();
            pane.add(createLabel("DEFAULT_LAYER", b, 00, 10), JLayeredPane.DEFAULT_LAYER);
            pane.add(createLabel("PALETTE_LAYER", b, 40, 20), JLayeredPane.PALETTE_LAYER);
            pane.add(createLabel("MODAL_LAYER", b, 80, 30), JLayeredPane.MODAL_LAYER);
            pane.add(createLabel("POPUP_LAYER", b, 120, 40), JLayeredPane.POPUP_LAYER);
            pane.add(createLabel("DRAG_LAYER", b, 160, 50), JLayeredPane.DRAG_LAYER);
            f.getContentPane().add(pane);
            JPanel south = new JPanel();
            JButton btn = new JButton("save");
            btn.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    save(pane);
            south.add(btn);
            f.getContentPane().add(south, BorderLayout.SOUTH);
            f.setSize(400,300);
            f.show();
        static JLabel createLabel(String text, Border b, int x, int y) {
            JLabel label = new JLabel(text);
            label.setOpaque(true);
            label.setBackground(Color.WHITE);
            label.setBorder(b);
            label.setBounds(x,y, 100,20);
            return label;
        static void save(JComponent comp) {
            int w = comp.getWidth(), h = comp.getHeight();
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setPaint(Color.MAGENTA);
            g2.fillRect(0,0,w,h);
            comp.paint(g2);
            g2.dispose();
            try {
                ImageIO.write(image, "jpeg", new File("image.jpeg"));
            } catch(IOException e) {
                e.printStackTrace();
    }Why does the saved image have a magenta background? JLayerPane, by default, is non-opaque. You can set it to be opaque and choose its background color, as you like.

  • JScrollPane Clip Bounds Incorrect

    I have a JScrollPane that contains a JLayeredPane. The JLayeredPane contains a variable set of objects (custom JComponents). These custom components can change their size based on user action.
    My problem is that the clipping rectangle of the graphics context in the paint method of the JLayeredPane is incorrect. It only represents the initial size of the screen. For example, my initial application frame is 200x200. The JLayeredPane's size is 400x400. This (properly) results in horizontal and vertical scroll bars. The problem is that when scrolling, the non-visible portion of the component never gets repainted. In looking at the clip bounds for the graphics, it shows that it is repainting only the initially visible portion of the custom object.
    This problem disappears if I first resize the main frame to get rid of the scroll bars. Once this is done, I can set the size of the window back to what it previously was and scroll without any painting problems. Does something magical happen when the scroll bar disappears? I've tried a number of variations on doLayout(), revalidate(), repaint(), but with no luck.
    Thanks for the input,
    Tom

    I've been able to pinpoint (and fix) the problem of the clipping bounds not being properly set. My JScrollPane contained a JLayeredPane subclass that had overridden the getSize() and getPreferredSize() methods. The size of my JLayeredPane changes based on user action. Both methods were always returning the same size (though that size was changing).
    I'm not exactly why this fixes things, but I changed my getPreferredSize() method to return a dimension exactly 1 pixel greater in both width and height than the dimension returned by getSize(). After doing this, everything paints properly. Does anyone know why this would work?
    I wonder if the JScrollPane's layout manager sees that the sizes are different and makes sure things are updated properly. I tried making the preferred size smaller than the getSize(), but I lost my scrollbars entirely.
    Tom

  • JLayeredPane help

    I need to create a GUI with a JPanel showing a plot, and on the bottom left corner I'd like to have a JTable showing some data. The LayeredPane would be real nice to do that. I tried but the objects in the LayeredPane did not resize with the window. So, my question is: is there any way to fix the objects in the LayeredPane so they resize with the window much like if it was a BorderLayout or so?
    Here is a little test I did without the plot; but it exemplifies real well what I mean:
    public class TestLayersMain extends javax.swing.JFrame {
        /** Creates new form TestLayersMain */
        public TestLayersMain() {
            initComponents();
        private void initComponents() {
            jPanel2 = new javax.swing.JPanel();
            jLayeredPane2 = new javax.swing.JLayeredPane();
            jScrollPane3 = new javax.swing.JScrollPane();
            jTextArea2 = new javax.swing.JTextArea();
            jScrollPane4 = new javax.swing.JScrollPane();
            jTable2 = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jPanel2.setLayout(new java.awt.BorderLayout());
            jScrollPane3.setViewportView(jTextArea2);
            jScrollPane3.setBounds(10, 10, 430, 280);
            jLayeredPane2.add(jScrollPane3, javax.swing.JLayeredPane.DEFAULT_LAYER);
            jTable2.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane4.setViewportView(jTable2);
            jScrollPane4.setBounds(10, 190, 200, 100);
            jLayeredPane2.add(jScrollPane4, javax.swing.JLayeredPane.POPUP_LAYER);
            jPanel2.add(jLayeredPane2, java.awt.BorderLayout.CENTER);
            getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
            pack();
       public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestLayersMain().setVisible(true);
        private javax.swing.JLayeredPane jLayeredPane2;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JScrollPane jScrollPane3;
        private javax.swing.JScrollPane jScrollPane4;
        private javax.swing.JTable jTable2;
        private javax.swing.JTextArea jTextArea2;
        // End of variables declaration                  
    }Thanks in advance!

    [url http://java.sun.com/docs/books/tutorial/uiswing/events/componentlistener.html]How to Write a Component Listener
    Try adding a ComponentListener to the LayeredPane and handle componentResized() method and then resize your components manually.

  • JTable have no resize cursor under a JLayeredPane

    Hi,
    i have over my JScrollPane a JLayeredPane to show infotext.
    When the JLayeredPane is over the JScrollpane you can resize the column but the JTable show no resize Cursor.
    Does anybody know why?
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    public class NoResizeCursorDemo extends JFrame
      public NoResizeCursorDemo()
        JTable table = new JTable( new DefaultTableModel( new String[]{ "aaa", "bbb" }, 10 ) );
        JScrollPane scrollPane = new JScrollPane( table );
        InfoLayer layer = new InfoLayer( scrollPane );
        add( layer );
      public static void main( String[] args )
        NoResizeCursorDemo frame = new NoResizeCursorDemo();
        frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
      class InfoLayer extends JLayeredPane
        private final JComponent wrappedComponent;
        public InfoLayer( JComponent wrappedComponent )
          this.wrappedComponent = wrappedComponent;
          setLayout( null );
          add( wrappedComponent, JLayeredPane.DEFAULT_LAYER );
          setInfoText();
        private void setInfoText()
          add( new JLabel( "Info......" ), JLayeredPane.POPUP_LAYER );
          revalidate();
        @Override
        public Dimension getPreferredSize()
          return wrappedComponent.getPreferredSize();
        @Override
        public void doLayout()
          Dimension size = getSize();
          Component layers[] = getComponents();
          for ( Component layer : layers )
            layer.setBounds( 0, 0, size.width, size.height );
    }Thanks

    Hi,
    I had almost the same problem with JTable and JSplitPane, the components worked fine, but cursor did not change when require.
    I already had in place mouse events dispatching in my top layer. It passed all events to the components underneath (see example in [Glass Pane Demo Project|http://java.sun.com/docs/books/tutorial/uiswing/examples/components/GlassPaneDemoProject/src/components/GlassPaneDemo.java]; in my case the listener was the content panel of the top layer).
    And now here is the trick around the cursor. Within the custom dispatch method I've called the following:
    this.setCursor(comp.getCursor());
    where "this" is the content panel of the layer and comp is the component where mouse event passed to.
    Hope that helps!
    Regards,
    Sergey

  • How to setBounds for components inside JLayeredPane

    Hello,
    Please help me find a solution to the following: I'm trying to construct a JPanel inside which there is a JLayeredPane. In the JLayeredPane there is (among others) a JScrollPane with a view onto a table. When the top panel resizes, I need to track the new size of the JLayeredPane and setBounds for the components inside the JLayeredPane for them to render correctly filling out the entire space available. I don't want to setBounds to a high threshold because on one of the layers there is a JScrollPane which needs to precisely fill the entire area of JLayeredPane to show the scroll controlls in their correct position. Here is a much simplified sample code:
    jLayeredPane.addComponentListener(new ComponentAdapter() {
    public void componentResized(ComponentEvent e) {
    setScrollPaneBounds();
    public void componentShown(ComponentEvent e) {
    setScrollPaneBounds();
    private void setScrollPaneBounds() {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    Dimension size = jLayeredPane.getSize();
    myJScrollPane.setBounds(0, 0, size.width, size.height);
    The problem in the above code is that the behaviour is random, when I resize the frame the myJScrollPane.setBounds sometimes sets the bounds, and other times it does not. Also I see the rendering of the JScrollPane 'leading' other changes higher up in the component hierarchy.
    Please help me solve these problems.
    Thanks.

    Thanks for suggestion, but that doesn't change anything. The biggest problem is the order of events. In the JFrame there is some complex layout with nested JSplitPane (2) and when I resize the window this little JLayeredPane seems to redraw FIRST and should be one of the last as it is deep in the component tree. When I take away the ComponentListener I have installed onto the JScrollPane, then event sequence is all good, but the setBounds on the JScrollPane is never called and the sizing becomes incorrect.
    Marcin.
    - CryptoHeaven Team

  • Avoid repaint in JLayeredPane components

    I have a program including a JLayeredPane that contains a JComponent and a JPanel. Both components are set on different layers of the JLayeredPane.
    I use the JPanel for painting, so I want to avoid unnecessary repaints if I can. The problem is that when I resize the JComponent using setBounds(), the JLayeredPane performs a repaint, and consequently, the JPanel too.
    How can I avoid the repaint propagation through all the JLayeredPane? I tried to use setIgnoreRepaint(true), but it didn't seem to work.
    If you need to see some code, just ask. Thanks in advanced. :)

    Sorry for not sending my SSCCE before; there was mealtime here. Thanks for your code anyway, I'll have a look now to see if I get any idea.
    This is my code. What I'd like to avoid it's to display the setence "inner painted" (it means that the paintComponent() method of the innerPanel has been triggered):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import javax.swing.BoxLayout;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.event.MouseInputListener;
    public class SelectionFrame implements MouseInputListener {
        private final static int CURSOR_WIDTH = 2;
        private final static int ALPHA_SELECTION_INT = 20;
        private JFrame frame;
        private JScrollPane scrollPane;
        private JPanel innerPanel;
        private JPanel outerPanel;
        private JComponent transComponent;
        private JLayeredPane layeredPane;
        private boolean cursorEnabled;
        private boolean selectionEnabled;
        private Color bgColor;
        public SelectionFrame() {
            cursorEnabled = true;
            selectionEnabled = true;
            frame = new JFrame();
            frame.setTitle("Adilo Selection");
            frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),
                    BoxLayout.X_AXIS));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setMinimumSize(new Dimension(400, 300));
            bgColor = Color.CYAN;
            innerPanel = new JPanel()  {
                @Override
                protected void paintComponent(Graphics g)   {
                    System.out.println("inner painted");
            innerPanel.setBackground(bgColor);
            outerPanel = new JPanel();
            outerPanel.setBackground(Color.BLUE);
            outerPanel.setBounds(0, frame.getHeight() / 3, frame.getWidth(), frame.getHeight() / 3);
            transComponent = new JComponent()
                @Override
                public void paintComponent(Graphics g)
                    Color selectionColor = new Color(255 - bgColor.getRed(),
                            255 - bgColor.getGreen(),
                            255 - bgColor.getBlue(),
                            ALPHA_SELECTION_INT);
                    g.setColor(selectionColor);
                    g.fillRect(0, 0, getSize().width, getSize().height);
            layeredPane = new JLayeredPane();
            layeredPane.add(innerPanel, new Integer(1));
            layeredPane.add(outerPanel, new Integer(2));
            layeredPane.add(transComponent, new Integer(3));
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(layeredPane);
            innerPanel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
            innerPanel.addMouseListener(this);
            innerPanel.addMouseMotionListener(this);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
        private int initXPos;
        public void mousePressed(MouseEvent e) {
            initXPos = e.getX();
            if(cursorEnabled)    {
                transComponent.setBounds(e.getX(), 0, CURSOR_WIDTH, frame.getHeight());
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mouseDragged(MouseEvent e) {
            int xPos = e.getX();
            if(selectionEnabled)    {
                if(xPos > initXPos) {
                    transComponent.setBounds(initXPos, 0, xPos - initXPos, frame.getHeight());
                else    {
                    transComponent.setBounds(xPos, 0, initXPos - xPos, frame.getHeight());
        public void mouseMoved(MouseEvent e) {
        public void mouseClicked(MouseEvent e) {
        public static void main(String[] args) {
            new SelectionFrame();
    }

  • Set Background image to JScrollPane ---  Need Help!!

    Hi all;
    How can i set a Background Image to this JScrollPane?
    JLabel imageLabel;
    JScrollPane jsp = new JScrollPane(imageLabel);
    Pls need your sugessions...
    Thanking in advance
    Madumm

    I included a complete code listing of a functional example. The main problem with wha tI shared earlier was that I did it quickly in Groovy, where everything is an object. When I called layeredPane.add(xxx, 4) - the number 4 was an object - whereas in Java it is not - this called the wrong function so that the label would not appear... ok - here is the code... run this with your own image and then modify it to do what you need...
    import java.awt.Dimension;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import javax.swing.JScrollPane;
    public class BackgroundImageExample {
        public static void main(String[] args) {
            try {
                //Load Image
                String filename = "/home/dlpinto/Desktop/Screenshot.png";
                BufferedImage image = ImageIO.read(new File(filename));
                //Create Image Label
                JLabel label = new JLabel(new ImageIcon(image));
                label.setBounds(0, 0, image.getWidth(), image.getHeight());
                //Create Layered Pane
                JLayeredPane layeredPane = new JLayeredPane();
                layeredPane.setLayout(null);
                layeredPane.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
                //Create Desired Components
                JLabel messageLabel = new JLabel("Hello World");
                messageLabel.setOpaque(true);
                messageLabel.setBounds(50, 50, 100, 100);
                //Populate Layered Pane
                layeredPane.add(label, new Integer(JLayeredPane.DEFAULT_LAYER-1));
                layeredPane.add(messageLabel, JLayeredPane.DEFAULT_LAYER);
                //Create ScrollPane
                JScrollPane sp = new JScrollPane(layeredPane);
                //Create & Display Frame
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(800, 600);
                frame.add(sp);
                frame.setVisible(true);
                System.out.println(layeredPane.getLayer(messageLabel));
                System.out.println(layeredPane.getLayer(label));
            } catch (Exception e) {
                e.printStackTrace();
    }

  • Customize JScrollPane

    Hello everybody,
    Iam having a JScrollPane which contains a layeredpane.
    There is a JPanel in the JLayeredPane.
    I have drawn some java2d shapes like rectangle, ellipse in the JPanel.
    I have written a code for moving the shapes when the arrow keys are pressed.
    But the problem is that when i press down arrow key, the vertical scrollbar also moves along with the shape.
    I dont want the scroll bar to move.I only want to move the shapes.
    So i hv written my own CustomJscrollPane class extending from JScrollPane.
    I wrote my own CustomUI classe extending BasicSrollPaneUI and set this CustomUI class in setUI method of CustomJScrollPane.
    I had overriden the method installKeyBoardAction and provided blank mplementation.
    But still the scroll bar comes down with the down arrow key.
    I dont want that.
    How can this be done.Please help
    Regards
    Satish

    Try calling:
    setAutoscrolls(false);
    in the component where the images are being drawn. Let us know if that works.

  • JScrollPane + Events

    Hello everybody,
    Iam having a JScrollPane which contains a layeredpane.
    There is a JPanel in the JLayeredPane.
    I have drawn some java2d shapes like rectangle, ellipse in the JPanel.
    I have written a code for moving the shapes when the arrow keys are pressed.
    But the problem is that when i press down arrow key, the vertical scrollbar also moves along with the shape.
    I dont want the scroll bar to move.I only want to move the shapes.
    How can this be done.Please help
    Regards
    Satish

    hi,
    maybe i missunderstand you, but that is exactly what JScrollPane has to do. If you press an arrow the slider moves in the direction of the arrow and the slider length gives you some information about the ratio scrollPane view/component size. If you don't want the slider to move you must implement your own "scrollPane".
    Gernot

Maybe you are looking for

  • Fields Missing in the data source

    Hello Friends ,                       I have to Append structures in my data source , and there are few fields under each append , the fields existing in Dev are missing in QA under one of Append strcuture's in QA. I see the fields when I double clic

  • INSTALL SSD IN MACBOOK PRO LATE 2011

    I have a late 2011 MacBook Pro 15". I would like to upgrade the 5400rpm hardrive for a fast SSD. Is it easy to do yourself or should I get this done in a store?

  • ITunes says it cannot back up my phone to my computer

    because there is not enough free space. My HD says it has 209GB Free Space. Whassup with that?

  • Reservation against maintenance order and MMBE

    Dear Experts, As per my knowledge the reservation which are created through maintenance order will be reflected in MMBE as we save the order, without specific to status of maintenance order.But here in my client it is not happening, instead of this i

  • User Profiles Synchronization Error Event id 5553 - Every hour

    I am getting these 2 events logged in the event viewer when the user profile synch is attempted:  First event: Second Event: (although we don't always get this error with the one above) failure trying to synch site 6c02f82c-2029-4ca0-990b-d14786b95d8