1

I am developing a GUI form in java. In that I am adding two panels in main frame which has FlowLayout. But now I want to change the size of panels and I tried changing using setsize(), and I can see no difference.

Here is my code:

public class Main_window extends JFrame implements ActionListener {

    JFrame MainFrm = new JFrame("MCQ Generator");
    JPanel LeftPanel = new JPanel();
    JPanel RightPanel = new JPanel();
    JButton BrowseButton = new JButton("Browse/Open");
    TextArea ta1 = new TextArea();
    TextArea ta2 = new TextArea();
    JButton ClearWindow = new JButton("Clear Window");
    JButton generateButton = new JButton("Generate MCQs");
    String fname;

    Main_window() {
        MainFrm.setLayout(new FlowLayout(FlowLayout.LEFT));
        MainFrm.setSize(1050, 400);
        MainFrm.add(LeftPanel, FlowLayout.LEFT);
        MainFrm.add(RightPanel);
        LeftPanel.setLayout(new BorderLayout(30, 30));
    //LeftPanel.setSize(10, 10);
        //RightPanel.setSize(10, 10);
        RightPanel.setLayout(new BorderLayout(40, 40));
        LeftPanel.setOpaque(true);
        LeftPanel.setBackground(Color.LIGHT_GRAY);
        LeftPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        RightPanel.setOpaque(true);
        RightPanel.setBackground(Color.LIGHT_GRAY);
        RightPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        JPanel InnerPanel = new JPanel();
        InnerPanel.setLayout(new FlowLayout());
        InnerPanel.setBackground(Color.LIGHT_GRAY);
        InnerPanel.add(new JLabel("Choose File: "));
        LeftPanel.add(InnerPanel, BorderLayout.NORTH);
        LeftPanel.add(ta1, BorderLayout.CENTER);
        RightPanel.add(new JLabel("Questions Generated:"), BorderLayout.NORTH);
        RightPanel.add(ta2, BorderLayout.CENTER);
    //ta1.setSize(10, 100);
        //ta2.setSize(10, 100);
        BrowseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "Text Documents(*.txt)", "txt");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(LeftPanel);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    System.out.println("You choose to open this file: " + chooser.getCurrentDirectory() + "\\" + chooser.getSelectedFile().getName());
                    fname = new String(chooser.getCurrentDirectory() + "\\" + chooser.getSelectedFile().getName());
                    try {
                        Jdbc_conn.truncateInputTable(ta1);
                        displayInput(fname);
                        //Jdbc_conn.truncateInputTable(ta1);
                        Give_input.getInput(fname);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        });
        InnerPanel.add(BrowseButton);
        LeftPanel.add(generateButton, BorderLayout.SOUTH);
        generateButton.addActionListener(this);
        RightPanel.add(ClearWindow, BorderLayout.SOUTH);
        ClearWindow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                try {
                    Jdbc_conn.truncateMcqAndNew_nountab(ta2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        MainFrm.setVisible(true);
        MainFrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Priyanka K.
  • 11
  • 1
  • 2
  • 3
    Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is a `CONSTANT_ALL_UPPER`) and use it consistently. – Andrew Thompson Jan 28 '15 at 12:29

2 Answers2

2

Usually, when setSize() doesn't work, try with setPreferredSize().

In this case, as the Oracle tutorial says: "The FlowLayout class puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, the FlowLayout class uses multiple rows. If the container is wider than necessary for a row of components, the row is, by default, centered horizontally within the container. To specify that the row is to aligned either to the left or right, use a FlowLayout constructor that takes an alignment argument. Another constructor of the FlowLayout class specifies how much vertical or horizontal padding is put around the components."

Giulio Biagini
  • 935
  • 5
  • 8
  • 1
    [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Jan 28 '15 at 10:43
  • No. As the [oracle tutorial](http://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html) says: *"The FlowLayout class puts components in a row, sized at their **preferred size**."* – Giulio Biagini Jan 28 '15 at 10:46
  • 2
    Absolutely, but it is also generally discouraged to use `setPreferredSize` as it can have adverse affects on how a component might be laid out on different platforms. It would be better to use a layout manager which gives you more control over the lay out, like `GridBagLayout` for example. – MadProgrammer Jan 28 '15 at 10:54
  • 2
    1) See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) 2) Further to the answer of @MadProgrammer.. Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with **layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556).** – Andrew Thompson Jan 28 '15 at 12:28
2

First, take a look at Laying Out Components Within a Container for information about the layout API.

You should never (okay, very rarely) need to call setSize on a component directly. Any component under the management of a layout manager will be sized to meet the requirements of the layout manager, so generally speaking, call setSize is a pointless exercise

You might be able effect the size of a component by using an EmptyBorder, but this is just adding internal padding to the component, which might not be desirable.

Another choice is to use a different layout manager which gives you more control, something like MigLayout or GridBagLayout, but this will increase the general complexity of the code.

The other choice would be to override the getPreferredSize method of the components you want to size and return the values you want to use. Be warned though, this is not to be done lightly or without a lot of consideration to "why" you want to change the default size. The main reason is, different platforms can change the amount of space any component might need in order to be laid out correctly.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366