By Sagar

2011-04-11 12:35:34 8 Comments

I want to add JTable into JPanel whose layout is null. JPanel contains other components. I have to add JTable at proper position.


@sergpank 2012-10-04 08:34:14

JTable should be added into the JScrollPane which actually should be added into the JPanel.

The JPanel should have some layout manager.

If you don't care about the precision of components size you can use pure BorderLayout and combine it with FlowLayout and GridLayout. if you need precision - use jgoodies FormLayout.

The FormLayout is really tricky one, but you can play a little with WindowBuilder (which is embedded into Eclipse) and a look at the code it generates. It may look complicated but it is just an ignorance.

Good luck.

@Axel Podehl 2017-06-07 09:30:12

First, you should seriously consider other Layout managers, for example the BorderLayoutManager (new JPanel(new BorderLayout())) is a good start.

Also when designing your dialog, remember that you can and should nest your layouts: one JPanel inside another JPanel (e.g. a GridLayout inside a BorderLayout). Please note: a 'good' dialog should resize properly, so that if the user resizes your Frame, you want to automatically extend your information objects such as your table, and not show large areas of JPanel background. That's something you cannot achieve with a NullLayout.

But there are probably cases - somewhere in this big world - where a NullLayout is just the thing. So here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableInNullLayout
  public static void main(String[] argv) throws Exception {

      DefaultTableModel model = new DefaultTableModel(
          new String[][] { { "a", "123"} , {"b", "456"} }, 
          new String[] { "name", "value" } );

      JTable t = new JTable(model);

      JPanel panel = new JPanel(null);

      JScrollPane scroll = new JScrollPane(t);
      scroll.setBounds( 0, 20, 150, 100 ); // x, y, width, height

      JFrame frame = new JFrame();
      frame.setPreferredSize( new Dimension(200,200));

@Kevin Wang 2017-01-11 14:59:00

When a component have a "null" layout, you have to manage the layout by yourself, that means you have to calculate the dimensions and locations for the children of the component to decide where they are drawn. Quite tedious unless it is absolutely necessary.

If you really want that fine-grained control, maybe try GridBagLayout first before going mudding with the UI arrangement.

@Andrew Thompson 2011-04-12 04:02:41

Nested/Combination Layout Example

The Java Tutorial has comprehensive information on using layout managers. See the Laying Out Components Within a Container lesson for further details.

One aspect of layouts that is not covered well by the tutorial is that of nested layouts, putting one layout inside another to get complex effects.

The following code puts a variety of components into a frame to demonstrate how to use nested layouts. All the layouts that are explicitly set are shown as a titled-border for the panel on which they are used.

Notable aspects of the code are:

  • There is a combo-box to change PLAF (Pluggable Look and Feel) at run-time.
  • The GUI is expandable to the user's need.
  • The image in the bottom of the split-pane is centered in the scroll-pane.
  • The label instances on the left are dynamically added using the button.

Nimbus PLAF

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;

/** A short example of a nested layout that can change PLAF at runtime.
The TitledBorder of each JPanel shows the layouts explicitly set.
@author Andrew Thompson
@version 2011-04-12 */
class NestedLayoutExample {

    public static void main(String[] args) {

        Runnable r = new Runnable() {

            public void run() {
                final JFrame frame = new JFrame("Nested Layout Example");

                final JPanel gui = new JPanel(new BorderLayout(5,5));
                gui.setBorder( new TitledBorder("BorderLayout(5,5)") );

                //JToolBar tb = new JToolBar();
                JPanel plafComponents = new JPanel(
                    new FlowLayout(FlowLayout.RIGHT, 3,3));
                    new TitledBorder("FlowLayout(FlowLayout.RIGHT, 3,3)") );

                final UIManager.LookAndFeelInfo[] plafInfos =
                String[] plafNames = new String[plafInfos.length];
                for (int ii=0; ii<plafInfos.length; ii++) {
                    plafNames[ii] = plafInfos[ii].getName();
                final JComboBox plafChooser = new JComboBox(plafNames);

                final JCheckBox pack = new JCheckBox("Pack on PLAF change", true);

                plafChooser.addActionListener( new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        int index = plafChooser.getSelectedIndex();
                        try {
                                plafInfos[index].getClassName() );
                            if (pack.isSelected()) {
                        } catch(Exception e) {
                } );

                gui.add(plafComponents, BorderLayout.NORTH);

                JPanel dynamicLabels = new JPanel(new BorderLayout(4,4));
                    new TitledBorder("BorderLayout(4,4)") );
                gui.add(dynamicLabels, BorderLayout.WEST);

                final JPanel labels = new JPanel(new GridLayout(0,2,3,3));
                    new TitledBorder("GridLayout(0,2,3,3)") );

                JButton addNew = new JButton("Add Another Label");
                dynamicLabels.add( addNew, BorderLayout.NORTH );
                addNew.addActionListener( new ActionListener(){

                    private int labelCount = 0;

                    public void actionPerformed(ActionEvent ae) {
                        labels.add( new JLabel("Label " + ++labelCount) );
                } );

                dynamicLabels.add( new JScrollPane(labels), BorderLayout.CENTER );

                String[] header = {"Name", "Value"};
                String[] a = new String[0];
                String[] names = System.getProperties().
                String[][] data = new String[names.length][2];
                for (int ii=0; ii<names.length; ii++) {
                    data[ii][0] = names[ii];
                    data[ii][1] = System.getProperty(names[ii]);
                DefaultTableModel model = new DefaultTableModel(data, header);
                JTable table = new JTable(model);
                try {
                    // 1.6+
                } catch(Exception continuewithNoSort) {
                JScrollPane tableScroll = new JScrollPane(table);
                Dimension tablePreferred = tableScroll.getPreferredSize();
                    new Dimension(tablePreferred.width, tablePreferred.height/3) );

                JPanel imagePanel = new JPanel(new GridBagLayout());
                    new TitledBorder("GridBagLayout()") );

                BufferedImage bi = new BufferedImage(
                Graphics2D g = bi.createGraphics();
                GradientPaint gp = new GradientPaint(
                    20f,20f,, 180f,180f,Color.yellow);
                ImageIcon ii = new ImageIcon(bi);
                JLabel imageLabel = new JLabel(ii);
                imagePanel.add( imageLabel, null );

                JSplitPane splitPane = new JSplitPane(
                    new JScrollPane(imagePanel));
                gui.add( splitPane, BorderLayout.CENTER );



                try {
                    // 1.6+
                } catch(Throwable ignoreAndContinue) {


Other Screen Shots

Windows PLAF

Mac OS X Aqua PLAF

Ubuntu GTK+ PLAF

@S.B 2016-02-25 11:53:15

        JPanel p = new JPanel(new BorderLayout());
        WindowEvent we = new WindowEvent(this, WindowEvent.WINDOW_CLOSED);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
        // Create columns names
        String columnNames[] = { "FirstCol", "SecondCol",
                "ThirdCol", "FourthCol" };
        dataModel = new DefaultTableModel();
        for (int col = 0; col < columnNames.length; col++) {
        // Create a new table instance
        table = new JTable(dataModel);
        table.setPreferredScrollableViewportSize(new Dimension(200, 120));

        // Add the table to a scrolling pane
        scrollPane = new JScrollPane(table,
        scrollPane.setPreferredSize(new Dimension(700, 700));
        JPanel jpResultPanel = new JPanel();
                BorderFactory.createEtchedBorder(), "Result",
                TitledBorder.CENTER, TitledBorder.TOP));
        setSize(720, 720);

Try this.

@krpa 2015-11-26 12:03:55

JFrame frame = new JFrame("Sample Frame");
frame.setSize(600, 600);
    JPanel panel = new JPanel();
        DefaultTableModel dfm = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(dfm);
        JScrollPane scrollPane = new JScrollPane(table);

table model depends on your requirement

@Leo 2014-07-28 11:25:08

JPanel panel = new JPanel();
JTable table = new JTable(rowData, colData);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
panel.setSize(800, 150);

Hope this helps.

@kleopatra 2014-07-29 05:38:09

no ... three errors in three consecutive lines and not solving the (bad as it is) requirement

@Leo 2014-07-30 06:09:52

use frame instead of panel and try.

@kleopatra 2014-07-30 22:10:45

you didn't even try to find your errors, did you? Sometimes (like now) I really would like to have as many downvotes as there are errors in the code/answer ..

@Leo 2014-07-31 06:32:55

which three lines? rowdata and coldata you have to add.

@kleopatra 2014-08-02 04:22:34

4, 5, 6 (and the last)

@Leo 2014-08-04 06:12:26

Sorry boss, it doesn't give any error for me. As I told you have to give your rowdata and coldata and import proper package.

@kleopatra 2014-08-04 08:05:35

A: take it for granted that there is something wrong with those lines. B: find out what it is (no rocket science, just a bit of searching). C: you improved your skills and your knowledge. Or refuse to learn, your choice obviously ;-) Bye.

@Sankar 2012-09-22 13:01:09

You can make use of the following code. To add JTable to JPanel.

JPanel panel = new JPanel();
String data[][] = {{"1.", "ABC"}, {"2.", "DEF"}, {"3.", "GHI" }};
String col[] = {"Sr. No", "Name"};
JTable table = new JTable(data,col);
table.setBounds(100, 100, 100, 80);

@user592704 2011-07-18 16:36:29

As I can remember, the null layout means an absolute position so it will be pretty hard you to count the X point for your JTable left upper corner location. But if you just want to have all panel components one by one you can use FlowLayout() manager as

JPanel panel=new JPanel(new FlowLayout());
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());

or if you need to fill the panel you should use GridLayout() as...

int x=2,y=2;
JPanel panel=new JPanel(new GridLayout(y,x));
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());

Good luck

@Boro 2011-04-11 14:47:42

If you are using null layout manager you always need to set the bounds of a component. That is the problem in your case.

You should do what everyone suggest here and go and use some layout manager believe they save time. Go and check out the tutorial in @jzd's post.

Enjoy, Boro.

@jzd 2011-04-11 12:45:42

Don't use a null layout. Learn to use LayoutManagers:

LayoutManagers allow you to properly handle things window resizing or dynamic component counts. They might seem intimidating at first, but they are worth the effort to learn.

Related Questions

Sponsored Content

40 Answered Questions

[SOLVED] How to get screen dimensions as pixels in Android

61 Answered Questions

[SOLVED] Avoiding != null statements

43 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

58 Answered Questions

[SOLVED] How to create a memory leak in Java?

66 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 4095732 View
  • 3531 Score
  • 66 Answer
  • Tags:   java random integer

35 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3918773 View
  • 1655 Score
  • 35 Answer
  • Tags:   java string split

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

30 Answered Questions

[SOLVED] Android Drawing Separator/Divider Line in Layout?

  • 2011-02-19 08:59:28
  • Androider
  • 704248 View
  • 684 Score
  • 30 Answer
  • Tags:   android layout draw

14 Answered Questions

[SOLVED] How to add an image to a JPanel?

Sponsored Content