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

Similar Messages

  • How to make users to select the date from calendar control my making the date field read only in date time control in external list in sharepoint 2010

    How to make users to select the date from calendar control only, by my making the date text field read only (don't want to let users type the date) in date time control in external list in sharepoint 2010. I am looking for a solution which can
    be done through sharepoint desginer / out of the box.
    thanks.

    Congratulate you got the solution by yourself. I am new to a
    WinForms calendar component, I feel so helpless on many problems even I'd read many tutorials. This question on the
    calendar date selection did me a great favor. Cheers.

  • How to make Label in selection screen?

    Hi friends.. can anybody explain how to make labels in selection screens and how to split the selection screen vertically? plz.. Thanks in advance

    Arun kumar,
    Check this program. you can put labels like this.
    REPORT  ZVENKAT_TEST1.
    SELECTION-SCREEN BEGIN OF BLOCK block.
    SELECTION-SCREEN BEGIN OF LINE.
    SELECTION-SCREEN COMMENT 1(15) text1.
    SELECTION-SCREEN POSITION 17.
    PARAMETERS :p_pernr type pa0001-pernr.
    SELECTION-SCREEN POSITION 26.
    SELECTION-SCREEN COMMENT 27(30) text2.
    SELECTION-SCREEN end OF LINE.
    SELECTION-SCREEN end OF BLOCK block .
    at SELECTION-SCREEN OUTPUT.
      text1 = 'Personal number'.
      SELECT SINGLE ename FROM pa0001 INTO text2 WHERE pernr = p_pernr.
    Regards,
    Venkat.O

  • 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 make a dynamic selection screen

    Hi
    I have been searching the SDN for long time, but couldn't find the answer, so therefor a new post.
    I have an internal table with following values:
    VBKD-BSARK_E
    TVKO-VKORG
    By these values I would like to make a new selection-screen whith following:
    Parameters: FIELD1 like VBKD-BSARK_E.
    Parameters: FIELD2 like TVKO-VKORG.
    Next time the internal table can contain
    MARA-MATNR
    TVKO-VKORG
    VBAK-BSTZD
    And the parameters should then be:
    Parameters: FIELD1 like MARA-MATNR.
    Parameters: FIELD2 like TVKO-VKORG.
    Parameters: FIELD3 like VBAK-BSTZD.
    How do I do that -any suggestions?

    Hi,
    This piece of code will design selection screen based on radio button selection:
        SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001 .
        SELECT-OPTIONS :  s_date  FOR  pnpbegps DEFAULT sy-datum  .   
        SELECTION-SCREEN: END OF BLOCK b1.
        SELECTION-SCREEN : BEGIN OF  BLOCK b2 WITH FRAME TITLE text-002.
        PARAMETERS:rb1 RADIOBUTTON GROUP rbf DEFAULT 'X'.
        PARAMETERS:rb2 RADIOBUTTON GROUP rbf .
        SELECTION-SCREEN: END OF BLOCK b2.
        SELECTION-SCREEN BEGIN OF BLOCK b3 WITH FRAME TITLE text-003 .
        SELECTION-SCREEN BEGIN OF LINE.
        SELECTION-SCREEN COMMENT 1(25) text-006 FOR FIELD px_pdf.
        PARAMETERS:  px_pdf AS CHECKBOX USER-COMMAND xxx  .      
        SELECTION-SCREEN END OF LINE.
        SELECTION-SCREEN BEGIN OF LINE.
        SELECTION-SCREEN COMMENT 1(15) text-004 FOR FIELD rb_app.
        PARAMETERS:rb_app RADIOBUTTON GROUP gbf DEFAULT 'X' USER-COMMAND uc01.
        PARAMETERS: p_file(128) MODIF ID 001.           " application server
        SELECTION-SCREEN END OF LINE.
    Thanks,
    Krishna..

  • How to make a listbox selected item highlight color from code the same as if user click on item?

    Hi all,
    I have a listbox that gets filled with data when my program starts. I save the last selectedItem value so I set it when the program start again. But the color that the selected item has is not the same as if the user click on it (pictures below).
    The color when I set the selectedIndex=someItem is black on light grey (background)
    The color when the user clicks on the item is white on blue (background)
    Any way to make them both white on blue (background)?
    Thanks
    This is the user clicking on it:
    This is the code:

    I think the difference is focus.  When you use the mouse to select it also sets focus to the listbox so you would have to set focus to the listbox when you set the selected item.  How are you setting your selected item?  I think that by
    using a property to hold the selected item rather than setting the index that might also fix the problem.
    Lloyd Sheen

  • How to make Logic auto-select channel when external instrument is selected?

    I recently upgraded hardware and now have to upgrade the OS 9 software (MOTU FreeStyle) I've been using and join the 21st century. I asked a Guitar Center employee about what package to buy and stressed that I wanted the software to auto-select the midi channel since that was a major benefit (for me) in using FreeStyle. I was informed that all of the newer DAW software did this (which made sense to me, after all FreeStyle was already at least 10 years old, although no longer under development (hence OS 9.) Logic Express was specifically recommended.
    Sadly, I don't see this capability in Logic Express. I don't understand why, if I have 15 instruments set up, and I select a new one, I have to manually look at each of the other instruments (assuming I don't have their channels memorized) and see what channels have been used so that I don't accidentally reuse the same one for the new instrument. Doesn't the computer already know what channels are unused??
    In FreeStyle could have 25 instruments set up for a 16 channel keyboard, and as long as there was never more than 16 voices playing at any particular time, the software just managed the channels for me. I don't know what happens if you go over 16 for a 16 channel instrument, I don't think I ever did (I never had voices cut out anyway.)
    Not to berate Logic Express, there's lots of cool stuff in it that I'm looking forward to exploring, and it sounds like you have to jump through hoops even to get MOTU's Digital Performer to emulate the same behavior and I suspect it's as much of a hassle to set it up as to just do it on the fly (from previous experience of "what a salesman says" vs. "what is real.") I'm just trying to figure out how to make the computer do the computer work so that I can do the music work.
    I have lots of partial (and even some complete!) projects to port over and not nearly as much spare time as I'd like to spend playing. I'd rather spend my meager spare time composing, not fighting with the technology.
    Any ideas?
    Thanks,
    -David

    Hi bunker,
    I can't test it at the moment but I think that can be achieved by slightly changing the code like so:
    *<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>*
    *<script type="text/javascript">*
    *$(document).ready(function(){*
    *$("td.GFPFilter span input").focus(function(event){*
    this.select();
    this.value = '';
    *</script>*
    Also, if you found my posts helpful or correct could you apply those labels to the relevant posts?
    Cheers,
    J
    Edited by: J Kremer on 20-Apr-2011 19:23
    Edited by: J Kremer on 20-Apr-2011 19:30

  • How to Make field for selection in the datasource.

    Hi All,
    I want to enable one field in the DataSource for selection. I am not getting where can we make that enable.
    I know we have one check box in transfer structure for make file for selection. But I am getting that is grayout , not able to check that ?
    Please let me know where can we change the setting to make it enable.
    regards
    Ashutosh D

    Look at Roberto's reply in the below post :
    Re: Hos to make a filed to be required field when creating datasource
    What is ur datasource ..?
    Have u tried RSA6 Change Mode for that datasource - Flag Selection?
    Message was edited by:
            Jr Roberto

  • How to make  struts html:select tag readOnly....!!!!

    Hi All,
    In my below code I want to make <html:select> as readonly like I did for <html:text>
    I don't want to make it disabled as it is graying out that field.
    My requirement is that it should be visible and also it shouldn't be editable.
    I am using Struts...!!!
    <html:text property="paramName" size="20" maxlength="50" readonly="true"/>                                
    <html:select property="paramTypeId" disabled="true"> // I dont want to use this--- disabled="true"
         <html:options collection="queryReturnType" property="value" labelProperty="label"/>
    </html:select>Thanks in advance....!!

    Can some one tell me in the below code
    *1. what is test="${controlEnabled}"....wha is this controlEnabled variable*
    *2. do I need to create an attribute for paramTypeId_Label in my form bean ??*
    I just wanna to make my <html:select> readonly..pls see my first post in this thread....!!
    <c:choose>
         <c:when test="${controlEnabled}">
           <html:select property="paramTypeId" >
                <html:options collection="queryReturnType" property="value" labelProperty="label"/>
           </html:select>
         </c:when>
         <c:otherwise
           <html:text property="paramTypeId_Label" value="${queryReturnType[paramTypeId].label}" readonly="true"/>
           <html:hidden property="paramTypeId"/>
         </c:otherwise>
    </c:choose>--Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to make applescript to select every 3rd file to move to new folder?

    I have an interesting 'problem' I think.
    As a result of a time-lapse experminent, I have a folder which holds several thousands of pictures from a fixed point, made over several days & nights.
    But there is one issue: the camera made 3 different exposures every 5 seconds.
    This resulted in every 3rd picture 'belonging' to each other. So these have to be selected for going in a seperate folder. Menaing: pictures 1 and 4 and 7 and 10 .... they must go in one folder. 2 and 4 and 8 and 11.. in the second folder. Finally 3 and 5 and 9 and 12 in a third folder.
    How to do this with software (to avoid injury) because of the thousands of pics.
    Is this do-able with applescript? How?
    Tnx

    Hello
    You may try something like the following script.
    Main part is written in shell script for performance sake. AppleScript is only used for user interface.
    Please see comments in script for its usage and behaviour.
    And please test the script first with small subset of your images.
    (Since the script will scan the source folder tree for image files, it is good idea not to create destination folders in source folder tree.)
    Minimally tested with OSX10.2 at hand but NO WARRANTIES of any kind.
    Make sure you have full backup of your images before applying this script.
    Hope this may help,
    H
    image file (jpg) sorter
    v0.2
    Script will let you choose two folders, i.e. -
    a) source folder where images reside (directory tree under the chosen folder is scanned),
    b) destination parent folder where three subfolders will be made (named '0', '1', '2').
    The file number i is obtained by removing extension and non-digts from file name.
    The file with number i (0-based) in source tree will be moved to (i mod 3)'th subfolder in destination.
    e.g.,
    IMG_1440.JPG -> '0' (i = 1440, i mod 3 = 0)
    IMG_1441.JPG -> '1' (i = 1441, i mod 3 = 1)
    IMG_1442.JPG -> '2' (i = 1442, i mod 3 = 2)
    IMG_1443.JPG -> '0' ...
    IMG_9997.JPG -> '1'
    IMG_9998.JPG -> '2'
    IMG_9999.JPG -> '0'
    IMG_0001.JPG -> '1'
    IMG_0002.JPG -> '2'
    IMG_0003.JPG -> '0'
    image file name convention : ZZZZ_9999.jpg
    set src to choose folder with prompt "Choose source folder."
    set src_ to (src's POSIX path's text 1 thru -2)'s quoted form
    set dst to choose folder with prompt "Choose destination parent folder."
    set dst_ to (dst's POSIX path's text 1 thru -2)'s quoted form
    set sh to "
    # source directory
    srcdir=" & src_ & ";
    # destination directories
    dstdir=" & dst_ & ";
    dest=("$dstdir"/{0,1,2});
    # make destinations
    mkdir -p "${dest[@]}";
    # let k = number of destination directories
    k=${#dest[@]};
    # sort files to destinations such that -
    # 1) number i is obtained by removing extension and non-digits from file name; and
    # 2) file with number i is stored in (i % k)'th destination, where i is zero-based.
    # e.g. Given xxxx_9999.jpg, k = 3;
    # i = 9999 and the file is sorted to destination 0 (= 9999 mod 3)
    find "$srcdir" -type f -iname '*.jpg' -print0 | while read -d $'\0' f;
    do
    leaf=${f##*/}; # get file name
    stem=${leaf%.*}; # remove extension
    i=${stem//[^0-9]/}; # remove non-digts from file name
    let i=0+10#$i; # to interpret, e.g., 010 as 10, otherwise 010 is treated as octal.
    # echo "$i $f ${dest[i % k]}"; # for testing
    mv "$f" "${dest[i % k]}"; # move file
    done
    do shell script sh
    display dialog "Done" with icon 1 giving up after 20

  • Can any tell me how to make Collage from selected images

    Hi
    I need to make a Collage of selected Images. Can anybody tell me how to proceed or point me a finger in the right direction. If there is an example then it would be great.
    Thanks in advance
    praveena

    One way you can do this is to override Panel, and set up clips, like this (mind you this is a very crude example. If you used this method, you'd want to set up loops and calculations to set the Polygon dimensions:
      private class MySubPanel  extends Panel {
        private Image[] images;
        private MySubPanel(Image[] _images) {
          images  = _images;
        public void paint(Graphics g) {
    // Just for a test, let's just assume only two Images are past in.
          int[]   xPnts = new int[] { 0,30,50,70,80, 95,75,60,45,30,15, 0},
                  yPnts = new int[] {20,35,15,35,20,110,75,95,70,85,55,30};
          Polygon p     = new Polygon(xPnts, yPnts, 12);
          g.setColor(new Color(50,150,20));
          g.setClip(p);
          g.drawImage(images[0], 0, 0, this);
          xPnts = new int[] { 0,15,30,45,60,75, 95, 80, 70, 50, 30,  0};
          yPnts = new int[] {30,55,85,70,95,75,220,130,145,135,155,130};
          p     = new Polygon(xPnts, yPnts, 12);
          g.setColor(new Color(50,150,20));
          g.setClip(p);
          g.drawImage(images[1], 0, 0, this);

  • ICal: how to make my print selections become the default

    how do I make my chosen printer selections become the default? Also, is there a way to assign selections to a named type of "file", i.e, "My Calendars", "My To Dos", etc.?

    If you leave a CD, DVD, or some disc with data, in the internal drive, it should then use the external drive for burning. If you use good blank discs, such as Verbatim, there should be no reason to reduce the burning speed.

  • How to make a JPanel containing buttons  take up the width of the window?

    I'm creating a GUI and I have a button group that I want to be the width of the window. I have another JPanel on the same window that doesn't have a button group in it and it takes up the width of the window. I don't think I'm doing anything differently creating the two, but I need consistency.
    The best way I can explain this is with code, so I created an example of what I am doing here:
    import java.awt.*;
    import javax.swing.*;
    public class test extends JFrame {
         public test() {
              JPanel win = new JPanel();
              JPanel buttonsPanel = new JPanel();
              JPanel statusPanel = new JPanel();
              win.setLayout(new BoxLayout(win, BoxLayout.Y_AXIS));
              buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
              statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.Y_AXIS));
    //          createRadioButtonsPanel
              ButtonGroup buttons = new ButtonGroup();
              JRadioButton currentMap = new JRadioButton("option1", true);
              JRadioButton newMap = new JRadioButton("option2");
              JRadioButton noMap = new JRadioButton("option3");
              buttons.add(currentMap);
              buttons.add(newMap);
              buttons.add(noMap);
              buttonsPanel.add(currentMap);
              buttonsPanel.add(newMap);
              buttonsPanel.add(noMap);
              buttonsPanel.setBorder(
                        BorderFactory.createTitledBorder("Create: "));
    //           createStatusPanel
              JLabel statusLabel = new JLabel("Loading...");
              statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
              statusLabel.setPreferredSize(new Dimension(400,20));
              statusLabel.setMinimumSize(new Dimension(400,20));
              statusLabel.setMaximumSize(new Dimension(400,20));
              statusPanel.add(statusLabel);
              JPanel statusButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              JButton pauseSearch = new JButton("Pause");
              JButton cancelSearch = new JButton("Cancel");
              statusButtons.add(pauseSearch);
              statusButtons.add(cancelSearch);
              statusPanel.add(statusButtons);
              statusPanel.setBorder(BorderFactory.createTitledBorder("Status: "));
              win.add(buttonsPanel);
              win.add(statusPanel);
              getContentPane().add(win);
              pack();
              setVisible(true);
         public static void main(String args[]) {
              test s = new test();
    }When I compile and run this class I get this window:
    http://img136.imageshack.us/img136/1538/exampleek5.png
    You see how on the bottom, "Status" JPanel takes up the entire width of the window? When the window is resized, the border is also resized. I would love to have the top "Create" JPanel have the same behavior. How do I do this?
    Thanks in advance!

    It can get confusing when using the BoxLayout. The box layout takes into consideration the X alignment of the components as well as the minimum and maximum lengths.
    So I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html]How to Use Box Layout for examples and explanations on how these values are used in the layout process.
    It may be easier to use a BorderLayout for the high level layout manger, since it will resize a components width when added to the NORTH, CENTER or SOUTH.

  • 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 to make dropdown menu selection create more text fields?

    I did some searching and am unable to find an answer for this. It could be because I don't know the name of what I'm trying to do (I'm a total LiveCycle Designer noob). I tried to find guides but they seem to be for newer versions of Designer (I'm using 8.2) so I'll ask here:
    I'd like specific text fields to appear after a pulldown menu option is selected (empty fields w/ the captions already filled in). How can I go about doing this?
    Thanks in advance!

    The script I see when I click on the dropdown menu in question:
    form1.#subform[0].DropDownList4::initialize - (FormCalc, client)
    form1.#subform[0].DropDownList4::enter - (FormCalc, client)
    form1.#subform[0].DropDownList4::exit - (FormCalc, client)
    form1.#subform[0].DropDownList4::calculate - (FormCalc, client)
    form1.#subform[0].DropDownList4::validate - (FormCalc, client)
    form1.#subform[0].DropDownList4::preOpen - (FormCalc, client)
    form1.#subform[0].DropDownList4::postOpen - (FormCalc, client)
    form1.#subform[0].DropDownList4::mouseEnter - (FormCalc, client)
    form1.#subform[0].DropDownList4::mouseExit - (FormCalc, client)
    form1.#subform[0].DropDownList4::change - (FormCalc, client)
    form1.#subform[0].DropDownList4::full - (FormCalc, client)
    form1.#subform[0].DropDownList4::mouseUp - (FormCalc, client)
    form1.#subform[0].DropDownList4::mouseDown - (FormCalc, client)
    form1.#subform[0].DropDownList4::click - (FormCalc, client)
    form1.#subform[0].DropDownList4::preSave - (FormCalc, client)
    form1.#subform[0].DropDownList4::postSave - (FormCalc, client)
    form1.#subform[0].DropDownList4::prePrint - (FormCalc, client)
    form1.#subform[0].DropDownList4::postPrint - (FormCalc, client)
    form1.#subform[0].DropDownList4::preSubmit:form - (FormCalc, client)
    form1.#subform[0].DropDownList4::postSubmit:form - (FormCalc, client)
    form1.#subform[0].DropDownList4::docReady - (FormCalc, client)
    form1.#subform[0].DropDownList4::docClose - (FormCalc, client)
    form1.#subform[0].DropDownList4::ready:form - (FormCalc, client)
    form1.#subform[0].DropDownList4::ready:layout - (FormCalc, client)

Maybe you are looking for

  • Editable and Non editable portion in JTextArea

    hi all i have following problem: in my application i m using JTextArea and JButton when button is clicked some text is added as follows with append method textarea.append("darshan"); textarea.append("\n\n"); textarea.append("gajjar"); now i want the

  • Problem in Master Detail form when using ADF table for Detail

    hi, jdev version-11.1.2.1.0 i have create Master detail form using datacontrol drag as ADF Master Form Detail Table. Now when i create a new row in Detail table using CreateInsert button a blank new row created on the top of detail table. and other r

  • Opening .msp.crdownload Acrobat Pro in Windows XP

    Hi I am trying to open an update for Acrobat Pro 9. The file extension is .msp.crdownload and Windows XP doesn't open it. How can I open and install the update? Thanks. Nancy Pedem

  • What do I do when time capsule says it's full?

    What do I do when time capsule says it's full?

  • Docx to epub

    Let me start by dating this.  June of 2013. Does anyone know of a current and great method to convert docx files to epub for upload to ibooks? I have seen older posts and methods (1-2 years) and they seem very convoluted.  I would imagine MS or someo