問題是BorderLayout
的中心元素擴大。我會建議使用GridBagLayout
與GridBagConstraint
S或A Box
如以下答案:
Alex B answered "How do I add a margin outside the border of a component in Swing?"
這裏是一個有效的解決方案(gist):
import javax.swing.*;
import java.awt.*;
/**
* CenterBorderedJTable.java
*
* @author Marco
* @since 2014-07-10
*/
public class CenterBorderedJTable {
private static final String[] tableColumns = {"First Name", "Last Name", "Hobby", "Age", "Vegetarian?" };
private static final Object[][] tableData = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
/**
* Creates a GridBagConstraints with the specified vertical and horizontal margin.
* @param verticalMargin The vertical margin specifies how many pixels the top and bottom margins will be
* @param horizontalMargin The horizontal margin specifies how many pixels the left and right margins will be
* @return A GridBagConstraints with the specified vertical and horizontal margin.
*/
private static GridBagConstraints createGridBagConstaints(int verticalMargin, int horizontalMargin) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(verticalMargin, horizontalMargin, verticalMargin, horizontalMargin);
return constraints;
}
/**
* This boilerplate is from the Java tutorials:
* @see <a href="http://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html">Creating the Demo Application</a>
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
/**
* This boilerplate is from the Java tutorials:
* @see <a href="http://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html">Creating the Demo Application</a>
*/
private static void createAndShowGUI() {
JFrame f = new JFrame("Center Bordered JTable");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // exit JVM when window is closed
// GridBagLayout needed since we use GridBagConstraints to constrain the table
f.setLayout(new GridBagLayout());
// Create JTable with our sample data
JTable table = new JTable(tableData, tableColumns);
JScrollPane scrollPane = new JScrollPane(table); // Allow for scrolling if data is too long
scrollPane.setBorder(BorderFactory.createLineBorder(Color.CYAN)); // CYAN for easy visibility
table.setFillsViewportHeight(true);
// Add the scrollPane with the specified constraints to the window
f.add(scrollPane, createGridBagConstaints(50, 25));
// Pack and show the user!
f.pack();
f.setVisible(true);
}
}
很高興見到你想通這個問題在你自己!如果你正在尋找一個更強大的解決方案(也許將來你想添加一個'EtchedBorder'到表格?),請參閱我的答案 –