2011-12-30 26 views
3

メモ帳のアプリケーションで、 Pictureをクリックして、JLabelJTextPaneに追加しています。画像をJTextPaneに挿入する


private class Picture implements ActionListener 
{ 
    public void actionPerformed(ActionEvent event) 
    { 
     fc = new JFileChooser(); 
     FileNameExtensionFilter picture = new FileNameExtensionFilter("JPEG files (*.jpg)", "jpg"); 
     fc.setFileFilter(picture); 
     fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); 

     if (fc.showDialog(Notepad.this, "Insert")!=JFileChooser.APPROVE_OPTION) return; 
     filename = fc.getSelectedFile().getAbsolutePath(); 

     // If no text is entered for the file name, refresh the dialog box 
     if (filename==null) return; 

     // NullPointerException 
     textArea.insertIcon(createImageIcon(filename)); 
    } 

    protected ImageIcon createImageIcon(String path) 
    { 
     java.net.URL imgURL = Notepad.class.getResource(path); 

     if (imgURL != null) 
     { 
      return new ImageIcon(imgURL); 
     } 

     else 
     { 
      JOptionPane.showMessageDialog(frame, "Could not find file: " + path); 
      return null; 
     } 
    } 
} 

問題は、私はすでに私がtextPane.add(image)に似た何かができるように、私はコードの行を書くにはどうすればよいなぜこれが起こっている知っているが... NullPointerExceptionがある20行目にあります(私はtextPane.add(StyleConstants.setIcon(def, createImageIcon(filename));を行うことができないので)?これを正しく実行するためにコードを書く必要がありますか?

+0

「の書式コードは」単にコードのテキストはかなり読みやすい見せることを意味し、プログラムの実行や関数とは何の関係もありません。あなたがしようとしていることを明確にしてください。 –

+0

@HovercraftFullOfEelsさて、 "フォーマット"の部分を忘れてください。ダイアログボックスで画像を見つけて「挿入」をクリックした後に、画像をjtextareaに挿入する方法を知りたいだけです。 – Rob

+0

「画像をJTextAreaに挿入する」とはどういう意味ですか?それを背景イメージとして使用することを意味しますか?それともJLabelやImageIconのようにイメージをJTextAreaに追加するのですか?問題が明確になればなるほど、他の人が解決しやすくなります。 –

答えて

1

は、多くの研究の後、私はついにそれを考え出しました! this postとcamickrの投稿に感謝します。


private class Picture implements ActionListener 
{ 
    public void actionPerformed(ActionEvent event) 
    { 
     fc = new JFileChooser(); 
     FileNameExtensionFilter picture = new FileNameExtensionFilter("JPEG files (*.png)", "png"); 
     fc.setFileFilter(picture); 
     fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); 

     if (fc.showDialog(Notepad.this, "Insert")!=JFileChooser.APPROVE_OPTION) return; 
     filename = fc.getSelectedFile().getAbsolutePath(); 

     // If no text is entered for the file name, refresh the dialog box 
     if (filename==null) return; 

     try 
     { 
      BufferedImage img = ImageIO.read(new File(filename)); 
      ImageIcon pictureImage = new ImageIcon(img); 
      textArea.insertIcon(pictureImage); 
     } 

     catch (IOException e) 
     { 
      JOptionPane.showMessageDialog(frame, "Could not find file: " + filename); 
     } 
    } 
} 
4

テキスト・ペインにコンポーネントやアイコンを追加することができます。

textpane.insertIcon(...); 
textPane.insertComponent(...); 
+0

あなたの提案に基づいてコードを更新しました。しかし、私はまだNull Pointer Exceptionを取得しています。私のダイアログでInsertをクリックすると、私のメッセージ ''ファイルを見つけることができませんでした: "+ path'。 – Rob

+0

+1、本当にありがとう! – Rob