Confusing behaviour with layout managers.

It appears that this page has become my favorite web page, having in mind all the
questions I come up with.
In the following page:
http://java.sun.com/docs/books/tutorial/uiswing/layout/none.html
a code example is given on how to use a null layout manager. If I use exactly the
same code, but instead of adding the pane into a frame, I add it into yet another
JPanel with for example FlowLayout, then the pane with the null layout manager
gets size 0...it just becomes a pixel in the panel it was added. I am not able to
fix this even if I in a hard-wired manner try to set the size of the internal pane.
Can somebody explain to me why the top level pane appears to completely ignore
the bounds and sizes set by the pane with the null layout manager? This confuses
me a lot :-/

hi there
did you...
1)set the bounds of each of the components contained by your jpanel?
2)then set the size of the jpanel?
if yes then did you:
3)call pack() on your jframe?
4)[before calling setVisible(true) on same jframe?
regards
lutha                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Help with layout managers

    I can't seem to understand layouts. Or maybe it's text components. Anyway, this little JFrame class seems to act really strangely, and I cannot figure out why.
    Can anybody tell me how to get pack() to do something sensible with the components in the main JFrame (the one with the statistics is just for reference.)
    The rest of this message is Java code (plus maybe a signature)
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import java.awt.Container;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    public class MyFrame extends JFrame {
    private String str;
    private JPanel panel;
    private JButton button;
    private JTextField textField;
    private JTextArea afterStatus;
    private JFrame otherFrame;
    private Container otherStuff;
    public MyFrame(String s) {
         // Create companion frame to hold statistics.
         afterStatus = new JTextArea();
         otherFrame = new JFrame("Stats");
         otherStuff = otherFrame.getContentPane();
         otherStuff.add(afterStatus, BorderLayout.CENTER);
         otherFrame.pack();
         otherFrame.setVisible(true);
    str = s;
    textField = new JTextField();
         panel = (JPanel)getContentPane();
    button = makeAButton();
    panel.setPreferredSize(new Dimension(200, 30));
    panel.add(button, BorderLayout.WEST);
    panel.add(textField, BorderLayout.EAST);
         textField.setText("Something or other; long so you can see it resize");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         myUpdate();
    private void myUpdate() {
         afterStatus.setText("Message is now: " + textField.getText() + "\n\n");
         afterStatus.append("textField Status Before Last Pack:\n");
         afterStatus.append("PreferredSize: " + textField.getPreferredSize() + "\n");
         afterStatus.append("Current Size: " + textField.getSize() + "\n\n");
         afterStatus.append("Button Status Before Last Pack:\n");
         afterStatus.append("PreferredSize: " + button.getPreferredSize() + "\n");
         afterStatus.append("Current Size: " + button.getSize() + "\n\n");
    pack();
         afterStatus.append("textField Status After Last Pack:\n");
         afterStatus.append("PreferredSize: " + textField.getPreferredSize() + "\n");
         afterStatus.append("Current Size: " + textField.getSize() + "\n\n");
         afterStatus.append("Button Status After Last Pack:\n");
         afterStatus.append("PreferredSize: " + button.getPreferredSize() + "\n");
         afterStatus.append("Current Size: " + button.getSize() + "\n\n");
         afterStatus.append("ContentPane Status After Last Pack:\n");
         afterStatus.append("PreferredSize: " + panel.getPreferredSize() + "\n");
         afterStatus.append("Current Size: " + panel.getSize() + "\n\n");
         otherFrame.pack();
    public static void main(String[] args) {
    String text = "Hello World";
    MyFrame frame = new MyFrame(text);
    frame.setVisible(true);
    public JButton makeAButton() {
    JButton b = new JButton("Push Me!");
         final JPanel thePanel = panel;
         final MyFrame thisFrame = this;
    class ButtonListener implements ActionListener {
    private int count;
    public ButtonListener() {
    count = 0;
    public void actionPerformed(ActionEvent e) {
    ++count;
    textField.setText("A longer than normalouch " + count);
    thePanel.revalidate();
              thisFrame.myUpdate();
    ButtonListener blist = new ButtonListener();
    b.addActionListener(blist);
    return b;
    public String getText() {
    return str;
    }

    Swing related questions should be posted in the Swing forum.
    Use the "code" tags when posting code, so the code retains its original formatting.
    panel.setPreferredSize(new Dimension(200, 30));Remove the above line. If you set the preferred size of the panel, then it doesn't care about the preferred size of its contained components.

  • Issue with adding JPanel objects with layout managers

    Hi. The games I made in the past did not contain any customized menus (ie. not from JOptionPane) different components dividing the display screen... so I thought I would try to on my current game I'm working on. So here's the issue: I'm trying to set the GUI up for the game screen.. but when I try to add in additional JPanel objects into the my main JFrame object, all of the JPanel objects stack up at the very top left corner (their not supposed to because I am using a layout manager). Here's my simplified version of the code:
    public void setUpGame(){
         MainGame game = new MainGame();
         game.setLayout(new BoxLayout(game, BoxLayout.Y_AXIS) );
            playPanel = new PlayPanel(); // don't worry about this.. it's a subclass of JPanel.
         playPanel.setPreferredSize( new Dimension(playPanel.width, playPanel.height) );     
            game.add(playPanel);
            JPanel collections = new JPanel();
            collections.setLayout(new FlowLayout() );
            collections.setPreferredSize( new Dimension( 1280, 256));
            miniMapPanel = new MiniMapPanel(); // subclass of JPanel.
         miniMapPanel.setPreferredSize( new Dimension(miniMapPanel.width, miniMapPanel.height) );
            collections.add(miniMapPanel);
            statsPanel = new StatsPanel();
         statsPanel.setPreferredSize( new Dimension(statsPanel.width , statsPanel.height ) );
            collections.add(statsPanel);
            ... // I do the same thing for StatsPanel and CommandPanel objects
            game.add(collections);
            add(game);
            // referencing to the JFrame object
            this.pack();
            setVisible(true);
            setFocusable(true);
    }Notes:
    -The sum of miniMapPanel.width, statsPanel.width, ... , commandPanel.width add up to 1280 pixels.
    - miniMapPanel.height, statsPanel.height, ... , commandPanel.height all have the same height of 256 pixels.
    - What I'm trying to do is set up a GUI very similar to that of StarCraft, and WarCraft.
    - The game is set up in full screen.
    When I compile the program, I see (and I've tested for it) that all of the JPanel objects that were created are all stacked one on top of each other, in the top left corner of the screen. Any ideas and/or suggestions are welcome.

    Hi weng,
    Try the following code example. I think the issue might be in your overridden methods if you did.
        public static void main(String[] args) {
            JPanel viewPanel = new JPanel();
            viewPanel.setBackground(Color.GREEN);
            viewPanel.add(new JLabel("You see a hut here..."));
            JPanel minimapPanel = new JPanel();
            minimapPanel.setBackground(Color.WHITE);
            minimapPanel.add(new JLabel("Minimap!"));
            JPanel commandPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
            commandPanel.add(new JButton("Characters"));
            commandPanel.add(new JButton("Inventory"));
            commandPanel.add(new JButton("World Map"));
            commandPanel.add(new JButton("Menu"));
            JPanel lifeAndManaPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
            lifeAndManaPanel.add(new JLabel("Life: 999/999"));
            lifeAndManaPanel.add(new JLabel("Mana: 999/999"));
            JPanel statusPanel = new JPanel(new BorderLayout());
            statusPanel.add(commandPanel, BorderLayout.PAGE_START);
            statusPanel.add(lifeAndManaPanel, BorderLayout.CENTER);
            JPanel bottomPanel = new JPanel(new BorderLayout());
            bottomPanel.add(minimapPanel, BorderLayout.LINE_START);
            bottomPanel.add(statusPanel, BorderLayout.CENTER);
            JPanel game = new JPanel(new BorderLayout());
            game.add(viewPanel, BorderLayout.CENTER);
            game.add(bottomPanel, BorderLayout.PAGE_END);
            JFrame frame = new JFrame();
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(game, BorderLayout.CENTER);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(800, 600);
            frame.setVisible(true);
        }

  • Heavy Fog - Layout Managers and the word "preferred"

    Hello again world.
    While reading the API, the tutorials, and various other documentation dealing with layout managers, I keep coming across the word "preferred" - "preferred size", "preferred width", "preferred height", and so on.
    However, I can't seem to visualize just what "preferred" means in this context.
    Do they pre-suppose that one has used the setPreferredSize() method?
    And if no set*Size() method is used, how does the parent container size its components? The literature just comes back to "preferred" this and that.
    This whole "preferred" business is, to me, circular and confusing, and the more I read, the foggier things get.
    Anyone out there with a fresh breeze?
    Thank you one and all.
    Ciao for now.

    You should never use setSize(). The size of a component is set by the LayoutManager as the components in the container are layed out. For example say you are using a GridLayout and you have 3 buttons: following text:
    small = new JButton("small");
    medium = new JButton("medium sized");
    large = new JButton("the largest button");
    The preferred size of each button is calculated to be:
    a) the size of the text +
    b) the border +
    c) the margin
    When components are added to the GridLayout all components are made the same size. The preferredSize does not change, but the size of each button is set the the largest preferredSize of the three buttons before it is painted. The GridLayout ignores the preferredSize of individual components and only cares about the largest component.
    On the other hand the FlowLayout repects the preferredSize of each component when they are layed out and painted. When using a FlowLayout you can set the preferredSize of each component to be the same by doing the following:
    small.setPreferredSize( large.getPreferredSize() );
    medium.setPreferredSize( large.getPreferredSize() );
    Every LayoutManager has rules it follows with respect to preferredSize, minimumSize and maximumSize. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Using Layout Managers.

  • How to get a specific layout with the available layout managers?

    Hi
    Not done java GUI's (approximately 5 and a half years) for a while (I havn't even touched java for ages until a few months ago), and I am a little embarrased by how much I have forgotten.
    After tring unsuccessfully several times with TableLayouts and GridBagLayouts to produce this [ [http://i32.tinypic.com/fl94kp.png] ] sort of layout, I have decided I am either being incredibly stupid, or It's a rather difficult thing to do.
    (Sorry about the crudeness of the drawing)
    Please can someone point me on the right track as to what combination of layout managers + components I should be using to achive this, or even be super kind and post a code snippet for it.
    Preferably, I would like to use just the default layout manages / components that come with java, which will allow me to continue working on the GUI in netbeans without it complaining, but I'll use external libraries if absolutely nesecarry.
    Thanks
    A completely unrelated side note, but where the heck have all my past posts and dukes gone. :(
    Edited by: DarthCrap on Aug 2, 2010 5:14 PM

    Yes, A BorderLayout did solve my problems. It appears I was being stupid after all. :)
    @Encephalopathic. Using a gridbaglayout does indeed help with the centering issue for the smaller panel on the right. I had just worked that out myself when you posted. I had been reluctant to try the gridbaglayout for that, because it caused me a load of pain when I tried using it for the original problem.
    Thanks

  • Layout managers and JTabbedPane

    I have a JTabbed pane on my 'form' on which i want to insert two tables. the problem is that the tables are overstepping the 'boundaries' i have desgned for them ,whivh i suspect is a problem with the layout managers. I just cant seem to be able to restrict the tables within the fames and have scrollpanes, both horizontal and vertical for scrolling tables. I have included the code here:
    import java.awt.*;
    import javax.swing.*;
    public class FrmProducts extends JFrame{
         private          JTabbedPane tabbedPane;
         private          JPanel          factorsTab;
         private          JPanel          productListTab;
         private          JPanel          rateHistoryTab;
         private          JTable          forexFactorsTable;
         private          JTable      otherFactorsTable;
         private      JTable          productListTable;
         public FrmProducts(){
              initializeComponents();
         public  void DisplayForm(){
              java.awt.EventQueue.invokeLater(new Runnable(){
                   public void run(){
         private void initializeComponents(){
              setTitle( "Products administration" );
              setSize( 900, 550 );
              setBackground( Color.gray );
              JPanel topPanel = new JPanel();
              topPanel.setLayout( new BorderLayout() );
              getContentPane().add( topPanel );
              Toolkit kit = getToolkit();
              Dimension screenSize = kit.getScreenSize();
              int screenWidth = screenSize.width;                         //all this is to get
              int screenHeight = screenSize.height;                    //the form size and
              Dimension windowSize = getSize();                       //centre the form on
              int windowWidth = windowSize.width;                         //the screen
              int windowHeight = windowSize.height;
              int upperLeftX = (screenWidth - windowWidth)/2;
              int upperLeftY = (screenHeight - windowHeight)/2;
              setLocation(upperLeftX, upperLeftY);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              // Create the tab pages
              createPage1();
              createPage2();
              createPage3();
              // Create a tabbed pane
              tabbedPane = new JTabbedPane();
              tabbedPane.addTab( "Facors", factorsTab );
              tabbedPane.addTab( "Products List", productListTab );
              tabbedPane.addTab( "Rate History", rateHistoryTab );
              topPanel.add( tabbedPane, BorderLayout.CENTER );
              setVisible(true);
         public void createPage1()
              factorsTab = new JPanel();
              factorsTab.setLayout( new GridLayout(2,1) );
              JPanel forexFactorsPanel;          //set up a frame with the forex factors details
              forexFactorsPanel = new JPanel();
              forexFactorsPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Forex factors"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
              String forexFactorsColumns[]={"Factor","ZAR","US$"};
              String dummyValues1[][]={ {"Costing exchange rate","485.00",   "3400.00"},
                                          {"Local product exchange rate","430.00","3000.00"},
                                          {"Duty exchange rate1","35.30",          "250.00"},
                                          {"Duty exchange rate2","35.30",          "250.00"}};
              forexFactorsTable=new JTable(dummyValues1,forexFactorsColumns);
              JScrollPane scrollPane1=new JScrollPane(forexFactorsTable);
              forexFactorsPanel.add( scrollPane1, BorderLayout.CENTER );
              factorsTab.add(forexFactorsPanel);
              JPanel otherFactorsPanel;
              otherFactorsPanel=new JPanel();
              otherFactorsPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Other factors"),
                     BorderFactory.createEmptyBorder(5,5,5,5)));
              String otherFactorsColumns[]={"Description","Value"};
              String dummyValues2[][]={{"Landing Factor",                         "1.16"},
                                            {"Duty factor",                        "1.065"},
                                            {"Loading for overseas sourcing",  "1.15"},
                                            {"Extra mark up local",             "0.0"},
                                            {"Extra mark up imports",          "0.0"}};
              otherFactorsTable=new JTable(dummyValues2,otherFactorsColumns);
              JScrollPane scrollPane2=new JScrollPane(otherFactorsTable);
              otherFactorsPanel.add(scrollPane2, BorderLayout.CENTER);
              factorsTab.add(otherFactorsPanel);
         public void createPage2()
              productListTab = new JPanel();
              productListTab.setLayout( new BorderLayout() );
              String productListColumns[]={"Code1","Code2","Code3","Sales Category","Product code","Short Description",
                                             "Long Description","Supplier/Manufacturer","Supplier Product code",
                                             "Units","Master stockist","Lead time","re-Order level","economic order qty",
                                             "APR","min shipping qty"};
              String sampleValues[][]={
                     {"AI","AC","CE","Switchgear inc Starters","AIACCE 270","Timer int pulse start 230v 2C/O 30mins",
                       "Timer interval pulse start 230v 2 closed open 30 minutes","AC/DC South Africa","IAP2 30M","each",
                       "Central Stores","2","500","5000","APR","5000"},
                       {"GI","IN","ZZ","Alternative power and accessories","GIINZZ 174","INV HT SERIES 2500W 12v/230v MOD SWV",
                            "INVERTER HT SERIES 2500W 12v/230v MODIFIED SINEWAVE","SINETECH","HT-P-2500-12","each",
                            "Central Stores","6","1000","5000","APR","10000"}
              productListTable=new JTable(sampleValues,productListColumns);
              JScrollPane scrollPane3=new JScrollPane(productListTable);
              productListTab.add(scrollPane3, BorderLayout.CENTER);
         public void createPage3()
              rateHistoryTab = new JPanel();
              rateHistoryTab.setLayout( new GridLayout( 3, 2 ) );
    }This class is called by invoking the DispalyForm() function from a main form. May you please run it and see how the 'factors' panel needs correcting and help me do that

    wondering if there's a method that can be used to show a window(i.e. dialog) within a frame (much like an MDI form). That is, all windows are shown w/in the frame's border or title bar.
    Here's what I have attempted but to no avail:
    java.awt.Dimension screen = getDefaultToolkit.getScreenSize();
    java.awt.Insets frameInsets = this.getInsets();  // frame's insets
    // set bounds of child (window)
    window1.setbounds(frameInsets.top, frameInsets.top,
       screen.width - frameInsets.top -2, screen.height - frameInsets.top -2);any help is appreciated

  • Newbie help: Layout Managers

    Hi,
    as a newbie in Swing I have difficulties with the Layout Managers... I have read the Swing tutorial but it's still a little bit complicated:
    I have a JPanel, I would like to add a JMenuBar, a JToolbar and then 2 additional JPanels at the top and on the left representing rulers like in the "How a Scroll Pane Works" example at
    http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html as well as a JTable on the right.
    How can I do this... BorderLayout containing my main JPanel at CENTER and the two JPanels representing the rulers at PAGE_START and LINE_START and the JTable at LINE_END? Where can I place then my menu- and toolbar? Can I add a BoxLayout to PAGE_START for that?
    In a posting here at the forum I read that the MenuBar should be added to the root Pane. How do I do this? When do I use Content Pane, Layered Pane and Glass Pane?
    Do you know a simple example or good tutorials at the web?
    Thanks a lot!

    Thank you for the link about the rulers.
    The rulers goes inside your custom component. It will be like the example at http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html
    Other stuffs layered like this.
    package tmp;
    import javax.swing.*;
    import java.awt.*;
    public class LayoutExample extends JFrame
        public static void main( String[] args ) throws Exception
            SwingUtilities.invokeAndWait( new Runnable()
                public void run()
                    // All the interaction with GUI do inside the MessageLoop thread!
                    LayoutExample l = new LayoutExample();
                    l.pack();
                    l.setVisible( true );
        protected JMenuBar mainMenu;
        protected JToolBar mainToolBar;
        protected RulesFeaturedScrolPane scrollPane;
        public LayoutExample() throws HeadlessException
            super();
            setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            setTitle( "Layout Example" );
            // -------------- CREATING NECESSARY CONTROLS ----------------
            // Menu
            mainMenu = new JMenuBar();
            JMenu mnuFile = mainMenu.add( new JMenu( "File" ) );
            mnuFile.add( new JMenuItem( "Open" ) );
            // ToolBar
            mainToolBar = new JToolBar();
            mainToolBar.add( new JButton( "Open" ) );
            // Customized JScrollPane (with rulers)
            scrollPane = new RulesFeaturedScrolPane();
            // -------------- END OF CREATING NECESSARY CONTROLS ----------------
            // Settig up the components
            setJMenuBar( mainMenu ); // Menu added to JFrame not to its ContentPane
            getContentPane().setLayout( new BorderLayout() );
            getContentPane().add( mainToolBar, BorderLayout.NORTH ); // ToolBar added to the ContentPane
            getContentPane().add( scrollPane, BorderLayout.CENTER ); // Other components added to ContentPane
        public static class RulesFeaturedScrolPane extends JPanel // <----------- this may extend JScrollPane
            public RulesFeaturedScrolPane()
                add( new JLabel( "TODO: this class should have rulers" ) );
    }Most interesting things starts at getContentPane().setLayout( new BorderLayout() );

  • Good book on Layout Managers...

    Hi,
    I am looking for good book on Swing. I needed to be a lot of things: a good reference, good explanations, good explanation about how Layout managers work and how to design GUIs.
    One of the biggest problems that I am having is, I think, not understanding how to layout my components and how to control each component so that the GUI doesn't look rediculous. So, I need a general explanation as well as a detailed, all in one.
    Does anyone know of a book or a set of books that would do this?
    Thanks,
    Yaakov.

    Core JFC (2nd Edition) by Kim Topely has a good section on gridbag. I really like this book. For more current books, try Java Swing, Second Edition by James Elliot et al and Swing, Second Edition by Matthew Robinson et al.
    As for layout managers, we've been using RelativeLayout and are very happy with it. Coding it is rather wordy and tedious, but it makes a lot more sense to us than gridbag's wacky concepts (weights, invisible grids with insets etc). I find it much more precise for positioning components than gridbag. Our new Swing programmers understand RelativeLayout within about 10 minutes of messing with it.
    Read about (and obtain) RelativeLayout at:
    http://www.onjava.com/pub/a/onjava/2002/09/18/relativelayout.html
    and
    http://www.onjava.com/pub/a/onjava/2002/11/27/layout2.html
    Michael Billesbach

  • I am confused by the layout of the I tunes Store...recently the entire graphics on the i tunes store pages are a complete mess, not downloading, creating odd layover and jumbled data and making it virtually impossible to access or read. Help!?

    I am confused by the layout of the I tunes Store...Ive had no problems or troubel for YEARS with the I Tunes store, but recently the entire graphics on the i tunes store pages are a complete mess, not downloading, creating odd layover and jumbled data and making it virtually impossible to access or read. I am looking for information or guidance on how to re-boot or fix this - Help?!

        I can see that this issue has been quite extensive, and frustrating, and I am so sorry for all that has happened societygirl! I would like to help you work this issue out. Please follow & send me a Direct Message, so I can get your account specifics and help finally bring this to a resolution.
    Thank you,
    MichelleH_VZW
    Follow us on Twitter @VZWSupport

  • Learning how to use Layout Managers

    The code that is included in this post is public code from the SUN tutorials. I am trying to learn how to use the layouts and add individual programs that were created to each component in the layouts.
    This is what I am exploring:
    I want to have a tabbed layout like the example TabbedPaneDemo located at http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html#TabbedPaneDemo. Below is the code.
    In one of the tabs, I want to place a button and report in it. When the button is clicked, I want the report refreshed. Eventually I will be populating an array with data. The report I want to use the example SimpleTableDemo located at http://java.sun.com/docs/books/tutorial/uiswing/examples/components/SimpleTableDemoProject/src/components/SimpleTableDemo.java. Below is the code.
    From what I have learned, you can place a container inside a container. So I should be able to place the SimpleTableDemo inside the tab 4 of the TabbedPaneDemo.
    If this is indeed correct, then how do I put these two things together? I am getting a little lost in all the code.
    Any assistance in helping me learn how to create and use layout managers would be appreciated.
    package components;
    * TabbedPaneDemo.java requires one additional file:
    *   images/middle.gif.
    import javax.swing.JTabbedPane;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JComponent;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    public class TabbedPaneDemo extends JPanel {
        public TabbedPaneDemo() {
            super(new GridLayout(1, 1));
            JTabbedPane tabbedPane = new JTabbedPane();
            ImageIcon icon = createImageIcon("images/middle.gif");
            JComponent panel1 = makeTextPanel("Panel #1");
            tabbedPane.addTab("Tab 1", icon, panel1,
                    "Does nothing");
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            JComponent panel2 = makeTextPanel("Panel #2");
            tabbedPane.addTab("Tab 2", icon, panel2,
                    "Does twice as much nothing");
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            JComponent panel3 = makeTextPanel("Panel #3");
            tabbedPane.addTab("Tab 3", icon, panel3,
                    "Still does nothing");
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            JComponent panel4 = makeTextPanel(
                    "Panel #4 (has a preferred size of 410 x 50).");
            panel4.setPreferredSize(new Dimension(410, 50));
            tabbedPane.addTab("Tab 4", icon, panel4,
                    "Does nothing at all");
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            //Add the tabbed pane to this panel.
            add(tabbedPane);
            //The following line enables to use scrolling tabs.
            tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        protected JComponent makeTextPanel(String text) {
            JPanel panel = new JPanel(false);
            JLabel filler = new JLabel(text);
            filler.setHorizontalAlignment(JLabel.CENTER);
            panel.setLayout(new GridLayout(1, 1));
            panel.add(filler);
            return panel;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = TabbedPaneDemo.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from
         * the event dispatch thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("TabbedPaneDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Add content to the window.
            frame.add(new TabbedPaneDemo(), BorderLayout.CENTER);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    //Turn off metal's use of bold fonts
              UIManager.put("swing.boldMetal", Boolean.FALSE);
              createAndShowGUI();
    package components;
    * SimpleTableDemo.java requires no other files.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    public class SimpleTableDemo extends JPanel {
        private boolean DEBUG = false;
        public SimpleTableDemo() {
            super(new GridLayout(1,0));
            String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);
            if (DEBUG) {
                table.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                        printDebugData(table);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
        private void printDebugData(JTable table) {
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            System.out.println("Value of data: ");
            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + model.getValueAt(i, j));
                System.out.println();
            System.out.println("--------------------------");
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("SimpleTableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            SimpleTableDemo newContentPane = new SimpleTableDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Before I did what you suggested, which I appreciate your input, I wanted to run the code first.
    I tried to run the SimpleTableDemo and received the following error:
    Exception in thread "main" java.lang.NoClassDefFoundError: SimpleTableDemo (wrong name: componets/SimpleTableDemo)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader...
    there are several more lines but as I was typing them out I thought that maybe the code is not written to run it in the command window. The errors seem to be around the ClassLoader. Is that correct? On the SUN example page when you launch the program a Java Web Start runs. So does this mean that the code is designed to only run in WebStart?

  • Does anyone know how to win a fight with layout manager?

    I am using the form designer in netBeans to design my page, which has a jPanel on the left and a number of controls on the right.
    My problem is that when I eventually get it to look half right at design time, it looks different at run time. The fonts are different, the combo boxes are a different height and some of my text boxes are 4 times as wide. http://RPSeaman.googlepages.com/layout.GIF shows both the design-time view and the run-time view. How can I win my fight with layout manager?

    I'd like to do an experiment where you take say 20 pairs of students of java, with each pair matched in terms of prior programming and java experience, general knowledge, etc... and set one of each pair to learn Swing using netbeans and its layout generator with the other pair learning to code Swing by hand. Then 6 months later compare their abilities. I'll bet that the code by hand group will blow the other group out of the water in terms of understanding and ability.
    Just my 2 Sheckel's worth.

  • Problem with layout and changing content

    Hi, I`m new to Swing and I have a problem with layout.
    I want to make a menu using JButtons so that depending on which button you click you`ll get different content in the window. And first of all I don`t know how to center the buttons.
    I have a JFrame called GameWindow that has a JPanel field called content. My idea was to create a JPanel with buttons and then using ActionListeners change the JPanel held in 'content'.
    Here`s the code:
    public class GameWindow extends JFrame{     
         private static final long serialVersionUID = 1L;
         private JPanel content;
         private Player player;
         public GameWindow(){          
              super("Dawn Crystal");
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              setSize((int)screenSize.getWidth(), (int)screenSize.getHeight());
              setExtendedState(MAXIMIZED_BOTH);
         public void mainMenu(){
              content = new MainMenu(this);
              Dimension dim = content.getSize();
              setLayout(null);                    
              Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
              int x = (int)((screen.getWidth() - dim.getWidth()) / 2);
              int y = (int)((screen.getHeight() - dim.getHeight()) / 2);
              int dimX = (int)dim.getWidth();
              int dimY = (int)dim.getHeight();          
              content.setBounds(x, y, 120, 120);          
              getContentPane().add(content);          
              setVisible(true);
         public void adventureScreen(){
              //so far empty
         public void createNewPlayer(){
              content.setVisible(false);
              content = new NewPlayerCreationWindow();
              getContentPane().add(content);          
              content.setVisible(true);
              //setVisible(true);
         public void setPlayer(Player p){ player=p; }
    public class MainMenu extends JPanel{     
         private static final long serialVersionUID = 1L;     
         private JPanel mainMenuButtons;
         private JButton newGame;
         private JButton loadGame;
         private JButton options;
         private JButton exit;
         public MainMenu(GameWindow par){
              mainMenuButtons = new JPanel();     
              //create buttons
              newGame = new JButton("NEW GAME");
              loadGame = new JButton("LOAD GAME");
              options = new JButton("OPTIONS");
              exit = new JButton("EXIT");
              //create action listeners
              newGame.addActionListener(new NewGameListener());
              exit.addActionListener(new ExitListener(par));     
              //add buttons to panel
              mainMenuButtons.setLayout( new GridLayout(4,1));
              mainMenuButtons.add(newGame);
              mainMenuButtons.add(loadGame);
              mainMenuButtons.add(options);
              mainMenuButtons.add(exit);     
              add(mainMenuButtons);          
    }When it displays the buttons are at the top of the frame rather than in the center - I thought that was how the default layout would behave. So that`s my first question - how to center it.
    Secondly I have NewPlayerCreationWindow written but when I call createNewPlayer() I get an empty frame - what am I doing wrong?
    Finally I`d like to ask how can I make the frame appear as maximized when the application is started? The setExtendedState(MAXIMIZED_BOTH); doesn`t help actually because the window`s height is too big and a part of window is hidden under the system bar. I want to have it maximized regardless of screen resolution.

    Use a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout.

  • Strange behaviour with Safari.

    Very strange behaviour with Safari this morning.   Pages loading piecemeal or partially.   The content only becomes viewable after the cursor has passed over the area.   Have cleared caches and reported it but I'm wondering if this is a local matter here in the UK.   Anyone suffering similar problems?    Firefox is responding perfectly normally.

    I see a reply has come back via a previous post.   As I am trying to get a response to this one I shan't reply there but I should point out that for me, this is an isolated problem.   I do use open DNS but with no track history of problems there , I can't blame that.
    In the last few minutes normality has returned.

  • Download ALV report with layout to application server

    Hi Gurus,
    I have a problem as follows:
    I have one ALV Grid report. This report is very time consuming.
    That is why, user wants this to be run in background every night and in the morning when user comes to the office that ALV report should be on user's drive in excel format.
    However, it should run with one specific variant and that variant should be dynamically populated. (I have handled this part)
    It should also apply specific layout that has many filtering conditions.
    As I can not download ALV to excel in background, I decided to download it to the Application server.
    My problem is that when run in background, in spool ALV report shows o/p with proper filter conditions that is 5 out of 20 records.
    But, when I write this report o/p to Application server, it writes all the records in there, i.e., all 20 records. It does not take into account all the filters. [:(]
    I also tried downloading spool to excel, but o/p is not neatly formatted. All columns are fying here and there.
    Any suggestion, how can I write ALV o/p to Application server with layout into consideration?
    P.S. I have searched forum for this type of query, but no apt responses.
    Thanks

    did u downloaded the report with standard option provided in the alv and checked the data? that is populating all 20 records?. if so then use coding for achieving the standard one
    at the end of selection do like this ..
    SET USER-COMMAND ' %PC' .
    and in the user-command use like this..
    case sy-ucomm.
    when '  %PC'.
    give the file name ..
    do processing ..
    endcase.

  • Want attach the XML data file with layout template in Oracle 10g

    Hi All,
    I need a help from you genius guys.
    I am genrating reports in BI with xml the procedure which I am following is as below.
    1. generating XML from the RDF
    2. creating a template in .rtf format
    3.after that loading the xml to the template then getting the required report.
    This all is doing through the given buttons
    But now my requirement is to create the gui from user can select the report and get the desire output file so how we would be able to attach the XML data file with layout template in Oracle 10g.
    If you require more detail please let me knnow.
    Thanks,
    Harry

    I am not using Oracle apps.
    I am using oracle 10g reports and I get something in it like one patch I downloded and one java code is having which creates the batch file ...still I am working on it ..
    If you will get some please share so that it will be helpful.
    Thanks,
    Harry

Maybe you are looking for

  • Getting Duplicate data Records error while loading the Master data.

    Hi All, We are getting Duplicate data Records error while loading the Profit centre Master data. Master data contains time dependent attributes. the load is direct update. So i made it red and tried to reloaded from PSA even though it is throwing sam

  • Outlook 2007 Calendar and MobileMe

    I have one need with this which is synced calendar across iphone 3G, Dell laptop running vista ultimate and mobileme. At first it worked perfectly. This morning I noticed that Outlook would show any appointment made on iphone or on mobileme calendar

  • Photo edit sliders painfully slow

    Hello, I have been trying to edit a couple of photos in iPhoto. I need to crop and edit the exposure, black/white points, etc. If I open a photo in edit mode, I can usually get one edit function complete without any problems. After that iPhoto slows

  • Oc4j-Unable to start

    I want to deploy MapViewer on Standalone OC4J. I have installed OC4J successfully on my m/c. But I am unable to start it. It gives me the below error: F:\OC4J\j2ee\home>java -jar oc4j.jar -config F:\OC4J\j2ee\home\config\server.xml Could not canonica

  • Temporary tablespace Oracle 8i

    Hi, We are having oracle 8i database on windows OS. Now, the existing TEMP TS in our database is dictionary managed. So, can i drop the existing TEMP TS and create a new one with locally managed ? if i create new TEMP TS (locally managed) then, shoul