【发布时间】:2019-04-22 09:56:29
【问题描述】:
单击位于前一行的按钮后,我正在尝试添加新的组件行。
这个图:
在我点击“添加”按钮后,显示我想要在下一行复制的行。
我试图做的事情给了我这个结果:
但只有在我第一次单击“添加”按钮然后项目选择完成之后。
如何使“添加”按钮独立于其他组件,如何调整可视化效果?
代码如下:
////// First row
// First Column
gbc.weightx = 0.5;
gbc.gridx = 1;
gbc.gridy = 0;
this.add(this.field, gbc);
// Second Column
gbc.gridx++;
this.add(this.operator, gbc);
// Third Column
gbc.gridx++;
this.add(this.value, gbc);
////// Second row
gbc.gridx = 0;
gbc.gridy = 1;
this.add(rowNumber, gbc);
// First Column
gbc.gridx = 1;
//////////////////////////////////////////////////// SET DIMENSION
attrList.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXX");
this.add(attrList, gbc);
// Second Column
gbc.gridx = 2;
//////////////////////////////////////////////////// SET DIMENSION
opListString.setPrototypeDisplayValue("XXXXXXX");
this.add(opListString, gbc);
// Third Column (Hidden)
gbc.gridx = 3;
////////////////////////////////////////////////////SET DIMENSION
sessoBox.setPrototypeDisplayValue("XXXXXXXXXXXXXX");
this.add(sessoBox, gbc);
sessoBox.setVisible(false);
////////////////////////////////////////////////////SET DIMENSION
titoloBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXX");
this.add(titoloBox, gbc);
titoloBox.setVisible(false);
// Fourth Column
gbc.gridx = 4;
remButton = new JButton("Rem");
this.add(remButton, gbc);
// Add row JButton
gbc.gridx = 5;
gbc.gridy = 1;
this.add(addRow, gbc);
// Add empty JLabel to positioning components at the top
gbc.weighty = 10;
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
this.add(emptyLabel, gbc);
// Add Action Listener on Attributes to choose
// Display Value Components based on item selected
attrList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String choose = attrList.getSelectedItem().toString();
switch(choose) {
case "----------------": {
removeItem();
break;
}
case "Sex": {
removeItem();
addOpsString();
addValueComp2(sessoBox);
}
}
}
});
// Remove row
/*remButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
remButton.remove((addRow));
}
});
*/
// Add row
addRow.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
gbc.gridy = ++rowNum;
gbc.gridx = 0;
panel.remove(emptyLabel);
panel.add(new JLabel(Integer.toString(rowNum)), gbc);
gbc.gridx++;
panel.add(attrList);
gbc.gridx++;
panel.add(opListString);
gbc.gridx++;
gbc.gridx++;
panel.add(remButton);
gbc.gridx++;
panel.add(addRow);
// Add empty JLabel to positioning components at the top
gbc.weighty = 10;
gbc.gridx = 1;
gbc.gridy = rowNum + 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
panel.add(emptyLabel, gbc);
}
});
【问题讨论】:
-
1) 该任务似乎更适合
JTable。 2)如需更好的帮助,请edit添加minimal reproducible example或Short, Self Contained, Correct Example。 -
这不是一个直接的答案——但对于任何 Swing 布局任务,我只使用 MigLayout:miglayout.com
标签: java swing layout-manager gridbaglayout