我遇到JTabbedPane
的问题,我的JPanel
之一有边框,我认为JTabbedPane
有自己的布局,因此边框基本上会根据布局展开JTabbedPane
就像这样:
然后我尝试使用JTabbedPane
更改jTabbedPane.setLayout(new GridBagLayout());
的边框,但这完全混淆了它,结果是这样的:
我一直试图让它看起来像这样(为了澄清,我试图实现内部边界,而不是外部边界。):
是否可以实际更改布局以适应我想要实现的目标,还是有更好的方法?
非常感谢任何帮助,谢谢。如果我的问题需要改进或者需要任何其他代码或澄清,请告诉我。
代码:
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e)
{
e.printStackTrace();
}
setLayout(new GridBagLayout());
add(new HomePanel());
pack();
setVisible(true);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args)
{
Test t = new Test();
}
public class HomePanel extends JPanel
{
protected JTabbedPane tabbedPane;
public HomePanel()
{
tabbedPane = new JTabbedPane();
tabbedPane.setPreferredSize(new Dimension(800, 500));
tabbedPane.addTab("Your Bookings", new ShowBookingPanel());
add(tabbedPane);
}
}
public class ShowBookingPanel extends JPanel
{
protected JTable bookingTable;
protected JScrollPane scrollPane;
public ShowBookingPanel()
{
TitledBorder titledBorder = new TitledBorder("Your Bookings");
titledBorder.setTitleJustification(TitledBorder.CENTER);
Border border = new CompoundBorder(titledBorder, new EmptyBorder(40, 50, 40, 50));
setBorder(border);
String[] columnNames = {"Check-In Date", "Check-Out Date", "Room Type", "Price", "Action"};
Object[][] data = {{"22/09/1997", "TBA", "Single", "Priceless"}, {"12/03/2017", "23/04/2017", "Double", "£50"},
{"12/03/2017", "23/04/2017", "Double", "£50"}, {"12/03/2017", "23/04/2017", "Double", "£50"},
{"12/03/2017", "23/04/2017", "Double", "£50"}, {"12/03/2017", "23/04/2017", "Double", "£50"},
{"12/03/2017", "23/04/2017", "Double", "£50"}, {"12/03/2017", "23/04/2017", "Double", "£50"}};
TableModel model = new DefaultTableModel(data, columnNames)
{
public boolean isCellEditable(int row, int column)
{
return false;
}
};
bookingTable = new JTable(model);
bookingTable.setPreferredScrollableViewportSize(new Dimension(500, 300));
bookingTable.setFillsViewportHeight(true);
bookingTable.getTableHeader().setReorderingAllowed(false);
bookingTable.getTableHeader().setResizingAllowed(false);
bookingTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane(bookingTable);
setLayout(new GridBagLayout());
add(scrollPane);
}
}
}
答案 0 :(得分:2)
更改:
tabbedPane.addTab("Your Bookings", new ShowBookingPanel());
致:
JPanel centeredPanel = new JPanel(new GridBagLayout());
centeredPanel.add(new ShowBookingPanel());
tabbedPane.addTab("Your Bookings", centeredPanel);
只要使用默认约束将组件添加为唯一组件而不拉伸组件,GridBagLayout
将使组件居中。