How to use layout managers

Hi ,
I designed a JFrame. If i enlrged the frame widow, the components are not arranged properly. How can i arrange them.
narayana

the components are not arranged properly.That statement mean absolutely nothing. They are arranged properly according the to the rules of the Layout Manager you are using.
If it is not layed out the way you want then you need to use a different Layout Manager or combination of Layout Managers. Since you don't define what "properly" means you are on your own.
Read the tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers

Similar Messages

  • 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?

  • Is it possible to make a javafx ui application without using layout managers ?

    I want to make an user interface application without using layout managers. In my previous attempt i made an application in java swing. There i used the setBounds() function. Is there any function like setBounds() in javafx ?

    There really isn't any more to it than that.
    Again, I have no idea why you would do things this way (either in JavaFX or in Swing), but:
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Pane;
    import javafx.stage.Stage;
    public class ManualPositioningExample extends Application {
        @Override
        public void start(Stage primaryStage) {
            final Pane root = new Pane();
            final Button button = new Button("Click me");
            final Label label = new Label("A Label");
            final TextField textField = new TextField();
            root.getChildren().addAll(button, label, textField);
            label.relocate(25, 25);
            textField.relocate(75, 25);
            textField.setPrefSize(100, 20);
            button.relocate(25, 50);
            button.setPrefSize(150, 20);
            Scene scene = new Scene(root, 400, 200);
            primaryStage.setScene(scene);
            primaryStage.show();
        public static void main(String[] args) {
            launch(args);

  • Arranging objects on a JPanel (Not sure how to use Layouts)

    Hey guys,
    It was suggested to me to use layouts to arrange Jbuttons fields and such. I tryed following the Java tutorial on the topic but I can't seem to follow it. If someone might look at my code and give me some pointers to arrange it. I'm not too familiar with the arrangement of objects, and what I do know is from BlueJ. This is is my code. Thanks in advance.
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    public class SonnetTest {
        public static void main(String[] args) {
             JFrame frame = new JFrame();
             frame.setResizable(false);
             //Creates a new PoemGenerator object
             final PoemGenerator vanorden = new PoemGenerator();
             //Sets the standard width of the fields
             final int FIELD_WIDTH = 20;
             //Initializes the input fields for author and title
             final JTextField authorField = new JTextField(FIELD_WIDTH);
             final JTextField titleField = new JTextField(FIELD_WIDTH);
             //Labels the input fields
             final JLabel titleLabel = new JLabel("Title");
             final JLabel authorLabel = new JLabel("Author");
             //Initializes the display area
             final JTextArea display = new JTextArea();
             display.setText(vanorden.verse);
             display.setEditable (false);
              //Initializes the submit and new poem buttons
             JButton submitButton = new JButton("Submit");
             JButton newPoemButton = new JButton("New Poem");
             //Constructs the panel      
             JPanel panel = new JPanel();
             panel.add(display);
             panel.add(authorLabel);
             panel.add(authorField);
             panel.add(titleLabel);
             panel.add(titleField);
             panel.add(submitButton);
             panel.add(newPoemButton);
             frame.add(panel);
             submitButton.setSize(5000,50);
             //Creates a listener to be used when the submit button is pressed
             class CheckAnswerListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       String authorGuess = authorField.getText();
                       //Compares the input with the correct (ignoring case)
                       if(authorGuess.compareToIgnoreCase(vanorden.Poet) == 0){
                            display.setText("Correct!");
                       else{
                            display.setText("Incorrect, the poet's name is " + vanorden.Poet + ".");
             ActionListener listener = new CheckAnswerListener();
             submitButton.addActionListener(listener);
             //Creates a listener to be used when the new poem button is pressed
             class NewPoemListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       PoemGenerator vanorden = new PoemGenerator();
                       display.setText(vanorden.verse);     
             ActionListener listener2 = new NewPoemListener();
             newPoemButton.addActionListener(listener2);
             //Sets the panel's size
             frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
        //Sets the variables to be used as dimensions for the window
        private static final int FRAME_WIDTH = 500;  //Good width for input fields
        private static final int FRAME_HEIGHT = 100;
    }

    Thank you. I put each of the components into its on panel, just for the sake of experimentation. The thing is though that only one panel shows up. How do I arrange them? I keep getting the error:
    cannot find symbol method setLayout(java.awt.GridLayout)
    Here is my revised code. Thanks for putting up with me.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    public class SonnetTest {
        public static void main(String[] args) {
             JFrame frame = new JFrame();
             frame.setResizable(false);
             //Creates a new PoemGenerator object
             final PoemGenerator vanorden = new PoemGenerator();
             //Sets the standard width of the fields
             final int FIELD_WIDTH = 20;
             //Initializes the input fields for author and title
             final JTextField authorField = new JTextField(FIELD_WIDTH);
             final JTextField titleField = new JTextField(FIELD_WIDTH);
             //Labels the input fields
             final JLabel titleLabel = new JLabel("Title");
             final JLabel authorLabel = new JLabel("Author");
             //Initializes the display area
             final JTextArea display = new JTextArea();
             display.setText(vanorden.verse);
             display.setEditable (false);
              //Initializes the submit and new poem buttons
             JButton submitButton = new JButton("Submit");
             JButton newPoemButton = new JButton("New Poem");
             //Constructs the panel      
             JPanel panel = new JPanel();
             panel.add(display);
             JPanel panel2 = new JPanel();
             panel2.add(authorLabel);
             JPanel panel3 = new JPanel();
             panel3.add(authorField);
             JPanel panel4 = new JPanel();
             panel4.add(titleLabel);
             JPanel panel5 = new JPanel();
             panel5.add(titleField);
             JPanel panel6 = new JPanel();
             panel6.add(submitButton);
             JPanel panel7 = new JPanel();
             panel7.add(newPoemButton);
             frame.add(panel);
             frame.add(panel2);
             frame.add(panel3);
             frame.add(panel4);
             frame.add(panel5);
             frame.add(panel6);
             frame.add(panel7);
             submitButton.setSize(5000,50);
             //Creates a listener to be used when the submit button is pressed
             class CheckAnswerListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       String authorGuess = authorField.getText();
                       //Compares the input with the correct (ignoring case)
                       if(authorGuess.compareToIgnoreCase(vanorden.Poet) == 0){
                            display.setText("Correct!");
                       else{
                            display.setText("Incorrect, the poet's name is " + vanorden.Poet + ".");
             ActionListener listener = new CheckAnswerListener();
             submitButton.addActionListener(listener);
             //Creates a listener to be used when the new poem button is pressed
             class NewPoemListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       PoemGenerator vanorden = new PoemGenerator();
                       display.setText(vanorden.verse);     
             ActionListener listener2 = new NewPoemListener();
             newPoemButton.addActionListener(listener2);
             //Sets the panel's size
             frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
        //Sets the variables to be used as dimensions for the window
        private static final int FRAME_WIDTH = 260;  //Good width for input fields
        private static final int FRAME_HEIGHT = 200;
    }

  • How to use layout of one view(some part) in another view

    Hi All,
                 I need how to use a layout of one view(some part) in another view.if anybody knows, help me.
    Ex : I took two views.but some part of layout in first view is also needed in second view.Is it possible.
    Thank You,
    Anupama.

    Hi,
    Whichever common ui elements you want to put in both views. Keep them in one view.
    Now create two views which You want to display.( i.e you have to create three views in that two only will be used for display purpose ) In that both views add viewcontainer ui element and embedd that view which has common UIs. And Then add rest uncommon UIs in both views.
    I hope it helps.
    Regards,
    Rohit

  • How to use layouts in PSE 13?

    HI! I used to have PSE 8 and I love to create collages. There I could resize the size and rotate the canvas and select different frames but sadly PSE 13 has one choice for collages and it doesn't let me resize the canvas on my desire size (8x10 size). when I have the collage open on the bottom right hand side says "layouts" and when I choose one it doesn't let me resize it or rotate. i am very sad about this. Can you help me find a way that will give me more choices in regards of collages? Thanks!

    PSE 13 is different from PSE 8 in that there is not a thing you can do to a collage in Create that you can't do better and more easily in the regular editor. Just create a blank file the size and resolution you want, get out the graphics panel, and have at it.

  • How to use layout:treeview in struts application

    hi all,
    i am creating a treeview in which whtever folder & subfolder name i m getting it from database
    now i want to create dynamic treeview. i.e. if i click on the + sign besides folder then only it will display or load the subfolder in the page.
    can anybody tell me how to that.
    thnx in adv.
    ritu

    hi all,
    pls help me out.
    is there anybody who has worked on layout treeview in struts
    regards,
    ritu

  • Resizing using layout managers

    Hi,
    I have have a box layout and in the CENTER i have a card layout purely with buttons. The frame also has a menu bar.
    However, when i resize the window, the buttons do resize but the menu is now shown across the buttons and also in the correct place. When the window is resized, the text of the buttons looks all over the place.
    I don't have a repaint method. Do i need it to resolve this issue?

    I tried the repaint method. I noticed that when the window is fully resized, if i hover over the buttons, the menu bar is also shown inside the button text.
        public mainMenu() {
            try {
                jbInit();
                procAddActionListeners();
                this.show();
            } catch (Exception e) {
                e.printStackTrace();
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(borderLayout2);
            this.setSize(new Dimension(700, 500));
            this.setTitle("Main Menu");
            this.setJMenuBar(mnuMain);
            lblTitle.setText("Please Select Your Option");
            lblTitle.setFont(new Font("Arial", 1, 20));
            lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
            jLabel1.setSize(new Dimension(60, 448));
            jLabel1.setText("              ");
            jLabel2.setText("              ");
            mainPanel.setLayout(new GridLayout(6,1,20,20));
            lblTop = new JLabel();
            lblBottom = new JLabel();
            lblTop.setText("  ");
            lblBottom.setText("  ");
            mnuFile.setText("File");
            mnuEdit.setText("Edit");
            mnuView.setText("View");
            mnuMenu.setText("Menu");
            mnuSearch.setText("Search");
            mnuFileNew.setText("New");
            mnuFileSave.setText("Save");
            mnuFileSave.setToolTipText("null");
            mnuFileExport.setText("Export");
            mnuFilePrint.setText("Print");
            mnuFilePrintPreview.setText("Print Preview");
            mnuFileClose.setText("Close");
            mnuFileExit.setText("Exit");
            mnuEditUndo.setText("Undo");
            mnuEditRedo.setText("Redo");
            mnuEditCut.setText("Cut");
            mnuEditCopy.setText("Copy");
            mnuEditPaste.setText("Paste");
            mnuEditDelete.setText("Delete");
            mnuInsert.setText("Insert");
            mnuTools.setText("Tools");
            mnuToolsOptions.setText("Options");
            mnuSpecial.setText("Special");
            mnuHelp.setText("Help");
            mnuSearchMembership.setText("Membership");
            mnuSearchMember.setText("Member");
            mnuSearchStaff.setText("Staff");
            mnuSearchBarcode.setText("Barcode");
            mnuInsertNonpayer.setText("Non-Payer");
            mnuInsertRating.setText("Rating");
            mnuSpecialWebcam.setText("Webcam");
            mnuHelpAbout.setText("About");
            mnuHelpHelp.setText("Help");
            mnuViewToolbarChk.setText("Toolbar");
            mnuViewStatusbarChk.setText("Statusbar");
            btnMembership.setText("Memberships");
            btnMembers.setText("Members");
            btnEquipment.setText("Equipment");
            btnStaff.setText("Staff");
            mainPanel.add(lblTop);
            mainPanel.add(btnMembership);
            mainPanel.add(btnMembers);
            mainPanel.add(btnEquipment);
            mainPanel.add(btnStaff);
            mainPanel.add(lblBottom);
            this.getContentPane().add(lblTitle, BorderLayout.NORTH);
            this.getContentPane().add(mainPanel, BorderLayout.CENTER);
            this.getContentPane().add(jLabel1, BorderLayout.WEST);
            this.getContentPane().add(jLabel2, BorderLayout.EAST);
            mnuFile.add(mnuFileNew);
            mnuFile.addSeparator();
            mnuFile.add(mnuFileSave);
            mnuFile.addSeparator();
            mnuFile.add(mnuFileExport);
            mnuFile.addSeparator();
            mnuFile.add(mnuFilePrint);
            mnuFile.add(mnuFilePrintPreview);
            mnuFile.addSeparator();
            mnuFile.add(mnuFileClose);
            mnuFile.add(mnuFileExit);
            mnuMain.add(mnuFile);
            mnuEdit.add(mnuEditUndo);
            mnuEdit.add(mnuEditRedo);
            mnuEdit.addSeparator();
            mnuEdit.add(mnuEditCut);
            mnuEdit.add(mnuEditCopy);
            mnuEdit.add(mnuEditPaste);
            mnuEdit.addSeparator();
            mnuEdit.add(mnuEditDelete);
            mnuMain.add(mnuEdit);
            mnuView.add(mnuViewToolbarChk);
            mnuView.add(mnuViewStatusbarChk);
            mnuMain.add(mnuView);
            mnuMain.add(mnuMenu);
            mnuSearch.add(mnuSearchMembership);
            mnuSearch.add(mnuSearchMember);
            mnuSearch.addSeparator();
            mnuSearch.add(mnuSearchStaff);
            mnuSearch.addSeparator();
            mnuSearch.add(mnuSearchBarcode);
            mnuMain.add(mnuSearch);
            mnuInsert.add(mnuInsertNonpayer);
            mnuInsert.addSeparator();
            mnuInsert.add(mnuInsertRating);
            mnuMain.add(mnuInsert);
            mnuTools.add(mnuToolsOptions);
            mnuMain.add(mnuTools);
            mnuSpecial.add(mnuSpecialWebcam);
            mnuMain.add(mnuSpecial);
            mnuHelp.add(mnuHelpAbout);
            mnuHelp.addSeparator();
            mnuHelp.add(mnuHelpHelp);
            mnuMain.add(mnuHelp);
        private void procAddActionListeners(){
          //  this.addWindowListener();
            btnMembership.addActionListener(this);
            btnMembers.addActionListener(this);
            btnEquipment.addActionListener(this);
            btnStaff.addActionListener(this);
        public void actionPerformed (ActionEvent e){
            String s = e.getActionCommand();
       public static void main(String [] args) {
            JFrame mainMenu = new mainMenu();
        public void repaint(){
            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
    Any ideas?

  • How to make fixed width size on grid layout managers.,

    hiya,
    my gird contains labels but whenever the labels has different width on their texts, the grid adopts to the width of the text, how not to?
    many thanks! :)

    Thats the way the GridLayout works, each cell is the same size. The size is determined by the largest component added to the grid.
    Here is the Swing tutorial on "Using Layout Managers".
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

  • 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

  • How to use a table to layout af components?

    i've been trying to figure out how to use a regular table
    to layout some components that are not databound ..
    I couldn't figure out how to use simple html
    Ie: the verbatim tag didn't like having unclosed tags...
    so i couldn't compile
    <f:verbatim>
    <table><tr><td>
    </f:verbatim>
    then my af controls
    i tried using a <af:table value="{1,2}">
    so it could render a row...
    but there is no <TR> equivalent... and it shows the column headings..
    and the presence of the table is too obvious (scroll bar .etc. and have
    to do a ton of css classes to make headers disappear..etc)
    anyway to nicely layout controls?

    Try the h:panelGrid component.
    http://www.jsftoolbox.com/documentation/help/12-TagReference/html/h_panelGrid.html

  • How to use search help in layout of se51

    how to use search help in layout of se51.

    Hi,
      One of the important features of screens is that they can provide users with lists of possible entries for a field. There are three techniques that you can use to create and display input help:
    Definition in the ABAP Dictionary
    In the ABAP Dictionary, you can link search helps to fields. When you create screen fields with reference to ABAP Dictionary fields, the corresponding search helps are then automatically available. If a field has no search help, the ABAP Dictionary still offers the contents of a check table, the fixed values of the underlying domain, or static calendar or clock help.
    Definition on a screen
    You can use the input checks of the screen flow logic, or link search helps from the ABAP Dictionary to individual screen fields.
    Definition in dialog modules
    You can call ABAP dialog modules in the POV event of the screen flow logic and program your own input help.
    These three techniques are listed in order of ascending priority. If you use more than one technique at the same time, the POV module calls override any definition on the screen, which, in turn, overrides the link from the ABAP Dictionary.
    However, the order of preference for these techniques should be the order listed above. You should, wherever possible, use a search help from the ABAP Dictionary, and only use dialog modules when there is really no alternative. In particular, you should consider using a search help exit to enhance a search help before writing your own dialog modules.
    Input help from ABAP dictoinary
    http://help.sap.com/saphelp_47x200/helpdata/en/9f/dbaa5435c111d1829f0000e829fbfe/content.htm
    Field Help on the Screen
    http://help.sap.com/saphelp_47x200/helpdata/en/9f/dbaa6135c111d1829f0000e829fbfe/content.htm
    Field Help in Dialog Modules.
    http://help.sap.com/saphelp_47x200/helpdata/en/9f/dbaac935c111d1829f0000e829fbfe/content.htm
    Regards,
    Vara

  • What are the best Layout Managers to use in these cases?

    (1) I have a form with labels at text fields. Right now, there are three lables and three text fields. There is a good chance (90%) that I will need to add additional fields and labels, so it needs to be expandable. Now, all of these features reside on a JPanel which resides as a tab in a JTabbedPane which resides in a JFrame. Regardless of the size of the JFrame, the contents of the JPanel should be their default sizes. Also - if anyone says SpringLayout, no - I use the code for the SpringForm from the Java tutorial, and I always get exceptions related to arrays (out of bounds, IIRC - I don't have the code on this PC).
    (2) I have another form (of sorts) that, right now, includes only one row of three components (a label, a text field, and a button). However, There's a 99% chance I'll be adding other things to this menu. What's a good layout manager that will help me keep everything their default sizes as well as add more "rows" of components that might have different numbers of components in them?

    If you really want advice then you need to learn how to specify requirements.
    1) "I have a form with labels at text fields. Right now, there are three lables and three text fields."
    and how do you want the component layed out????
    a) do you want all the fields on a single line, in which case you would use a FlowLayout or a horizontal BoxLayout.
    b) do you want all the fields on separate lines, in which case you could use a vertical BoxLayout
    c) do you want pairs of label and text fields on a single line? If so, then do you want each lable and text field in a column? If so then do you want the labels left or right justified, or centered? You have many options depending on your requirements:
    - use a GridBagLayout.
    - use a GridLayout. Each cell will be the same size but you can add your components to a JPanel first and then add the panel to the GridLayout. In this case the panel will be resized, but the component will retain its original size.
    - use a BorderLayout.. The West will contain a panel of your labels in a GridLayout. The East will be the text fields in a GridLayout.
    - figure out how to use the SpringLayout correctly. The demo doesn't cause errors, so its obviously your code that is causing the problem. Do some debugging to fix your problem.
    - write your own LayoutManager. I wrote one which I called ColumnLayout, which I posted in the forum somewhere. It is like the GridLayout excepct each column is the widht of the widest component in the column and each row is the height of the talles component in the row.
    2) Learn to mix and match LayoutManagers.
    includes only one row of three componentsSounds like a FlowLayout
    as well as add more "rows" of components that might have different numbers of components in them? Sounds like another FlowLayout.
    Each row would then be added to a main panel using a vertical BoxLayout.
    The point is you are not restricted to a single LayoutManager for a form. Mix and match to get the effect you desire.

  • 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

Maybe you are looking for