I made a custom table that extends JTable. My user table is different in layout, where it has a JPanel with a button at the bottom of the table. The panel should always be at the bottom of the visible part of the table, regardless of the scroll position.
It works almost the way I want, except that it flickers when I look at the table . And some lines are behind the panel .
Is it possible to make the code better somehow in order to get rid of the flicker and make sure that not a single line is behind the panel?
Here is a working example of my user table:
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
class TableDemo {
public static void main(String[]args){
new TableDemo();
}
public TableDemo() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
CustomTable table = new CustomTable();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
table.initChangeListener();
frame.add(scrollPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
class CustomTable extends JTable {
private TableLayout layout = new TableLayout();
public CustomTable() {
super(100,10);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.setBackground(Color.lightGray);
panel.add(new JButton("Press me!"));
this.add(panel);
this.setLayout(layout);
}
public void initChangeListener() {
if(this.getParent() != null) {
if(this.getParent() instanceof JViewport) {
JViewport viewport = (JViewport)this.getParent();
viewport.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(CustomTable.this.getLayout() instanceof TableLayout) {
CustomTable.this.getLayout().layoutContainer(CustomTable.this);
}
}
});
}
}
}
}
class TableLayout implements LayoutManager {
@Override
public void addLayoutComponent(String name, Component comp) {}
@Override
public void removeLayoutComponent(Component comp) {}
@Override
public Dimension preferredLayoutSize(Container parent) {
return parent.getPreferredSize();
}
@Override
public Dimension minimumLayoutSize(Container parent) {
return parent.getMinimumSize();
}
@Override
public void layoutContainer(Container parent) {
CustomTable table = (CustomTable)parent;
JViewport vp = (JViewport)table.getParent();
Point p = vp.getViewPosition();
Rectangle rectangle = vp.getVisibleRect();
for(Component c : parent.getComponents()) {
if(c instanceof JPanel) {
c.setBounds(0, p.y + (int)rectangle.getHeight() - 40, (int)rectangle.getWidth(), (int)rectangle.getHeight());
}
}
}
}
}