How to scroll a JPanel?

I have class, which extends JPanel, in which I override
the paintComponent(Graphics g) method
I am drawing a graph and, depending on the input values, the graph can be wider than the JPanel. I would like to be able to add a scroll bar so the whole of the graph can be viewed.
I have tried to make the JPanel implement scrollable
and I have tried putting the JPanel within a JScrollpane
but neithor work.
please help!
Simon

You should be able to add the JPanel to the JScrollPane by doing the following (setting the scrollbars as required)
// create a panel to hols the scrollpane
JPanel aPanel = new JPanel();
// create the scrollpane with your graph in it = yourPanel
// disable the vertical scrollbar and enable the hoziontal
JScrollPane aScrollPane = new JScrollPane(yourGraph, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// set the scrollpane to the same size as the panel
aScrollPane.setSize(aPanel.getSize());
// add the scrollpane to the panel
aPanel.add(aScrollPane);
// refresh the layout
aScrollPane.doLayout();
Hope this helps - I had the same problem a couple of days ago!

Similar Messages

  • How to make a JPanel selectable

    When extending a JPanel and overriding the paintComponent() method the custom JPanel can not be selected so that it gets for example KeyEvents.
    But if I make the new Class extend a JButton it gets of course selected and able to receive for example KeyEvents.
    My question is therefore; what does the JButton implement that a JPanel doesn’t so that a JButton gets selectable? Or in other words; how to make a JPanel selectable?
    Aleksander.

    Try this extended code. Only the first panel added can get the Focus.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test extends JFrame
      public Test()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel(new BorderLayout());
        JPanel panel2 = new JPanel(new BorderLayout());
        ImagePanel imgPanel = new ImagePanel();
        panel1.setFocusable(true);
        panel2.setFocusable(true);
        panel1.setPreferredSize(new Dimension(0, 50));
        panel2.setPreferredSize(new Dimension(0, 50));
        panel1.setBorder(BorderFactory.createLineBorder(Color.RED,     4));
        panel2.setBorder(BorderFactory.createLineBorder(Color.CYAN,    4));
        imgPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
        panel1.add(new JLabel("Panel 1"), BorderLayout.CENTER);
        panel2.add(new JLabel("Panel 2"), BorderLayout.CENTER);
        getContentPane().add(panel1, BorderLayout.NORTH);
        getContentPane().add(panel2, BorderLayout.SOUTH);
        getContentPane().add(imgPanel, BorderLayout.CENTER);   
        pack();
        panel1.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel1");}});
        panel2.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel2");}});
      public static void main(String[] args){new Test().setVisible(true);}
    class ImagePanel extends JPanel
      Image img;
      public ImagePanel()
        setFocusable(true);
        setPreferredSize(new Dimension(400,300));
        try{img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));}
        catch(Exception e){/*handled in paintComponent()*/}
        addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            System.out.println("ImagePanel");}});
      public void paintComponent(Graphics g)
        if(img != null)
          g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
        else
          g.drawString("This space for rent",50,50);
    }

  • How to dynamically resize JPanel at runtime??

    Hello Sir:
    I met a problem, I need to resize a small JPanel called panel within a main Control JPanel (with null Layout) if I click the mouse then I can Drag and Resize this small JPanel Border to the size I need at runtime, I know I can use panel.setSize() or panel.setPreferredSize() methods at design time,
    But I have no idea how to do it even I search this famous fourm,
    How to dynamically resize JPanel at runtime??
    Can any guru throw some light or good example??
    Thanks

    Why are you using a null layout? Wouldn't having a layout manager help you in this situation?

  • How to place a JPanel at the center of another JPanel?

    Can anyone tell me how to place a JPanel inside another JPanel? The first JPanel consists of three JPanels each consisting of a label&textfield and are placed using BoxLayout. The second JPanel is a big blank screen. So, i would like to put the first JPanel at the center of second JPanel(horizontally & vertically). The problem is that i don't have any other component. So,if i try to use FlowLayout, i am able to put it at the center(horizontally, not vertically) only on the top edge. I tried to use BoxLayout. But, i couldn't(as i don't have any other elements). I tried to create some blank elements. But, they are messing up the elements of my JPanel. Any cluesssssssss??????????

    import java.awt.*;
    import javax.swing.*;
    public class CenteredLayout
        private JPanel getPanel()
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            JPanel p = new JPanel(gridbag);
            addComponents(new JLabel("label 1"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 2"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 3"), new JTextField(8), p, gbc);
            JPanel panel = new JPanel(gridbag);
            panel.setBackground(Color.pink);
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.insets = new Insets(0,0,0,0);
            panel.add(p, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            c.add(c2, gbc);
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new CenteredLayout().getPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • I turned some mode where i have to double tap everything and i cant figure out how to scroll, I turned some mode where i have to double tap everything and i cant figure out how to scroll

    I need  help I turned some mode on that makes me duoble tap whatever i want to open it say whatever it is i am touching and I cant figure out how to scroll to turn it off

    It is an accessibility setting and is covered in the manual:
    iPhone User Guide (For iOS 5.1 Software)

  • How to scroll text.

    I want to scroll text on a touch device. But i have no idea how to do this. I read up on adobe that a mouse event will work, but a touch point could also be used, then they lost me talking about item rendering.
    Can someone help me figure out how to scroll text on a touch enabled device?

    You don't want to use just a while loop because once you get into the loop, it'll stay in there until you break out. Nothing else will be allowed to process. You'll want to use a Thread with a while loop inside.
    I don't know if thise code will work. just wrote it off the top of my head. But something like that. You'll probably have to put extra white space in at the beginning of your scrollText so it starts on the far right side.
    class ScrollArea extends JTextField implements Runnable
    private Thread myThread;
    private int i;
         public ScrollArea()
              myThread = new Thread(this);
              int scrolDist = textToScroll.length() + this.getColumns();
              i = 0;
         public void Run()
              int scrolDist = textToScroll.length() + this.getColumns();
              while(true)
                    if(i == scrolDist)
                         i = 0;
                    int scrolDist = textToScroll.length() + this.getColumns();
                    this.setText(textToScroll.substring(i, scrolDist)
                    i++;
         }

  • How to scroll presenters notes during presentation?

    I have some slides with quite a lot of notes. How do I scroll the presenters notes during a presentation when I am using the Presenter Display? I can see the notes, but they are too long to show in the window. I can't figure out how to scroll the notes to read the rest of the notes.
    Many thanks,
    Darren

    Is it bad form to answer my own question?
    I finally found the answer in the User Guide:
    "To scroll presenter notes up or down, press the U or D key."

  • How to scroll the contents of the table without scrolling tab/colmn headers

    how to scroll the contents of the table without scrolling table and column headers in WebDynPro.
    I have set the table properties as
    footer visible = false;
    Visible row count = -1;
    and have put the table into scroll container with some specified height.
    I dont want to use the footer as I have used many tables in the container in same row and with same <b>Data node</b>.
    I have used many tables in same row and with same context node to differentiate it with two different colors for that specific columns.
    I am using <b>NW 04</b> and not NW04s.
    Please help me regarding this.

    To print the whole data of your table you have to do it yourself. The showPrintablePageBehavior only print what you actually see on the page. It does not traverse the data.
    The normal way to handle tis is to use a report generator (like itext, jasper report, fop ...).
    Timo

  • How to scroll i presenterwiev

    Im trying to figure out how to scroll my presenternotes (the are very long) i presenter view by Im unable to succed.

    Welcome to the forums, stefanbje!
    While in presenter view in Keynote 3, Shift-D will scroll down the notes a line at a time (d, without shift, will scroll down a full "page"). Likewise, Shift-U will scroll up a line (and u, without shift, will scroll up a full page).
    Under the Help menu in Keynote, there is a handy Keyboard Shortcuts guide that covers a wide variety of areas, including shortcuts usable during presentations.

  • How to scroll datagrid to highlight records?

    I have used
    styleFunction(data:Object,col:AdvancedDataGridColumn) to highlight
    one record in a datagrid. My question is how to scroll to this
    highlighted record using action script?
    Thanks

    For now you can enable scroll bars so that they are always visible, and thus able to grabbed using your pen. Check this under System Preferences > Personal > General > Show Scroll Bars > Always.
    The default setting is "Automatically based on Input Device" which makes me think that perhaps Wacom needs to do something in order for OS X Lion to recognize that if you are using a pen, the scrollbars will appear automatically. That's my hope at least!

  • In adobe muse when we have more thumbnail in slide show how can scroll them?

    In adobe muse when we have more thumbnail in slide show how can scroll them?

    Hi,
    Can you please be a little more specific regarding your issue?   perhaps a screenshot explaining what you are trying to do using muse would be really helpful .
    Regards,
    Rohit Nair

  • How to make a JPanel with a GridLayout scroll

    I am using a JPanel to hold around 100 buttons. The JPanel is using GridLayout to organise these buttons in rows of 3 buttons per row. i.e. buttonPanel.setLayout(new GridLayout(33,3)); As there are so many buttons they obviously don't all fit in the viewable area of the screen. To get around this I am trying to use a JScrollPane on the buttonPanel to make it scroll but I can't get it to work. I have tried both creating a seperate JScrollPane object and adding the buttonPanel to it
    JScrollPane buttonScroll = new JScrollPane();
    buttonPanel.setLayout(new GridLayout(33,3));
    buttonPanel.setPreferredSize(new Dimension(380,400));
    buttonPanel.setMaximumSize(new Dimension(380,400));
    buttonScroll.add(buttonPanel);and also embeding everything into a new JPanel like:
    buttonHolder.add(new JScrollPane(buttonPanel),BorderLayout.CENTER);Neither way works. Any ideas. I've read about view port but not exactly sure what this is or if this will fix my problem.
    Help urgently required.

    Fixed layouts have their perils.
    We need to figure the size for the buttonScroll. Here's one way to approach this:
        topPanel
            messagePanel 400 x 400    buttonScroll unknown size
        inputPanel
            previewPane  600 x  80    sendButton   icon size (55 x 68, duke)
        For a fixed layout, find the size required for the buttonScroll by commenting out the
        two lines that add the buttons to buttonPanel and calling pack on the frame:
        frame size (pack w/no buttons)     743 x 570
        topPanel size                      735 x 400
        therefore, required size for
            buttonScroll is                335 x 400     (735 - 400, 400)
    After adding the buttons back in the final sizes become
    C:\jexp>java GUI
    frame width = 763       height = 570
    topPanel width = 755    height = 400I substituted a Duke image for your sendIcon so the sizes may differ but this should get you started...
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.Container.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class GUI extends JFrame
        Icon sendIcon = new ImageIcon(getClass().getResource("images/T4.gif"));
        Icon deleteIcon = new ImageIcon(getClass().getResource("images/T6.gif"));
        JButton sendButton = new JButton("Send",sendIcon);
        JButton deleteButton = new JButton("Delete",deleteIcon);
        JLabel statusBar = new JLabel();
        JMenu optionsMenu = new JMenu("Options");
        JMenu helpMenu = new JMenu("Help");
        JMenuBar menuBar = new JMenuBar();
        JMenuItem connectMenuItem = new JMenuItem("Connect");
        JMenuItem disconnectMenuItem = new JMenuItem("Disconnect");
        JMenuItem exitMenuItem = new JMenuItem("Exit");
        JMenuItem helpMenuItem = new JMenuItem("Online Help");
        JMenuItem aboutMenuItem = new JMenuItem("About");
        JPanel buttonPanel = new JPanel();
        JPanel inputPanel = new JPanel();
        JPanel messagePanel = new JPanel();
        JPanel topPanel = new JPanel();
        JPanel buttonHolder = new JPanel();
        JScrollPane buttonScroll = new JScrollPane(buttonPanel,20,30);
        JTextPane messageArea = new JTextPane();
        JTextPane previewPane = new JTextPane();
        public GUI()
            super("Chat Program");
            String userName = "user";
            statusBar.setText("Connected: " + userName);
            menuBar.add(optionsMenu);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            optionsMenu.add(connectMenuItem);
            optionsMenu.add(disconnectMenuItem);
            optionsMenu.add(exitMenuItem);
            helpMenu.add(helpMenuItem);
            helpMenu.add(aboutMenuItem);
            buttonPanel.setLayout(new GridLayout(0,3));
            for(int i = 0; i < 100; i++)
                buttonPanel.add(new JButton("Button " + (i + 1)));
            messageArea.setEditable(false);
            previewPane.setEditable(false);
            previewPane.setPreferredSize(new Dimension(600,80));
            previewPane.setMaximumSize(new Dimension(600,80));
            messagePanel.setLayout(new BorderLayout(10,10));
            messagePanel.add(new JScrollPane(messageArea),BorderLayout.CENTER);
            messagePanel.setPreferredSize(new Dimension(400,400));
            messagePanel.setMaximumSize(new Dimension(400,400));
            // w = 735 - 400, h = 400
            // does not take into account the width of the vertical scrollBar
            buttonScroll.setPreferredSize(new Dimension(335,400));       // *
            Box box = new Box(BoxLayout.X_AXIS);
            box.add(new JScrollPane(previewPane));
            box.add(sendButton);
            inputPanel.add(box,BorderLayout.CENTER);
            statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
            topPanel.setLayout(new BorderLayout(10,10));
            topPanel.add(messagePanel, BorderLayout.WEST);
            topPanel.add(buttonScroll, BorderLayout.EAST);
            Container content = getContentPane();
            content.add(topPanel,   BorderLayout.NORTH);
            content.add(inputPanel, BorderLayout.CENTER);
            content.add(statusBar,  BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
    //        setSize(?,?);       // 763, 570 (now we know)
            setLocation(200,200);
            setVisible(true);
            // collect size information
            System.out.println("frame width = " + getWidth() + "\t" +
                               "height = " + getHeight() + "\n" +
                               "topPanel width = " + topPanel.getWidth() + "\t" +
                               "height = " + topPanel.getHeight());
        public static void main(String[] args)
            new GUI();
    }

  • How does one scroll a JPanel?

    I have a drawing area in my GUI which is a JPanel on which I draw graphics. I have added scrollbars but I cannot get the JPanel to scroll. I tried setting the size (setSize) of this JPanel much larger than it appears within its JFrame but no go.
    Any suggestions?

    You have to put your JPanel inside of a JScollPane. For example...
    JPanel jp = new JPanel();
    // add your stuff to the JPanel
    JScrollPane sp = new JScrollPane(jp);
    Alternatively you can call setViewportView on the JScrollPane...
    sp.setViewportView(jp);
    Hope this helps.

  • How to prevent a JPanel to grow ?

    Hello,
    I've included a JPanel in a JScrollPane.
    When I size down the whole thing, scroll bars appear. Nice.
    But when I size up, the JPanel grows and its content (buttons) is stretched.
    I would like the JPanel to always keep the same size, and some grey area to appear around it when the JScrollPane is sized up. I've tried with :
    panel.setMaximumSize (panel.getPreferredSize ());
    panel.setMinimumSize (panel.getPreferredSize ());
    But it does nothing...
    Do you know how to do ?
    Matthieu

    Subclass the JPanel and return your own fixed preferredSize always.

  • Scrolling a JPanel

    Hi, I'm relatively new to Java and I'm having trouble grasping what I think is a simple concept. I am writing an app which uses a JScrollPane to scroll over a JPanel with about 600 vertically stacked JTextFields and labels on it (its a big multiple choice test). Scrolling works fine with the mouse and pgup/down keys. The problem is that when I traverse the text fields with the tab key, the JPanel doesn't scroll. So, ok, that's kind of expected. But I'm really not sure how to implement this behavior. I read the ScrollPanel tutorial and looked at some of the demo code.
    So as far as I can tell, each textfield needs an event listener which will tell me what keys were pressed: I need to determine if I am scrolling up or down (i.e. shift+tab or just tab is pressed). So I wait for that event and then I need to somehow calculate the proper visible Rectangle and call the scrollRectToVisible method on my JPanel, which will send a message to its parent- the scroll panel which will move the visible rectangle for me.
    I would really appreciate some sample code snippets to help me along, or maybe I am barking up the wrong tree completely?
    Thanks very much,
    -Jonathan

    So as far as I can tell, each textfield needs an
    event listener which will tell me what keys were
    pressed: I need to determine if I am scrolling up orNo. Use a FocusListener. And btw you can just use 1 focus listener for all your elements if you are clever about it
    calculate the proper visible Rectangle and call thesee Component.getBounds()
    scrollRectToVisible method on my JPanel, which will
    send a message to its parent- the scroll panel which
    will move the visible rectangle for me.Yes

Maybe you are looking for

  • NI DAQmx 8.3 and CPU usage

    I have similar problem as described on page http://forums.ni.com/ni/board/message?board.id=250&message.id=23831 but have solution and some reflections. first of all, about system system use 2x PCI-6143 and take data from 16 channels with maximum rate

  • Apple's DRM

    when you download a tv show from iTunes you, you can't burn a disc. i have a client who would like to encode their video podcast the same way. any thoughts on how to do this?

  • Restore archivelogs from backupset

    STEP-1 RMAN> backup archivelog all; Starting backup at 13-MAR-13 current log archived using channel ORA_DISK_1 channel ORA_DISK_1: starting archive log backupset channel ORA_DISK_1: specifying archive log(s) in backup set input archive log thread=1 s

  • CS3 mediacore issue. (Editing modes/plugins)

    Hi, I've been having an unresolved issue the past couple days. I can't seem to figure out what's wrong. I looked up my problem on different boards but I haven't found one similar to mine. So I own a macbook pro, running on a Mac OS X version 10.6.3,

  • Other solution instead of RMI

    dear members! with RMI the run time goes slow, so can u suggest any other method in which i don't have to run the webserver within proxy and communication can be handled. to be more specific is there any other way of doing " http tunneling " . withou