我使用的IDE是Intellij。 在這裏我創建了一個轉換貨幣的小程序。 我使用BorderLayout作爲根面板,flowLayout作爲底部按鈕。對於西部和東部的面板,我使用了GridLayout(Intellij)。 當我運行該程序時,通常像這樣顯示:如何讓元素根據JAVA swing中的窗口大小自動調整大小?
如何讓他們調整距離自動?
這裏是我的代碼:
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
}
}
似乎從來沒有組合框所示的代碼來創建。也似乎有很多不必要的東西。爲了儘快提供更好的幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 –
..但基本上,有很多方法可以使組合框和文本字段伸展到可用寬度。個人將把每個組件放在'CENTER'約束中的'BorderLayout'中,而標籤放在'WEST'中。不幸的是,這將不會對齊標籤的右邊緣。相反,您可能會考慮使用單個「GridBagLayout」或「GroupLayout」。後者大多隻能由IDE中的GUI設計者使用,但GBL可以使用適當的'GridBagConstraint'來擴展輸入組件的寬度。 –
正如Andrew所說,值得發佈[MCVE](http://stackoverflow.com/help/mcve),以便您可以更快地獲得所需的幫助。但是,正如我的回答所說,你所追求的是[佈局管理器](https://docs.oracle.com/javase/tutorial/uiswing/layout/using.html)。如果您希望我進一步澄清我的答案或需要幫助瞭解其中某個部分,請讓我知道 – Dan