Question

Given

import javax.swing.*;

public class TestCornerComponent {

    public static void main(String args[]) {
        JTable table = new JTable();
        final JScrollPane scrollPane = new JScrollPane(table);

        /* button to put in corner */
        JButton cornerButton = new JButton("#");
        scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
            cornerButton);

        scrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);


        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame("Test corner component");
                frame.getContentPane().add(scrollPane);
                frame.setVisible(true);
            }
        });
    }
}

how might one make the cornerButton always visible, irrespective of whether the JTable is empty or not?

I see that the JXTable in SwingX accomplishes this however, I wasn't able to decipher from the source code how it was done.

Thanks

Was it helpful?

Solution

My issue is that the JScrollPane only shows the button when there is something in the ScrollPane's column header viewport.

I think that is half the problem. You need a component in the viewport to take up some space.

I've tried putting an empty JPanel in there but that doesn't seem to work

Try the empty JPanel in the viewport along with the panel in the column header:

import java.awt.*;
import javax.swing.*;

public class TestCornerComponent {

    public static void main(String args[])
    {
        final JScrollPane scrollPane = new JScrollPane();

        /* button to put in corner */
        JButton cornerButton = new JButton("#");
        scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, cornerButton);

        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel column = new JPanel();
        column.setPreferredSize( new Dimension(100, cornerButton.getPreferredSize().height) );
        scrollPane.setColumnHeaderView( column );

        JPanel view = new JPanel();
        view.setPreferredSize( new Dimension(100, 100) );
        scrollPane.setViewportView( view );

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame("Test corner component");
                frame.add(scrollPane);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top