How to add Two components on the right side of the splitted plane in Java Swing

131 views Asked by At

I want to add two components on the right side, i.e. JTextField and JTable on right side of the split plane. The below code is not working. What shall I do?

Here is the UI I want to look like

The result of the above code :( but if I add component (table) in the JScrollPane then it's showing table on right side.

after adding the panel into the jscrollpane I'm getting this

1

There are 1 answers

0
Abra On

Don't set the layout manager to null. Use an appropriate layout manager. I suggest using BorderLayout.

The below code is not a complete solution, just an example to get you started.

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;

public class SpliTest {
    private void buildAndDisplayGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTree tree = new JTree();
        JScrollPane treeScrollPane = new JScrollPane(tree);
        JTable table = new JTable(2, 4);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        JScrollPane tableScrollPane = new JScrollPane(table);
        JTextField textField = new JTextField(20);
        JPanel right = new JPanel(new BorderLayout());
        right.add(textField, BorderLayout.PAGE_START);
        right.add(tableScrollPane, BorderLayout.CENTER);
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScrollPane, right);
        frame.add(splitPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new SpliTest().buildAndDisplayGui());
    }
}

Here is a screen capture.

screen capture