【发布时间】:2017-05-11 13:59:58
【问题描述】:
我使用的 IDE 是 Intellij。 在这里,我创建了一个转换货币的小程序。 我使用 BorderLayout 作为根面板,使用 flowLayout 作为底部按钮。对于西面板和东面板,我使用了 GridLayout(Intellij)。 当我运行程序时,它可以正常显示如下:
如何让它们自动调整距离?
这是我的代码:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Bob on 2017/5/11.
*/
public class layout {
private JPanel converterRootPanel;
private JPanel westPanel;
private JLabel selectNationPanel;
private JLabel currencyToConvett;
private JLabel currencyConverted;
private JComboBox currencyType;
private JTextField input;
private JTextField output;
private JPanel eastPanel;
private JPanel southPanel;
private JButton convertButton;
private JButton clearButton;
private JLabel convertToLabel;
private JComboBox convertType;
private JPanel northPanel;
public int selection1;
public int selection2;
public Double toConvert;
public double[][] rate1={{0,0.1335,0.1449,16.5172,163.4922},{7.4927,0,1.0857,123.7900,
1225.0380},{6.9029,0.9382,0,114.01,1129.19},{0.06053,0.00808,0.008771,0,9.9043},{0.006112,
0.0008158,0.0008856,0.101,0}};
public layout() {
currencyType.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selection1 = currencyType.getSelectedIndex();
}
});
convertType.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selection2 = convertType.getSelectedIndex();
}
});
convertButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(selection1==selection2){
JOptionPane.showConfirmDialog(null, "You have to choose different currency types!", "Error Alert", JOptionPane.CANCEL_OPTION);
}
output.setText("");
toConvert = Double.parseDouble(input.getText().toString());
Double convertResult = toConvert*rate1[selection1][selection2];
output.setText(convertResult.toString());
}
});
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
output.setText("");
input.setText("");
convertType.setSelectedIndex(0);
currencyType.setSelectedIndex(0);
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame("layout");
frame.setContentPane(new layout().converterRootPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
//layout lay = new layout();
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
}
【问题讨论】:
-
组合框似乎从未在所示代码中创建。似乎还有很多不必要的杂物。如需尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。
-
..但基本上,有很多方法可以让组合框和文本字段拉伸到可用宽度。一个是将这些组件中的每一个放在
CENTER约束处的BorderLayout中,而标签放在WEST中。不幸的是,这不会对齐标签的右边缘。相反,您可能希望使用单个GridBagLayout或GroupLayout。后者大多只能由 IDE 中的 GUI 设计人员使用,但 GBL 可以使用适当的GridBagConstraint拉伸输入组件的宽度。 -
正如 Andrew 所说,发布MCVE 是值得的,这样您就可以更快地获得所需的帮助。但是,正如我的回答所说,您所追求的是layout manager。如果您希望我进一步澄清我的答案或需要帮助理解其中的某个部分,请告诉我
-
我推荐 Oracles 教程/Java 文档:Lesson: Laying Out Components Within a Container
标签: java swing intellij-idea