我编写了一个生成 PDF 表格的程序。为了更容易操作,我还创建了一个 GUI 来控制这些东西。然而,真正让我困扰的是,在 JFrame 上,这个 JComboBox 占用了大量空间,使得右侧子面板不必要地变宽。
出现这种情况的原因可能是组合框中有一个相当长的字符串。
我尝试对面板使用“设置首选大小”,但它不起作用。然后我继续使用 GridBagLayout 来尝试缩小该组合框的范围。有什么方法可以将所有按钮和组合框限制为一定的宽度吗?或者我应该使用不同的布局?
如果右侧面板中的所有组件都具有相同的宽度,就像现在一样,那就最好了。
谢谢!
这是我的代码:
JTable studentTable=new JTable(new StudentTableModel(bro));
studentTable.setRowHeight(25);
studentTable.setGridColor(java.awt.Color.BLACK);
DefaultTableCellRenderer centerRenderer = new
DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
studentTable.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
studentTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
studentTable.getColumnModel().getColumn(5).setCellRenderer(centerRenderer);
JPanel panelA1= new JPanel();
panelA1.setOpaque(false);
panelA1.setAlignmentX(Component.LEFT_ALIGNMENT);
panelA1.setLayout(new GridBagLayout());
JScrollPane scrollPaneA= new JScrollPane(studentTable);
JButton buttonA1= new JButton("Activate All");
JButton buttonA2= new JButton("Create Tables");
JButton buttonA3= new JButton("Save File");
JLabel labelA1= new JLabel("-Job Crews-");
JButton buttonA4= new JButton("Deact Crew");
JComboBox<Object> comboBoxA1=new JComboBox<Object>();
comboBoxA1.addItem(new String("-N/A-"));
for(JobCrew jj: crews)
{
comboBoxA1.addItem(jj);
}
comboBoxA1.setMaximumSize(new Dimension(100,100));
GridBagConstraints c = new GridBagConstraints();
{
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
panelA1.add(buttonA1,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
panelA1.add(buttonA2,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
panelA1.add(buttonA3,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
panelA1.add(labelA1,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 4;
panelA1.add(comboBoxA1,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 5;
panelA1.add(buttonA4,c);
}
JPanel panelA= new JPanel();
panelA.setLayout(new BoxLayout(panelA,BoxLayout.X_AXIS));
panelA.setOpaque(false);
panelA.add(scrollPaneA); panelA.add(panelA1);
//////
/**********/
tabs.addTab("Student info",null,panelA,"Organizes & displays student information");
最佳答案
关于Java 使用 GridBagLayout 限制 JPanel 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46270044/