我正在使用JLabel來通知用戶JTextField中是否存在與他/她的輸入有關的錯誤。當JLabel出現時,它移動組件的其餘部分
如果出現問題,我將JLabel的文本設置爲「無效輸入」。但是,當標籤中的文本被設置時,它略微「推」了佈局的其餘部分。我希望一切都留在它的地方。有任何想法嗎?
public Dialog(Window owner){
widthL = new JLabel("Width: ");
heightL = new JLabel("Height: ");
widthF = new JTextField(5);
heightF = new JTextField(5);
apply = new JButton("Apply");
error = new JLabel("");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10,10,10,10);
gbc.gridy = 1;
gbc.gridx = 1;
add(widthL,gbc);
gbc.gridx = 2;
add(widthF,gbc);
gbc.gridy = 2;
gbc.gridx = 1;
add(heightL,gbc);
gbc.gridx = 2;
add(heightF,gbc);
gbc.gridy = 1;
gbc.gridx = 3;
gbc.gridheight = 2;
add(apply,gbc);
gbc.gridheight = 1;
gbc.gridy = 3;
gbc.gridx = 2;
add(error,gbc);
apply.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int width,height;
try{
width = Integer.parseInt(widthF.getText());
height = Integer.parseInt(heightF.getText());
}catch(NumberFormatException ex){
error.setText("Invalid input");
}
}
可能的重複http://stackoverflow.com/questions/10897092/how-do-you-stop-a-jlabel-changing-its-size-when-its-text-changes – desperateCoder
使用不可編輯的文本字段,將其邊框移除並設置爲透明,並將列設置爲預期寬度 – MadProgrammer
@MadProgrammer謝謝,完美的作品:) –