GridLayout in JPanles and JScrollPanels

Hi,
This problem might seem easy in the beginning, but I have spent lots of time solving it, and yet no success.
I have a frame with this size:
frm.setBounds(0, 0, 800,750);
It has a tabPanel, which in itself consists of a few panels, one of which is the following.
panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.setBackground(Color.white);
panel.setPreferredSize(new Dimension(200,450));
ScrollPanel = new JScrollPane(panel);
SP.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
SsrchSP.setPreferredSize(new Dimension(200,450));
vector.add(new Checkbox("string"));
panel.add((Checkbox) vector.lastElement());
All I am trying to do, is to add one checkbox per line to this panel.
What happens, is that when the number of lines increases, instead of assigning more space to the panel and scrolling it down,
it reduces the space in between the lines. i.e. each timea new line is added, it sqeezes the line into the panel space.
How should I avoid this, and just have a normal scroll panel with lines added into it?
Thanks for your help. I have a deadline at work for today ...
Tara.

Hi,
I have seen the code you have used to solve your problem, and is almost similar to the problem i have: I am using a class which extends to JPanel, I use this class to paint the results from a data base, the problem is whe the results are more than I can see in a single screen, so I want to scroll the screen, but i can't do the scrollbar apears. Maybe i have tu use a ManagerLayout in the panel.
i will apreciate your help.
this is the code of the JPanel:
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class DesplegarPanel extends JPanel
public void paintComponent(Graphics g)
super.paintComponent(g);
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException e)
System.out.println(e.getMessage());
try
Connection conexion = DriverManager.getConnection("jdbc:odbc:estetica");
Statement estatuto = conexion.createStatement();
ResultSet rs = estatuto.executeQuery("SELECT * FROM inventario ORDER BY nombreProd");
int x1=5;
int x2=200;
int x3=300;
int x4=400;
int y=25;
while(rs.next())
y=y+20;
g.drawString(rs.getString("clave"),x1,y);
g.drawString(rs.getString("nombreProd"),x2,y);
g.drawString(rs.getString("fecha"),x3,y);
g.drawString(Integer.toString(rs.getInt("cantidad")),x4,y);
rs.close();
estatuto.close();
conexion.close();
catch (SQLException e)
System.out.println(e.getMessage());
* and this is the frame: *
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class VerMercanciaExistente extends JFrame
private DesplegarPanel desplegarPanel;
public VerMercanciaExistente()
super(" Ver Mercanc?a Existente");
setSize(800,575);
getContentPane().setLayout(null);
desplegarPanel = new DesplegarPanel();
desplegarPanel.setBackground(new Color(84,31,100));
JScrollPane barraInv = new JScrollPane( desplegarPanel );
barraInv.setPreferredSize(new Dimension(200,200));
setContentPane(barraInv);
public static void main (String args[])
VerMercanciaExistente vme = new VerMercanciaExistente();
vme.show();
}

Similar Messages

  • Creating a gridlayout of jlabels and jbuttons in a JPanel

    The assignment:
    "Create a JPanel that contains an 8x8 checkerboard. Make all of the red squares JButtons and be sure to add them to the JPanel. Make all of the black squares JLabels and add them to the JPanel. Don't forget, you must use the add method to attach the JPanel to the JApplet's contentPane but that there is no contentPane for a JPanel. Be sure to set up any interfaces to handle the JButtons. Use a GridLayout to position and size each of the components instead of absolute locations and sizes."
    This assignment introduces the JPanel to me for the first time, I have not seen what the JDialog and JFrame are.
    What I have:
    import java.awt.*;
    import javax.swing.*;
    * Class CheckerBoard - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class CheckerBoard extends JPanel
        JButton redSquare;
        JLabel blackSquare;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            JPanel p = new JPanel();
            setLayout(new GridLayout(8,8));
            setSize(512,512);
            ImageIcon red = new ImageIcon("GUI-006-RedButton.png");
            ImageIcon black = new ImageIcon("GUI-006-BlackSquare.png");
            blackSquare = new JLabel(black);
            blackSquare.setSize(64,64);
            redSquare = new JButton(red);
            redSquare.setSize(64,64);
            for (int i = 0; i < 64; i++) {
                if ((i % 2) == 1)
                    add(blackSquare);
                else
                   add(redSquare);
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
    }After successfully compiling it when I try to run it there appears to be nothing to run. I've tried messing around with content panes but I'm not sure if I need to add one for this assignment at all.

    Some suggestions:
    1) First and foremost, read about JPanels, JApplets, and JFrames. None of the help you can get here will substitute for your applying yourself towards this, absolutely none, and judging by your code, you have your work cut out for you.
    2) Don't have your JPanel initialize with an init method, that's what Applets and JApplets do. Instead have it initialize with a proper constructor.
    3) I'm wondering if your "workaround" code belongs in the JApplet that contains the JPanel and not in the JPanel. It has nothing to do with the JPanel's mission. For instance, what if you later decide to place this panel into a JFrame?
    4) Avoid "setSize", and if at all possible, use "setPreferredSize" instead. You are working with LayoutManagers who do the size setting. You are best served by suggesting the size to them.
    5) Please ask specific questions. Just dumping your code without a question is considered quite rude here. We are all volunteers. If you want our free advice, you really should be considerate enough to make it easy for us to help you.
    Good luck.
    Edited by: Encephalopathic on Dec 21, 2007 6:14 PM

  • Applet very slow and shows no activity, but its running

    I have a new applet for the users, but I am reluctant to implement until I get some others opinions. It is very slow (30 - 40 seconds)
    Before it outputs a screen with about 20 lines, it reads 90 different html files. It looks at the forth rec of each to extract a name. It also gets the file size to determine if the record needs to be on the screen.
    Anyway, it does 4 reads on 90 files. = 360 reads. Oops, it also reads and loads a 80 record file at the beginning. So total is 440 reads.
    It takes 30 - 40 seconds. Which is not horrible, but it is not good. What really bothers me is that the applet screen shows no activity. At the bottom is shows "done" and "100%". Task Manager shows no activity. But if you just let it sit there, it will finally fill the screen. Pretty amazing to me. I would much rather see a "progress bar" moving on the bottom like other screens. Actually, a progress bar would solve it, because the users are not in a big hurry anyway.
    I am using "openStream" and "readLine" for the files.
    Any opinions?
    import javax.swing.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class urlaa extends JApplet
    //zz  implements Runnable, ActionListener
          implements ActionListener
    // zz added
        private JLabel item;
        private JList itemList;
      int par;
      int errorflag = 0 ;
      int orgsize = 14900 ;
      String par1;
      String s;
      String e1;
      String e2;
      String e3;
      String w1;
      String w2;
      String w3;
      String w4;
      int i = 0;
      int len ;
      int size ;
      String stringsize ;
      URLConnection conn ;
      int i2 = 0 ;
      int k = 0;
      int current = 0;
      String s1 ;
      String s6 ;
      String s7 ;
      String s8 ;
      String printline ;
      String pageLink;
      String arr[]  = new String[150] ;
      String arr2[] = new String[150] ;
      String arr3[] = new String[150] ;
      int arr4[] = new int[150] ;
      String inputLine;
      Thread runner;
      public void init()
             String parameter = getParameter("par1");
             if (parameter != null)
                 par = Integer.parseInt(parameter);
             else
                 par = 99;
    // zz         Button goButton = new Button("Go");
    // zz         goButton.addActionListener(this);
    // zz         add(goButton);
    // zz   added
            this.item = new JLabel();
            this.addButton();
            Container container = this.getContentPane();
            this.itemList = this.getList();
            container.add(this.getPanel());
            URL u;
            InputStream wis = null;
            DataInputStream dis;
            int rcnt = 0;
            int rcn2 = 0;
           //    1)  read filelist.txt file
           //         and load into a table.
           //    2)  close the filelist.txt file
           //    3)  Use the tabled file names to
           //         read and see if the bio
           //         has been done
           //  1) Read filelist.txt and load table
            try
            u = new URL("http://www.classof1961.mysite.com/filelist.txt");
            catch (MalformedURLException e)
              errorflag = 1 ;  // set error flag to stop while loops
              e1 = ("FILELIST.TXT MalformedURLException: " + e.getMessage()) ;
            try
                u = new URL("http://www.classof1961.mysite.com/filelist.txt");
                wis = u.openStream();
            catch (IOException ioe)
              errorflag = 1 ;  // set error flag to stop while loops
              e1 = ("FILELIST.TXT IOException : " + ioe.getMessage()) ;
    //      does not work     size = wis.getContentLength() ;
                // Convert the inputStream to a buffered DatainputStream.
                dis = new DataInputStream(new BufferedInputStream(wis));
                // Read 1st record to set up while loop
                   try
                     s1 = dis.readLine() ;  // get 1st rcd
                   catch (IOException ioe)
                     errorflag = 1 ;  // set error flag to stop while loops
                     e3 = ("FILELIST.TXT IOException : " + ioe.getMessage()) ;
                   while (s1 !=  null)
                   {  // load file names loop
                   if (errorflag == 0)
                   {  // if errors
                    arr[i] = s1 ;
                    i++ ;
                    try
                    s1 = dis.readLine() ;
                    catch (IOException ioe)
                      errorflag = 1 ;  // set error flag to stop while loops
                      s1 = null ; // force end of loop
                      e3 = ("load table read failed" + ioe) ;
                    rcnt++ ;
                    if (rcnt > 100)  // test code
                    {                // test code
                      errorflag = 1;
                      s1 = null ;
                      e3 = "Load table is looping!!" ;
                   }  // end of error check loop
                   }  // end of table load loop
               int lasttableentry = i ;  //
                   // CLOSE the filelist.txt file
                   try
                    wis.close();
                   catch (IOException ioe)
                    errorflag = 1 ;  // set error flag to stop while loops
                    e3 = ("close of filelist.txt file failed" + ioe) ;
    //   End of filelist read and load and close
    //      ptr to whats new names in table arr
            i = 0 ;
    //      While more names in table,
    //        Connect and Open file
    //        Read file until 4th rcd (rel 3rd rcd)
    //          if rcd has date, then move it to table
    //          else
    //          bump to next file name
              w1 = arr[i] ;
              w2 = w1.substring(1, 4) ;   // ONLY USED FOR CHK FOR XXXX
    //    ______________  start of major loop  _____________
            boolean morenames = true ;
            while (morenames)
            {  // Name table loop
            if (errorflag == 0)
            {  //if no errors
              try
                u = new URL(w1);
                try
                  URLConnection conn ;
                  conn = u.openConnection();
                  size = conn.getContentLength();
                catch (IOException e)
                  errorflag = 4 ;
                  morenames = false ;
                  e1 = ("file size logic failed " + w1) ;
              catch (MalformedURLException e)
                    errorflag = 1 ;  // set error flag to stop while loops
                    morenames = false ;
                    e1 = ("next whats new url error : " + w1) ;
    // compile error                break ;
              try
                  u   = new URL(w1) ;
                  wis = u.openStream();
              catch (IOException e)
                errorflag = 1 ;  // set error flag to stop while loops
                morenames = false ;
                e2 = ("next whats new open error :  " + w1) ;
    //   compile error            break ;
    //            Convert the inputStream to a buffered DatainputStream.
                  dis = new DataInputStream(new BufferedInputStream(wis));
                if (errorflag == 0)
                {  //if no errors
                       try
    //  does not work                       String s2 = dis.readLine(3) ;
                         s1 = dis.readLine() ;
                         s1 = dis.readLine() ;
                         s1 = dis.readLine() ;
                         s1 = dis.readLine() ;
                       catch (IOException e)
                         errorflag = 1 ;  // set error flag to stop while loops
                         morenames = false ;
                         e2 = "whats new file MalformedURLException: " ;
                       // file is larger than original non-bio file size
                       if (size > orgsize)  //  if file size > original file size
                       String s2a = s1.substring(0, 5);
                       String s3 = "                       " ;
    //                 Only look at title records to get the name
                       if (s2a.equals("<titl"))
                          int k2 = 7 ;
                          int l = k2 + 1 ;
                            while (!s1.substring(k2, l).equals("<"))
                              k2++ ;
                              l++ ;
                          s3 = s1.substring(7, k2) ;
                       else
                          s3 = "               " ;
    //                 s3 now has blanks or the name
                       arr2[k] = w1 ;    // move name into arr2 (link to bio)
                       arr3[k] = s3 ;    // move name into arr3 (bio name)
                       arr4[k] = size ;  // move in file size
                       k++ ;
                       } // end of if length > 36
                } // end of chk for error flag zero (no errors)
                  //  now we have to close this whats new file
                   // CLOSE the current whats new file
                   try
                    wis.close();
                   catch (IOException ioe)
                    errorflag = 1 ;  // set error flag to stop while loops
                    morenames = false ;
                    e3 = ("close of the current whats new file failed" + ioe) ;
                  //  end of the close
              rcn2++ ;
              if (rcn2 > 100)  // test code
              {                // test code
                 errorflag = 2;
                 morenames = false ;
                 e3 = "Searching files is looping!!" ;
              i++ ;           // bump to next whats up name
              w1 = arr[i] ;   // load it into work string
              if (i > lasttableentry)
                morenames = false ;
              } // end of error checking loop
             else
                  morenames = false ;
            } // end major name table loop
                   // CLOSE the last whats new file
                   try
                    wis.close();
                   catch (IOException ioe)
                    errorflag = 1 ;  // set error flag to stop while loops
                    e3 = ("close of last whats new file failed" + ioe) ;
    // end of init
    //     _________________ other methods  ______________________
    // zz added
        private JList getList() {
            // Create a List
            JList tempList = new JList(arr3);
            tempList.setVisibleRowCount(3);
            // Enable single selection
            tempList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            return tempList;
        private JButton addButton() {
            JButton button = new JButton("Select Item below and click here to go to the bio");
            button.addActionListener(this);
            return button;
        private JPanel getPanel() {
            // set layout to GridLayout 3 rows and 1 columns, no separations
            JPanel panel = new JPanel(new GridLayout(3,1,0,0));
            JScrollPane spane1 = new JScrollPane(this.itemList);
            panel.add(this.addButton());
            panel.add(spane1);
            panel.add(this.item);
    //       panel.add(new JLabel("Example List"));
            return panel;
    //   _______________  actionPerformed method  ____________________
         public void actionPerformed(ActionEvent evt)
           s8 = "actionPerformed";
    // zz added
            String command = evt.getActionCommand();
            // Get the selected value from the list and update the JLabel
            item.setText((String)itemList.getSelectedValue());
    //  try to redirect to selected url
      try
             int idx  = itemList.getSelectedIndex() ;
             String urlvalue = this.arr2[idx] ;
             URL u = new URL(urlvalue);
             this.getAppletContext().showDocument(u, "_self");
         catch(Exception e)
    }

    jagossage wrote:
    But if you just let it sit there, it will finally fill the screen. Pretty amazing to me. The onus is on you, the developer, to decide how to distract your users as they wait for your code to finish. Why should you expect something to do it for you?
    I would much rather see a "progress bar" moving on the bottom like other screens.Ah, I think I see where you're confused. The progress bar and applet loading subtitles, etc are Java's way of presenting the progress of loading the applet. Once it's fully loaded, though (which it is when your code starts running), it hands off control to you. It's in your hands at that point.

  • Have GridLayout in JLayeredPane

    Hi, I would like to have a JPanel with GridLayout as background and another image on top of it. So I think I have to add 2 JPanel into the JLayeredPane but it doesn't work. I wonder whether I can do it in fact, anybody know it? Thanks.
    I have my code for your reference:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MainFrame{
         public MainFrame(){
              initFrame();
         public void initFrame(){
              JFrame frame = new JFrame("Swing program");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              ImageIcon bgIcon = new ImageIcon("pic/background.jpg");
              JLabel[] bgLabel = new JLabel[4];
              for(int i=0; i<4; i++){
                   bgLabel[i] = new JLabel(bgIcon);
                   bgLabel.setBounds(50,50,200,200);
              JPanel bgPane = new JPanel(new GridLayout(2,2));
              bgPane.setPreferredSize(new Dimension(600, 600));
              for(int i=0; i<4; i++){
                   bgPane.add(bgLabel[i]);
              ImageIcon charIcon = new ImageIcon("pic/character.jpg");
              JLabel charLabel = new JLabel(charIcon);
              charLabel.setBounds(10,10,100,100);
              JPanel charPane = new JPanel();
              charPane.setPreferredSize(new Dimension(100,100));
              charPane.add(charLabel);
              JLayeredPane layeredPane = new JLayeredPane();
              layeredPane.setPreferredSize(new Dimension(600, 600));
              layeredPane.add(bgPane, new Integer(1));
              layeredPane.add(charPane, new Integer(2));
              Container contentPane = frame.getContentPane();
              contentPane.add(layeredPane);
              frame.pack();
              frame.setVisible(true);

    Error in code:for(int i=0; i<4; i++){
      bgPane.add(bgLabel);
    }should befor(int i=0; i<4; i++){
      bgPane.add(bgLabel[ i]);
    }

  • Move elements in layout and bind the elements?

    Hi experts, I have sereval questions.
    1. In a view, I drag & drop a group to the layout and drap sereval elements on the group. But I can't move the elements to the next line. They were just arranged one after one and line after line. How can I move them as I want?
    2. Does it exist a "table" element for the layout? Where is it?
    3. Does it exist a "date select" button for the layout which allows me to see a calendar and select a date on clicking it? Where is it.
    4. I've  mapped and binded the context of Component Controller to my Window context. But when I want to map & bind Window Context to View Context, all of the elements of context are gray that I can't bind them to the UI elements on the layout. That's why? How can I bind them?
    Thank you a lot in advance!!!!!

    Hi
    1. In a view, I drag & drop a group to the layout and drap sereval elements on the group. But I can't move the elements to the next line. They were just arranged one after one and line after line. How can I move them as I want?
    You have to use Layouts, you have GridLayout, FlowLayout, MatrixLayout and RowLayout
    Layout property is there for Groups, Transparent Containers
    2. Does it exist a "table" element for the layout? Where is it?
    Table UI element is not for Layouts, you have to use the Layouts mentioned above
    3. Does it exist a "date select" button for the layout which allows me to see a calendar and select a date on clicking it? Where is it.
    Take an Input Field and bind it with a Cotnext Attribute which of type DATS or dataelement which is a date type, then you can see calender automatically
    4. I've mapped and binded the context of Component Controller to my Window context. But when I want to map & bind Window Context to View Context, all of the elements of context are gray that I can't bind them to the UI elements on the layout. That's why? How can I bind them?
    This should not happen, check this again
    Abhi

  • Help with JLabels and JTextFields

    I'm experimenting with JLabels and JTextFields in a basic JFrame. What I am trying to accomplish (without success) is to align a JLabel above and centered on a JTextField. The tutorials are confusing me. Any help would be greatly appreciated. a Sample of code is ...
    JLabel  myTextLabel = new JLabel("Who's text Field?");
    JTextField myTextField = new JTextField("My Text Field");...after reading the tutorial I thought that I needed to assign L&F variables to the JLabel ... i.e.
    JLabel myTextLabel = new JLabel("Who's text field?:", JLabel.CENTER, JLabel.TOP); but this results in an error when compiling. (cannot find symbol), so I thought I need to assign the JLabel to the JTextField. i.e.
    myTextLabel.setLabelFor(myTextField);Then I get "identifier" expected. So now being completely confused I am here asking "How do I?" :)
    Thanks in advance!

    Most likely, you need to think a little more about using a layout manager to hlp you along the way. If memory serves, the default layout manager for a JPanel is FlowLayout and that will simply place the components you add to the panel one after another and allow each to adopt it's preferred size.
    One way to ensure that the two compoenets were sized equally, would be to use the GridLayout layout manager and create either one row with two columns, or two rows with one column on each. Then add the compoennets to each of the 'cells' so to speak and that should ensure that they are both the same size.
    As to making the text centered in each, both the JLabel and JtextField classes have amethod called setHorizontalAlignment(); it can be used to aligh the text as you require.
    Simply create an instance of the class;
    JLabel aLabel = new JLabel("Some Text");
    // Then set the alignment
    aLabel.setHorizontalAlignment(SwingConstants.CENTER);Or, do the whole operation i one step
    JLabel aLabel = new JLabel("Sone Text", SwingConstants.CENTER);and then add the componenet to the panel once you have set the layout manager.
    Remember that the label.textfield will have to be wide enought to make it obvious that the text is centered!

  • JCalendar and GroupLayout

    Greetings,
    Greetings,
    Thanks for taking the time to listen to my problem. I am a moderately-experienced Java developer, but I am a newbie when it comes to Swing components. I am trying to build a program for someone, and I need a date chooser.
    I downloaded the JCalendar from http://www.toedter.com/en/jcalendar/. However, I am unable to implement the JDateChooser effectively, and I think it's because of my limited experience with Swing.
    I use Netbeans to build all my Swing apps, because it knows everything that I don't. =D My THEORY is, it's something to do with GroupLayout vs GridBagLayout. My theory stems from the fact that I copy/pasted the DateChooserPanel code (which is from the JCalendar demo), and it worked. I began commenting off lines of code 1 by 1, and the entire thing disappeared when I commented off the "setLayout(gridbag);" Also, the panels I had created in Netbeans finally started showing the DateChooser when I made all their layouts GridBag...
    Does anyone else have trouble using JCalendar components with a GroupLayout? Are we forced to use GridBagLayout? Layouts are a bit advanced for me. I'm not unwilling to take the time, but I've spent too many hours on this (small) feature to not ask for some help.
    Any help would be greatly appreciated.
    I also posted this question on their forums, but being that the most recent post was 2 months ago, I thought I'd post it here also to see people's input.

    rwilson352 wrote:
    Greetings,Live long and prosper.
    Does anyone else have trouble using JCalendar components with a GroupLayout? GroupLayout is for having an IDE place components in a container. It's very difficult to use manually.
    Are we forced to use GridBagLayout? Heck no, and in fact that's a layout many of us avoid if possible. There are several other easier to use layouts.
    Layouts are a bit advanced for me. I doubt this, I really do.
    I'm not unwilling to take the time, but I've spent too many hours on this (small) feature to not ask for some help.It will be hard to help without more info and code (not NetBeans generated code though!). I suggest that you first read the Sun layout tutorial as they're really not that hard to use -- just avoid GridBagLayout if you can, especially early on. Instead focus on GridLayout, BorderLayout, BoxLayout, and FlowLayout. It will be effort well-spent.
    If after this effort you're still striking out, then look into creating and posting an SSCCE (see the link)

  • Design problem(split pane scrollpane Insets)

    hi,
    doing a exam simulator prgm
    design is like,
    Question (text area with scrollpane)
    Answers (checkbox inside panel with scrollpane)
    used split pane between qst and ans but big thick bar comes how to reduce size and it is not
    moving.
    used GridLayout for container and panel.
    PROBLEM is how to leave space qst textarea appears from very left edge of screen how to leave some space
    same prblm for checkbox they to appear extreme left on screen.

    Put those components in a JPanel overwriting the getInsets() method like this:
    JPanel cPane=new JPanel(){
        private final Insets _insets=new Insets(10,10,10,10);
        public Insets getInsets(){
            return _insets;
    };...should do the trick, take a look at the Insets class if you need information on how defining it...

  • Buttons doesn�t fit the panel correctly

    public class myProgram extends Applet implements ActionListener
    JButton blue = new JButton();
         JButton red = new JButton();
         JButton yellow = new JButton();
         JButton green = new JButton();
         JButton white = new JButton();
    JPanel painel = new JPanel(new BorderLayout());     
    painel.add(blue,BorderLayout.NORTH);
         painel.add(yellow,BorderLayout.CENTER);
         painel.add(red,BorderLayout.EAST);
         painel.add(green,BorderLayout.SOUTH);
         painel.add(white,BorderLayout.WEST);
    add(painel); //add panel to the applet
    When I add the buttons they don�t fit correctly the panel. I have tried many kinds of layout and I didn�t get what I wanted. Some buttons seems bigger than the others.

    When I add the buttons they don�t fit correctly the
    panel. I have tried many kinds of layout and I didn�t
    get what I wanted. Some buttons seems bigger than the
    others.Well that happens with the BorderLayout. Possible solution might be using a GridLayout, a FlowLayout and the setPreferredSize(), setMaximumSize(), setMInimumSize() methods, a null layout and the set****Size() methods plus the setAlignmentX() setAlignmentY() methods.
    al912912

  • Can't resize JScrollPane

    I put a JTable in a JScrollPane using
    new JScrollPane(table);
    I can't change the Dimension of the JScrollPane and if the table is greater than the Panel it is cuted even if I scroll max ...
    Any Help is welcomed

    if changing size of the scrollpane does not work and the reason is not the layout you use you could try to put the scrollpane on a panel with Gridlayout(1,1) and resize the panel.

  • Substring index out of range

    i am using substring
    and putting string
    into 2 jlabel's
    at runtime
    i dont know the size of index at rumtine
    though i am using database to rerieve information
    into label
    it gives me error
    String index out of  range:40_
    any solutions to this plz..........

    i am using 3jlabels and putting them in jpanel
    which layout i set to gridlayout
    p1.setLayout(new GridLayout(3,0))and here is the problem code in which iam getting runtime error
    try
    String txt1=res.getString(2);
    String txt01=txt1.substring(0,40);
    String txt02=txt1.substring(41);
    label1.setText(txt01);
    label3.setText(txt02);
    label2.setText(res.getString(3));
           //label4.setText(res.getString(4));
    }Edited by: Karamjeet on Jul 11, 2009 1:57 PM

  • Two JSplitPanes sharing single JPanel...

    Say I have JPanels 1,2 and 3. I want JPanel 1 on top with a splitPane dividing it and Panel 2. THen I want JPanel 2 and 3 to be divided w/ another JSplitPanel . I can't seem to get this to work. Here's a little pseudo of what I'm doing.
    JPanel jp1,jp2,jp3.
    JSplitPane jsp1,jsp2
    jsp1 = new JSplitPane(Vertical, jp1, jp2);
    jsp2 = new JSPlitPane(Vertical,jp2,jp3);
    getContentPane().add(jsp2);
    I'm not sure If It's a Layout Manager issue or if I'm just doing it wrong. I've tried this with GridLayout(2,1) and put both in, and default Manager just putting in jsp2. THanks for any help.

    Say I have JPanels 1,2 and 3. I want JPanel 1 on top
    with a splitPane dividing it and Panel 2. THen I want
    JPanel 2 and 3 to be divided w/ another JSplitPanel .
    I can't seem to get this to work. Here's a little
    pseudo of what I'm doing.
    JPanel jp1,jp2,jp3.
    JSplitPane jsp1,jsp2
    jsp1 = new JSplitPane(Vertical, jp1, jp2);
    jsp2 = new JSPlitPane(Vertical,jp2,jp3);A component can only have one parent, but you are adding jp2 to both jsp1 and jsp2.
    Change the above with
    jsp1 = new JSplitPane(Vertical, jp2, jp3)
    jsp2 = new JSplitPane(Vertical, jsp1, jp1)
    getContentPane().add(jsp2)
    I'm not sure If It's a Layout Manager issue or if I'm
    just doing it wrong. I've tried this with
    GridLayout(2,1) and put both in, and default Manager
    just putting in jsp2. THanks for any help.No its not the layout manager.

  • Swing interview questions

    I thought this would be the best place to ask some of you all what type of questions should be asked in an interview for a Swing developer. I also would love to have some questions about general GUI development.
    I have to interview a guy and I need to know what to expect from him and this is the first GUI interview I've done.

    So, after discussing this thread with some co-workers we came up with the following, which I think are acceptable GUI and Swing questions. They aren't too hard but aren't easy, and they tend to more relevant than just asking for specific information that can be looked up in the API.
    We did go through them and give some of what should be heard in an answer. These 'answers' aren't catch-alls, and may not have what individual interviewers are looking for but I think they make a good starting point. Some of the questions require a mockup or screenshot to ask them and these weren't included. Since different jobs require different skills an interviewer will need to create their own mockups and screenshots to focus the interview to the job listing.
    Interview Questions
    Graphical User Interface and Swing
    Section 1 - General Swing and GUI Questions
    What types of components have you used?
    This will depend on what the company does but you can never go wrong with JTables and JTrees. If you do MDI development, obviously JInternalFrames might be something you want to hear. The interviewee gets extra points for GridBagLayout experience since it is so powerful but feared by many Java delevopers.
    When you are building a GUI do you prefer to use an IDE or build it by hand?
    You want an employee who can do it by hand but you don't want the person to be inefficient and not use an IDE if it's available. If the person doesn't have any experience with an IDE that's not a plus or minus, it just means they will need to learn (if you are an IDE shop). If the person is only creating GUIs through an IDE builder, that may be a problem but there are other questions to clarify the person's skills.
    What is the difference between AWT and Swing?
    The difference is that an AWT component is a 'heavyweight' and Swing is a 'lightweight' component. Obviously, the interviewee needs to know that a heavyweight component depends on the native environment to draw the components. Swing does not. The interviewee gets extra points for some of the other things Swing brings to the table, like a pluggable look & feel, MVC architecture, and a more robust feature set.
    Can you name four or five layout managers?
    GridBagLayout, GridLayout, BorderLayout, FlowLayout, and CardLayout tend to be the most common. There are others that are listed in the Java API; check out the java.awt.LayoutManager interface for more.
    What is the difference between a component and a container?
    All Swing 'objects' are components, like buttons, tables, trees, text fields, etc. A container is a component that can contain other components. Technically, since JComponent inherits from Container all Swing components are containers as well. However, only a handful of top-level containers exist (JFrame, JDialog, etc.), and to be visible and GUI must start by adding components to a top-level container.
    Some components do not implement their 'add' methods so while they may be containers they do not allow the nesting of other components within their bounds. Specifically, JPanels can be used for component-nesting purposes.
    What would you change about this dialog?
    Using a dialog screenshot that has a poor layout, uses the wrong component for a specific task, has poor spacing between components, allow the interviewee to dissect the dialog and describe what should be done. I would suggest that a completely fictitious dialog is used to remove any personal biases the interviewer might have.
    This definitely needs to come before the next question, since we don't want to taint the interviewee with how we think a dialog should look. So the next question is:
    Explain how you would achieve the layout given this mockup.
    Using a screenshot of a dialog with a fair number of components, the user is to explain how they would get the components to be in the locations that they are in the mockup. This is much like the layout manager question although in this case the skill with the layout managers is being questioned. The weight each interviewer places on this question is up to them, but it can be used to discover whether someone knows about, has used it occasionally, or is intimately familiar with GridBagLayout or other layout managers. Also take into consideration the grouping of logical components in panels that might make a new piece of data that needs to be reflected in the dialog easier to add in later.
    What is the significance of a model in a component (for example, in a JTable or JTree)?
    What are the advantages of using your own model?
    The model in a component is used to fine-tune what the component displays by returning the specific data in specific instances where either the default values are used (a default model) or custom values are used (a custom model).
    When would you use a renderer or editor on a component?
    A renderer is used to create a custom display for the data in a component. The custom display is all that a renderer does. Implementing an editor allows the user to manipulate the data as well as have a custom display. However, once editing is completed the renderer is once again used to display the data.
    Why is Swing not 'thread safe'?
    A Swing application is run completely in the event-dispatching thread. Changes to components are placed in this thread and handled in the order they are received. Since threads run concurrently, making a change to a component in another thread may cause an event in the event-dispatching thread to be irrelevant or override the other thread's change.
    To get around this, code that needs to be run in a thread should be run in the event-dispatching thread. This can be achieved by creating the thread as normal but starting the thread by using SwingUtilities.invokeLater() and SwingUtilities.invokeAndWait().
    What would you do if you had to implement a component you weren't familiar with?
    This question is more about the process a person uses to solve a coding problem. Where do they go to find an answer? The order of the sources of information is just as important as which sources. Asking team members or other co-workers should be first, with other sources like the Internet (documents and forums) and books next. The Java API can also be useful in some cases but I think we have to assume that the component's requirements were more complex than just the API documentation can tell you.
    Section 2 - GUI Design Skills
    In this section, we are going to give the user an example of some inputs that need to be implemented and have them design a GUI for us. This will be completely done on the whiteboard and we don't care about any code. The timeframe is irrelevant so any component or custom component can be used.
    What we are looking for:
    - A design that focuses on the workflow from the user's perspective.
    - The proper components used to represent the data, but also
    - Unique and interesting ways of displaying data.

  • Listening for change events on a JTable

    Hi
    me = Java newbie!
    Well I've been building an app to read EXIF data from JPEG files using the imageio API and Swing. Learning both along the way.
    Stumbling block is that I am outputting the EXIF data into a JTable, inside a JScrollPane. These 2 components then become associated with a JInternalFrame container of the class MyInternalFrame.
    Works!
    Next job is to enable user to select a row in the table which then displays the image file.
    I know I can use ListSelectionEvent to detect a row selection and that 2 events are fired.
    I put some code into MyInternalFrame class to register a ListSelectionEvent, but I can't see how to reference MyInternalFrame from within this code....see below:
    package EXIFReader;
    import java.io.File;
    import java.io.FilenameFilter;
    import javax.swing.JInternalFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    //This class constructs a table and displays it in a JInternalFrame
    public class MyInternalFrame extends JInternalFrame {
    static int openFrameCount = 0;
    static final int xOffset = 30, yOffset = 30;
    File file;
    File[] directoryMembers = null;
    public MyInternalFrame(File aFile) { //aFile rererences a directory containing jpeg files//
    super(null,
    true, //resizable
    true, //closable
    true, //maximizable
    true);//iconifiable
    file = aFile;
    //Set the window's location.
    this.setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    FilenameFilter filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
    return name.endsWith(".jpg");}};//Filter out any files in the directory that ain't jpegs
    directoryMembers = file.listFiles(filter);
    int i = 0;
    String[][] tableData= new String [directoryMembers.length][5];
    String[]headers = new String[]{"File Name","Date Taken",
    "F-Number","Exposure",
    "Flash Settings"};
    for (File dirfile: directoryMembers)
    try {
    if(dirfile!=null){
    tableData[i] = new ExifReader(dirfile).getEXIFData();//populate the table with jpeg file names
    i++;}}
    catch (Exception ex) {
    System.out.print("Error" + ex);
    if (tableData[0] != null){
    final JTable myTable = new JTable(tableData,headers);
    this.setSize(900,(50+(directoryMembers.length)*19));
    myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    this.getContentPane().add(new JScrollPane(myTable),"Center");//add the JTable and JScrollPanel to this MyInternal Frame and display it! - cool it works!
    ListSelectionModel myLSM = myTable.getSelectionModel();
    myLSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent le) {
    int[] rows = myTable.getSelectedRows();//want to respond to selections and then display the image as a JInternalFrame but got confused about references from within this listener - need help!
    Any gentle nudges?!
    P
    I can respond to these events using a JFrame, but how can I display the image in a JInternalFrame?

    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    db

  • Aligning swing components

    hello everybody,
    i read about FlowLayout,BorderLayout,GridLayout,BoxLayout,CardLayout and GridBagLayout,but i still have a problem in aligning the components.
    I want to desgin a Wizard Frame like in this Following Website:
    http://java.sun.com/products/jlf/at/book/Wizards2.html#51473
    the problems are:
    How to draw the line under the Subtitle?
    How to align the component in that way?
    if there is some real examples,please guide me.
    thank you in advanced...

    What you have here is a combination of layouts ...
    First, there is a BoxLayout aligned along the Y-Axis seperating the top content with the buttons at the bottom.
    Second, There is FlowLayout seperating the two panels at the top, also with a bevel border.
    Third, for the different spacings, use Box.HorizontalGlue and Box.VerticalGlue items. There are others space fillers in the Box Class, check them out.
    Hope that helps
    Cheers

Maybe you are looking for

  • How to go for a JCO connection

    Hi All, I want to establish a jco connection. How can I proceed for the same . Can any one give me a step by step description. Regards DK

  • Export from iweb to Wordpress

    Hi I've been running a blog via iWeb, but I've been advised to move it to something more SEO-able, and to allow log in from anywhere - Wordpress in fact. There are quite a few entries in my blog, is there any way of exporting everything from iweb so

  • SNMP monitoring of Oracle 10g?

    Hi there, I'm curious about using SNMP technology to monitor Oracle 10g databases. I've done some light reading on the subject and I'm now at the stage where I have a few questions. -What exactly do I need to configure in my Oracle 10g environment? -

  • Installing BPEL PM 10.1.2.0.2 for OC4J Developers on AIX

    Hi I'm trying to install BPEL PM 10.1.2.0.2 for OC4J Developers on AIX. I downloaded the as_aix5l_power_bpel_101202.cpio and ran the "./runInstaller" from the "bpel_oc4j" directory. As per the installation instructions(it did not specifically have in

  • Just bought new video ipod need help

    Hey everyone... Yesterday I bought a new 30gig black video ipod. Using some programs i bought on the internet, i was able to convert the movie "Animal House" to MP4 and put it on itunes. The computer I did this on was my brothers computer since my co