简体   繁体   中英

Small Gap between Table and ScrollPane Border Java Swing

在此处输入图片说明

I'm trying To insert a JTable into a JScrollPane and I see a small gap between the borders of the table and the scroll Pane.And on the left side the table looks to be aligned to extreme left.Can someone please help me fix this.?

Removing setAutoResizeMode(JTable.AUTO_RESIZE_OFF) is fixing that.But I Need to turn that off.

this.dataTable = new SortableTable(this);
    this.dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    this.dataTable.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
    scrollPane = new JScrollPane(dataTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setPreferredSize(new Dimension(900,250));
    scrollPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));

You simply need to set the resize mode in a listener, when the component is resized. Here is an example:

import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.TableColumn;

public class TableTest implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TableTest());
    }

    @Override
    public void run() {
        JTable table = new JTable(10, 3);
        final JScrollPane scroller = new JScrollPane(table);
        // update the resize mode when scroller is resized and window is shown
        scroller.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                Window win = SwingUtilities.windowForComponent(scroller);
                if (win != null && win.isVisible()) {
                    updateColumns(table);
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                }
            }
        });
        JFrame frm = new JFrame("Table");
        frm.add(scroller);
        frm.setSize(600, 400);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    // Transfer column widths from autoresize mode
    private void updateColumns(JTable table) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            TableColumn col = table.getColumnModel().getColumn(i);
            col.setPreferredWidth(col.getWidth());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM