因此,我有一個JTextPane
對象需要在運行時將其背景更改爲特定圖像的背景。我似乎有相當多的錯誤(JComboBox
用於更改背景,並呼籲repaintBackground()
似乎沒有autoclose選擇等),它也拋出一個空指針,我不知道爲什麼隨着背景的變化。嘗試在運行時更改JTextPane的背景,但成功但出錯
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.text.BoxView.paint(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$RootView.paint(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.paintSafely(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.paint(Unknown Source)
at javax.swing.plaf.synth.SynthEditorPaneUI.paint(Unknown Source)
at javax.swing.plaf.synth.SynthEditorPaneUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
etc etc etc....
這是我的目標:
public class PreviewPane extends JTextPane {
private String _name = "bg3";
public PreviewPane() {
super();
setOpaque(false);
StyledDocument document = this.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
document.setParagraphAttributes(0, document.getLength(), center, false);
}
@Override
protected void paintComponent(Graphics g) throws RuntimeException{
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
BufferedImage img = null;
try {
img = ImageIO.read(new File(getClass().getResource("/icons/"+_name+".png").toURI()));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
g.drawImage(img, 0, 0, this);
super.paintComponent(g);
}
public void repaintBackground(String bgName){
_name = bgName;
paintComponent(this.getGraphics());
}
}
任何幫助,將不勝感激。
'保護無效paintComponent(圖形G)拋出的RuntimeException { .. IMG = ImageIO.read('哇一種油漆方法:1)不應該拋出運行時異常。 2)應立即調用超級方法。 3)不應該嘗試像加載圖像一樣可能長時間運行的任務! – 2014-10-07 12:08:31
你會如何推薦避免這種情況? – Ofek 2014-10-07 12:09:37
哪'這'?請明確點。 – 2014-10-07 12:10:24