2014-02-28 17 views
0

我正在使用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"); 
    } 

} 
+0

可能的重複http://stackoverflow.com/questions/10897092/how-do-you-stop-a-jlabel-changing-its-size-when-its-text-changes – desperateCoder

+1

使用不可編輯的文本字段,將其邊框移除並設置爲透明,並將列設置爲預期寬度 – MadProgrammer

+0

@MadProgrammer謝謝,完美的作品:) –

回答

1

因爲你沒privide一個Minimal, Complete, Tested, and Readable example演示這個問題,我只是掃了一眼足以看出您正在使用的GridBagLayout。

,你可以利用一些技巧:

  1. 某處在同一列的標籤(或略高於或 下方),你可以把一個Box.createHorizontalStrut(...) 組件,這只是足夠長的時間要長一些比您的JLabel的任何預計的 長度。當然,你需要提前知道最長的 文本(並計算其在JLabel中的寬度),以此爲 工作。

  2. 把你的JLabel放在它自己的行上,以免打擾 在同一行上放置其他組件。你想讓 確保它有一個跨越多個列的網格寬度,以免 使JLabel的列擴展到其他佈局。

  3. 在您的JLabel中使用HTML以像素爲單位定義固定寬度。

  4. 使用HTML創建一個多線JLabel <br>標籤。

  5. 創建一個JTextField並相應地進行裝飾(不透明度,邊框,不可編輯等),使其看起來像一個JL​​abel 。

  6. 只需將您的消息放入JTextArea中,因爲JLabels並非真正適用於動態,任意文本的 。你可能會擁有佈局 問題;-)

  7. 如果「無效輸入」是將永遠不會有該標籤的純文本,預設 在JLabel中的文本,然後就叫 label.setVisible(true/false)在適當的時候。
相關問題