2011-10-12 41 views
1

在我的Java Swing應用程序,我想提出鎖定圖像一個JTextField不可編輯裏面,出現這樣的:如何在不可編輯的JTextField中顯示圖像?

Locked JTextField

我已經創建了一個JTextField,並插入一個JLabel它上面和定義JLabel的鎖定圖標。如果JTextField是可編輯的,那麼JLabel就像上面的圖片顯示的那樣顯示正常,但是如果JTextField不可編輯,那麼圖像根本不會出現。

我該如何解決這個問題?

+0

爲了更快提供更好的幫助,請發佈[SSCCE](http://pscode.org/sscce.html)。 在代碼中生成一個小圖像。 –

回答

2

你可以嘗試添加兩個標籤(圖標)和文本字段中的面板。從文本框中刪除邊框,並在面板周圍添加一個公共邊框。將背景設置爲與文本框的背景相同。

+0

謝謝大家的好解決方案。這對我來說是最簡單的。最後的組件看起來非常好。謝謝StanislavL。 – Brad

0

寫自己的類,它擴展JTextField和這個類,你必須與職位精心此改變paintComponent(Graphics g)

1)Icon

因爲

2)把你Custom JTextField到resizibale Container內,如果Icon停留在右側,如果尺寸正確調整爲Custom JTextFieldIcon裏面,

3)setEditable(true)setEditable(false)創建構造與Icon

1

爲什麼不使用jTextPane?

try { 
    // Get the text pane's document 
    JTextPane textPane = new JTextPane(); 
    StyledDocument doc = (StyledDocument)textPane.getDocument(); 

    // The image must first be wrapped in a style 
    Style style = doc.addStyle("StyleName", null); 
    StyleConstants.setIcon(style, new ImageIcon("imagefile")); 

    // Insert the image at the end of the text 
    doc.insertString(doc.getLength(), "ignored text", style); 
} catch (BadLocationException e) { 
} 
0

創建自定義Border讓我們稱之爲IconBorder。查看MatteIcon的源代碼,然後對其進行定製以僅繪製單個圖像。然後,您可以使用以下代碼將邊框添加到文本字段:

Border border = new CompoundBorder(textField.getBorder(), new IconBorder(...)); 
textField.setBorder(border); 
相關問題