JTable を含む JScrollPane を持つ JFrame があります。JTable の下に、SpringLayout を使用して JButton を配置しました。
l.putConstraint(SpringLayout.NORTH, but, 50, SpringLayout.SOUTH, sP);
JButton は JTable に行を追加し、JScrollPane のサイズを更新します。それらは互いに制約されているため、ボタンの位置を更新して下に移動させたいと思います。しかし、それは起こりません。
プレーンな JTable だけで同じことを試したので、うまくいきましたが、JTable がフレームを超えて拡張するのを避けるために、この JScrollPane が必要です。
ここに私の完全なテストコードがあります:
package tests;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SpringLayout;
import javax.swing.table.DefaultTableModel;
public class StackOverflowQRuntimeAlignment extends JFrame{
private JScrollPane sP;
private JTable tab;
private JButton but;
private DefaultTableModel dtm;
public static void main(String[] args){
StackOverflowQRuntimeAlignment frame = new StackOverflowQRuntimeAlignment("Test");
frame.setSize(new Dimension(1280, 720));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
StackOverflowQRuntimeAlignment(String title){
super(title);
//DefaultTabelModel to create the Table
dtm = new DefaultTableModel(new String[][]{{"data1", "data2"}}, new String[]{"Column1", "Column2"});
tab = new JTable(dtm);
//set TableHeaderHeight to RowHeight
tab.getTableHeader().setPreferredSize(new Dimension(tab.getWidth(), tab.getRowHeight()));
//create ScrollPane containing the Table
sP = new JScrollPane(tab);
//set the size of the ScrollPane
sP.setPreferredSize(new Dimension(500, (dtm.getRowCount()+1)*16+3));//+1 for the Header, +3 to hide ScrollBars if they are not neccesary
sP.setMaximumSize(new Dimension(tab.getWidth(), 360));
//create the button to add an row to the table
but = new JButton("Hit me");
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dtm.addRow(new String[]{"Banana", "Apple"});
//updating the size of the ScrollPane
sP.setPreferredSize(new Dimension(500, (dtm.getRowCount()+1)*16+3));
sP.setSize(sP.getPreferredSize());
}
});
//constraining the Components on the GUI
SpringLayout l = new SpringLayout();
this.setLayout(l);
l.putConstraint(SpringLayout.HORIZONTAL_CENTER, sP, 0, SpringLayout.HORIZONTAL_CENTER, this.getContentPane());
l.putConstraint(SpringLayout.NORTH, sP, 50, SpringLayout.NORTH, this.getContentPane());
l.putConstraint(SpringLayout.HORIZONTAL_CENTER, but, 0, SpringLayout.HORIZONTAL_CENTER, sP);
l.putConstraint(SpringLayout.NORTH, but, 50, SpringLayout.SOUTH, sP);
//adding the Components to the GUI
this.add(sP);
this.add(but);
}
}