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

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&#8217;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 make text columns with adobe muse

    Hi,How to make text columns with adobe muse (like InDesign)?

    Multiple columns can be acheived with CSS - http://www.w3schools.com/css/css3_multiple_columns.asp
    div
    -moz-column-count:3; /* Firefox */
    -webkit-column-count:3; /* Safari and Chrome */
    column-count:3;
    I'm surprised that Muse does not support text columns yet, but perhaps the custom CSS can be added in style tags on page properties. Haven't tried it, but don't see why it wouldn't work.

  • How to make turning page with ibooks author?

    How to make turning page with ibooks author?

    This question has been answered on this thread
    https://discussions.apple.com/message/17981772#17981772#17981772
    Best regards.
    Alex

  • How to make this work with Firefox, HELP!

    Downloading for Real-player, after watching the full movie, I click download and it has to reread the movie from the internet. When using explorer, after downloading the movie, it reads it from memory, which makes it a fast download. How to make this work with Firefox, I like not to use Microsoft products, and I really like Firefox 7.0.1!!!! HELP!

    -> click '''Firefox''' button and click '''Options''' (OR File Menu -> Options)
    * Advanced panel -> Network tab
    * place Checkmark on '''Override Automatic Cache Management''' -> under '''Limit Cache''' specify a large size of space
    * Remove Checkmark from '''Tell me when websites asks to store data for offline use'''
    * click OK on Options window
    * Restart Firefox
    Check and tell if ts working.

  • How to make email link with a button with AC2 in flash cs3?

    How to make email link with a button with AC2 in flash cs3?
    I wrote this, but it does not work:
    btn_emailinfo.on (release) {
    getURL("mailto:"[email protected]");
    }

    I am guessing you put that on a frame?
    If so, the syntax is as follows:
    btn_emailinfo.onRelease = function(){
    getURL("mailto:[email protected]");
    Though, if you are placing it directly on the button itself,
    the syntax is:
    on(release){
    getURL("mailto:[email protected]");
    }

  • I reset my phone and it now receives calls that were meant for my husband. I know how to fix this with messaging and facetime, but can't seem to find how to make it stop with the calls. Please help.

    I reset my phone and it now receives calls that were meant for my husband. I know how to fix this with messaging and facetime, but can't seem to find how to make it stop with the calls. Please help.

    It may be due to Continuity
    The following quote is from  Connect your iPhone, iPad, and iPod touch using Continuity
    Turn off iPhone cellular calls
    To turn off iPhone Cellular Calls on a device, go to Settings > FaceTime and turn off iPhone Cellular Calls.

  • In JSF, how to make a menu with access control?

    In JSF, how to make a menu with access control?
    The access control can be guided by programming, database or other means if possible?
    Thanks

    I want to make a dvd menu in iMovie because i don't have IDVD and can't find anywhere to download it?
    For making DVDs I would recommend iMovie 06 and iDVD 09 both readily available on Amazon or eBay.  Shop for iLife 06 and iLife 09.
    You can make menus and chapters with any version of iMovie except the latest one. There's nothing wrong with iMovie 11 either but I prefer iMovie 06.
    By using iMovie 06 and iDVD 09 I make DVDs with professional moving menus with very little effort. They look almost as good as Hollywood.

  • How to make slide images with Dreamweaver CS6?

    How to make slide images with Dreamweaver CS6? Please teach me.

    Hello
    in addition to Jon's hint, I'll send you some links to nice sliders (have fun with the different representations ):
    http://sandbox.scriptiny.com/javascript-slideshow/
    http://jquery.malsup.com/cycle/
    http://wowslider.com/best-jquery-slider-crystal-linear-demo.html
    http://www.jcoverflip.com/demo
    http://www.jacksasylum.eu/ContentFlow/
    http://addyosmani.com/blog/jqueryuicoverflow/
    You only need to use the source code to implant these shows there where you want. In my eyes it would be the best that you use first a very new and blank DW file to perform (maybe in LiveView) the one or the other.
    Hans-Günter

  • How to make a JPanel transparent? Not able to do it with setOpaque(false)

    Hi all,
    I am writing a code to play a video and then draw some lines on the video. For that first I am playing the video on a visual component and I am trying to overlap a JPanel for drawing the lines. I am able to overlap the JPanel but I am not able to make it transparent. So I am able to draw lines but not able to see the video. So, I want to make the JPanel transparent so that I can see the video also... I am posting my code below
    import javax.media.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.lang.Math;
    import javax.media.control.FramePositioningControl;
    import javax.media.protocol.*;
    import javax.swing.*;
    class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
         Player player;
         Component vc, cc;
         boolean first = true, loop = false;
         String currentDirectory;
         int mediatime;
         BufferedWriter out;
         FileWriter fos;
         String filename = "";
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         JButton bn = new JButton("DrawLine");
         MPEGPlayer2 (String title)
              super (title);
              addWindowListener(new WindowAdapter ()
                   public void windowClosing (WindowEvent e)
                            dispose ();
                            public void windowClosed (WindowEvent e)
                         if (player != null)
                         player.close ();
                         System.exit (0);
              Menu m = new Menu ("File");
              MenuItem mi = new MenuItem ("Open...");
              mi.addActionListener (this);
              m.add (mi);
              m.addSeparator ();
              CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
              cbmi.addItemListener (this);
              m.add (cbmi);
              m.addSeparator ();
              mi = new MenuItem ("Exit");
              mi.addActionListener (this);
              m.add (mi);
              MenuBar mb = new MenuBar ();
              mb.add (m);
              setMenuBar (mb);
              setSize (500, 500);
              setVisible (true);
         public void actionPerformed (ActionEvent ae)
                        FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
                        fd.setDirectory (currentDirectory);
                        fd.show ();
                        if (fd.getFile () == null)
                        return;
                        currentDirectory = fd.getDirectory ();
                        try
                             player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
                             filename = fd.getFile();
                        catch (Exception exe)
                             System.out.println(exe);
                        if (player == null)
                             System.out.println ("Trouble creating a player.");
                             return;
                        setTitle (fd.getFile ());
                        player.addControllerListener (this);
                        player.prefetch ();
         }// end of action performed
         public void controllerUpdate (ControllerEvent e)
              if (e instanceof EndOfMediaEvent)
                   if (loop)
                        player.setMediaTime (new Time (0));
                        player.start ();
                   return;
              if (e instanceof PrefetchCompleteEvent)
                   player.start ();
                   return;
              if (e instanceof RealizeCompleteEvent)
                   vc = player.getVisualComponent ();
                   if (vc != null)
                        add (vc);
                   cc = player.getControlPanelComponent ();
                   if (cc != null)
                        add (cc, BorderLayout.SOUTH);
                   add(new MyPanel());
                   pack ();
         public void itemStateChanged(ItemEvent ee)
         public static void main (String [] args)
              MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
              System.out.println("111111");
    class MyPanel extends JPanel
         int i=0,j;
         public int xc[]= new int[100];
         public int yc[]= new int[100];
         int a,b,c,d;
         public MyPanel()
              setOpaque(false);
              setBorder(BorderFactory.createLineBorder(Color.black));
              JButton bn = new JButton("DrawLine");
              this.add(bn);
              bn.addActionListener(actionListener);
              setBackground(Color.CYAN);
              addMouseListener(new MouseAdapter()
                             public void mouseClicked(MouseEvent e)
                   saveCoordinates(e.getX(),e.getY());
         ActionListener actionListener = new ActionListener()
              public void actionPerformed(ActionEvent aae)
                        repaint();
         public void saveCoordinates(int x, int y)
                    System.out.println("x-coordinate="+x);
                    System.out.println("y-coordinate="+y);
                    xc=x;
              yc[i]=y;
              System.out.println("i="+i);
              i=i+1;
         public Dimension getPreferredSize()
    return new Dimension(500,500);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
              Graphics2D g2D = (Graphics2D)g;
              //g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
              g2D.setColor(Color.GREEN);
              for (j=0;j<i;j=j+2)
                   g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]);

    camickr wrote:
    "How to Use Layered Panes"
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html
    Add your video component to one layer and your non-opaque panel to another layer.Did you try that with JMF? It does not work for me. As I said, the movie seems to draw itself always on top!

  • How to add a JPanel with label and border line

    hi,
    I want a Jpanel with label and border line like this.Inside it i need to have components.Is there a resuable component to bring this directly??
    Any solution in this regards.???
    Label-----------------------------------------------------------
    | |
    | |
    | |
    | |
    | |
    |________________________________________ |

    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html]How to Use Borders

  • How to make a line with arrow curve around a circle?

    I've got CS6 and Windows 7. Trying to make a line with an arrow on one end curve around a circle. Actually want it to have a 3D look like it was curving around the back side of a globe. How do you do this? Thanks.

    Perhaps you mean something more like this
    similar technique you create the arrow as a straight stroke path with an arrowhead and make it a symbol
    You then make it a symbol
    you than make a vertical rectangle and use the 3D Revolve Effect to make a cylinder
    then you go to map art
    then you choose in the map art to make the geomtery invisible
    then you ma the arrow symbol and adjust the placement and then adjust the rotation of the cylinder to your likeing.
    If you need a video to follow I'll do one later.

  • How to make different events with different colors on calendar, on my new iPad

    how to make events on calendar with different colors ?

    Sergio,
    The color of an event is dictated by the color assinged to the calendar it's on.
    Tap Calendars then tap Edit to either changed the color of an existing calendar or to add a new one.
    Matt

  • How to make Macbook work with closed display?

    I need to make MacBook to be closed (display) most of the time and work with external monitor, keyboard and mouse (actually trackball as I have been hating any type of mice since 1998 and not using it even at work).
    Now I do not like mediocre resolution of small MacBook display and I prefer my 20 inch wide monitor. Also the keyboard is rather for quick work in small areas like restroom rather than comfortable work on big desk (I hate notebook keyboards either as they make me feel claustrophobic and crunching my fingers).
    Considering recent buzz on Mac Mini not living for too long into future I would love to find alternative solution (meaning I do not want computer with display and keyboard in one and I do not have needs of spending few thousand of dollars for big metal case good for feeding and breeding birds I have ergonomics demands, but not higg performnce processing needs.
    So can you tell me how I make Apple notebook being closed (and perhaps squashed by monitor stand) behave like a CPU box?
    Thanks,
    Maciek

    Thnaks, but I am not interested in bluethooth/wireless solution. That minimum of cable to reach CPU does not bother me and I do not buy big monitor to work on my computer from adjacent room. I just need space for more windows and I think Apple did great job having USB Hub on keyboard that allows stringing mouse and keayoboard with one cable to CPU.
    Also I haven't heard of wireless KVM and I use such solution. This is not my only computer as I run home network and two of them in my room are supposed to share keyboard, mouse and monitor. So far I was successful to run this setup, but I need inexpensive plain CPU from Apple to be able to find comfortable solution to work.
    Well I could drop the other computer if Apple managed to provide everything that I need (how about Safari properly working with Citrix client and Remote Desktop to Windows as I do not want Firefox on Apple computer? Only Firefox fixes the problems with this software).

  • How to make JFormattedTextField respond with . (dot) key

    Dear all,
    Currently I have to create a text field for IP Address entry.
    I have used MaskFormatter and JFormattedTextField.
    I have a problem, on how to make my JFormattedTextField responding with dot entry, to move the cursor to the next segment of the IP Address.
    e.g.
    IP Address want to be inputted = 192.168.1.2
    Keyboard to be pressed = [1][9][2][1][6][8][1][.][2]
    Currently, after [1], I have to press my arrow key, or click by using mouse to go for the last segment.
    Can you please help me ?
    Thank you.

    Hi there,
    Thank you for your help. It works. Anyway, I have 1 more question. Do you have any idea, on how can I set the IP Segment size to be fixed ?
    What I mean is, originally, my text field will look like this ---> . . .
    But as I type, the dot can be shifted since it is pushed by the entry value --> 192.168.111.111
    Do you have any idea for this ?

Maybe you are looking for

  • How can I create a Text-Input Field in BexAnalyzer for a Planning Function

    Hello, i want to create a pre calculation(contribution accounting) for Materials in BI-Integrated Planning. These Materials aren't in the master data. So I create a new Info Object for pre calculated materials with only a material-number as key and a

  • UIX: How to add linked view table columns to the Read-only table

    Hi I have two tables T1: ID, STAFF_ID, NOTE T2: STAFF_ID, USERNAME I have created corresponding entity objects (E1, E2), views (V1, V2), association A(E1->E2 as *..1 using STAFF_ID) and viewlink VL(V1->V2 as *..1 using association A). My model in App

  • How to delete photos in Elements 12 Organizer?

    Been using Elements 6 for years.  Bought E12 to go with a new iMac.  I am totally bewildered by 12.  Simple 1 or 2 click things have become procedures. Like deleting pictures from the Organizer... the Delete function is grayed-out in the pull down me

  • User validation for the BSP application

    I wanted a user to access the bsp application. I already have the user names maintained in the database who will be using the application. i am using the application class for my application. where should i do the user validation and how. i know tst

  • SAP B1 2007A PROBLEM

    Dear All I am facing a problem when we add the A/R Invoice after approval when we open the invoice the system show the message "TAX CODE S2 IS MISSING OR OUT OF DATE" after this when we click on add the system show this message "THIS ENTRY ALREADY EX