0

I have the following structure in a frame:

Frame->contentPane panel->topPanel panel->table

This is the code:

private JPanel contentPane;
private JTable table;
private JPanel topPanel;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ShowList frame = new ShowList();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public ShowList() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 675, 433);

    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    topPanel = new JPanel();
    topPanel.setBounds(76, 76, 491, 245);
    contentPane.add(topPanel);
    topPanel.setLayout(null);

    table = new JTable();
    table.setBounds(0, 0, 491, 245);
    topPanel.add(table);
}

What I want to achieve is that when I resize the frame making the window bigger, the topPanel and the table that it is contained by this one resize also and do not stay the same size as they were before resizing the frame. I have read about Layouts but I can not make it work. Any suggestion?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
v8rs
  • 197
  • 4
  • 17
  • Why are you call ShowList() with new keyword? It is neither class nor method. – Necromancer May 09 '16 at 23:20
  • Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. 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 May 10 '16 at 02:53

1 Answers1

3

Use a LayoutManager to control the size and position of the components inside of your frame. Avoid setting the layout manager of your panels as null.

I recommend you to take a look at this link: "A Visual Guide to Layout Managers" to learn more about the different kinds of layouts you can use.

In your code, for example, I would use a BorderLayout:

contentPane.setLayout(new BorderLayout());

...

contentPane.add(topPanel, BorderLayout.CENTER);
topPanel.setLayout(new BorderLayout());

...

topPanel.add(table, BorderLayout.Center);

By the way, I suppose your class ShowList extends JFrame because methods like setDefaultCloseOperation gives you an error if not, right?

I hope it helps.

Albertpv
  • 31
  • 2