我希望表格的寬度與框架的寬度相同,當我調整框架的大小時,表格也需要調整大小。 setSize()
JTable
無法正常工作。你可以幫我嗎?在JScrollPane和JPanel中設置JTable的大小和JFrame的大小
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
public Main() {
setSize(400, 600);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", 2},
{"Jhon", "ewrewr", 4},
{"Max", "zxczxc", 6}
};
JTable table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
int A = this.getWidth();
int B = this.getHeight();
table.setSize(A, B);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Marks");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Main ex = new Main();
ex.setVisible(true);
}
});
}
}
首先的代碼:沒有必要添加JScrollPane中您的JPanel。第二:不要調用setSize();根本不需要打包();. –
我感謝您可能希望閱讀[使用佈局管理器](http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html) – MadProgrammer