【发布时间】:2014-10-29 22:19:11
【问题描述】:
我正在创建一个应用程序,它以表格的形式显示来自数据库的信息。由于表中的行数可以变化,我创建了一个通用方法,它将创建表的单行,表的标题或单个行。我已经使用 JPanel 完成了。
我的问题是每次向表中添加新行时,行之间都会出现间隙。我知道我可以使用 Table,但这对我来说也是一次使用 swing 的学习经验,所以如果可能的话,我想使用 JPanel 来完成。
下面是创建行的方法:
public static JPanel customersTable(){
FlowLayout FlowCustTable = new FlowLayout();
FlowCustTable.setHgap(1);
FlowCustTable.setVgap(0);
JPanel customersTable = new JPanel(FlowCustTable);
JTextField surname = new JTextField();
FieldSetup(surname, 120, 25, " Surname", Color.CYAN, false);
JTextField firstname = new JTextField();
FieldSetup(firstname, 120, 25, " Firstname", Color.CYAN, false);
JTextField mobile = new JTextField();
FieldSetup(mobile, 120, 25, " Mobile", Color.CYAN, false);
JTextField homePhone = new JTextField();
FieldSetup(homePhone, 120, 25, " Home Phone", Color.CYAN, false);
JTextField address = new JTextField();
FieldSetup(address, 280, 25, " Address", Color.CYAN, false);
JTextField postcode = new JTextField();
FieldSetup(postcode, 120, 25, " Postcode", Color.CYAN, false);
customersTable.add(surname);
customersTable.add(firstname);
customersTable.add(mobile);
customersTable.add(homePhone);
customersTable.add(address);
customersTable.add(postcode);
return customersTable;
}
这是用于设置 JTextfields 的方法:
public static void FieldSetup(JTextField field, int x, int y, String text, Color color, Boolean Editable){
field.setText(text);
field.setBackground(color);
field.setPreferredSize(new Dimension(x, y));
field.setEditable(Editable);
Border border = BorderFactory.createLineBorder(Color.BLACK);
field.setBorder(border);
}
这是创建最终表格和用户界面的方法:
public static void CustomersGui(){
final JFrame frame = new JFrame("Customers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel customers = new JPanel();
customers.add(customersTable());
customers.add(customersTable());
frame.setContentPane(customers);
frame.setSize(1200,500);
frame.setVisible(true);
}
出于这个问题的目的,我添加了表头的 2 个实例,但同样的原则仍然适用。
我已经尝试过 JPanel 的 setHgap 和 setVgap,虽然这确实会影响间隙,但它不会使其为零。
【问题讨论】:
-
尝试更改
customers中的间隔。如果您希望垂直添加组件,可能更适合 BoxLayout 而不是默认的 FlowLayout。 FlowLayout 将它们水平添加。溢出会导致它看起来是垂直的,但是当 BoxLayout 已经提供了你想要的功能时,你不想依赖它 -
1) 为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)。 2)见Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?(是的。)
-
另一方面,为什么不直接使用 JTable,因为看起来该字段是创建一些表格格式的。考虑到您不想要这些间隙,它看起来很合理,特别是因为我没有看到任何字段标签。可以在表格上设置列宽和行高
-
关于我的第一条评论
FlowLayout layout = (FlowLayout)customers.getLayout(); set gaps -
一个 MCVE 应该是一个源文件,带有
main(String[])和导入。当问题可以使用 1 或 2 来证明时,它不会有 6 xFieldSetup调用。它可以热链接到源代码或在源代码中生成图像。想想自己,“我能做些什么来轻松地在另一台 PC 上复制/粘贴此代码,然后发现问题?”。并在发布的代码上:使用逻辑和一致的缩进代码行和块形式。缩进是为了让代码的流程更容易理解!
标签: java swing user-interface jpanel spacing