Mini editor de textos

Pessoal, alguém tem algum componente simples para edição de texto.
Algo do tipo JTextPane mais alguns botões para colocar o texto em negrito, mudar a cor e tal?

Desde já, vlw.

Blz?

Se o componente que está procurando for para a web, conheço o FckEditor . . . dá uma pesquisada no assunto.

Sei tbm que existem componentes para integração do BrOffice em aplicações web, mas no caso o programa tem que estar instalado no servidor e no cliente.

espero ter ajudado.

t+

Não, é para aplicações Desktop mesmo.
Algo bem simples. Edição com negrito, italico, sublinhado, fonte, tamanho e cor…
Só mesmo!

Se eu for implementar, conhece algo que já devo ir indo estudando?

[quote=engdanilo]Não, é para aplicações Desktop mesmo.
Algo bem simples. Edição com negrito, italico, sublinhado, fonte, tamanho e cor…
Só mesmo!

Se eu for implementar, conhece algo que já devo ir indo estudando?[/quote]

Oi,

Como você disse é bem simples mesmo…

Se você tiver o jdk instalado, poderá entrar na pasta jdk\demo\jfc\Notepad que lá tem um Notepad.jar e seus códigos fontes para pesquisa.

Tchauzin!

Segue o código de uma classe que eu implementei há pouco tempo. Se quiser/puder melhorar faça e disponibilize aqui, vlw?! :smiley:

[code]import java.awt.Color;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.text.rtf.RTFEditorKit;

/**

  • @author Marcelo Silva de Medeiros, Natal-RN

  • Classe que permite formatações básicas em texto para o formato RTF
    */
    public class TextFormatPane extends JPanel{

    private static final long serialVersionUID = 1L;
    private static final String CORINGA = “#@#@#”;

    private final String pathTempRTF= System.getProperty(“java.io.tmpdir”)+“texto.rtf”; // Path para Arquivo RTF temporário

    private JScrollPane jScrollPane = null;
    private JTextPane textPane = null;
    private StyleContext sContext = new StyleContext();
    private JColorChooser escolherCor;
    private JComboBox jComboFontSize = null;
    private JPanel jPanelOperacoes = null;
    private JButton jButtonNegrito = null;
    private JButton jButtonSubLinhado = null;
    private JButton jButtonItalico = null;
    private JButton jButtonSelCor = null;
    private JComboBox jComboBoxFontFamily = null;

    private JToolBar jToolBarTools = null;

    private JButton jButtonFonte = null;

    /**

    • Construtor paadrão
    • @throws IOException
      */
      public TextFormatPane() throws IOException{
      super(null);
      initialize("");
      }

    /**

    • Construtor que recebe uma String(texto formatado em RTF) para exibí-la no textPane
    • @param conteudoRTF, String a exibir
    • @throws IOException
      */
      public TextFormatPane(String conteudoRTF) throws IOException{
      super(null);
      initialize(conteudoRTF);
      }

    private void initialize(String conteudoRTF) throws IOException {
    File tempFile = null;

     if ( !("".equals(conteudoRTF)) ) {
     	tempFile = setRTFContent(conteudoRTF);
     }
     
     this.setSize(605, 384);
     this.setLayout(null);
     this.add(getJScrollPane(tempFile), null);
     this.add(getJToolBarTools(), null);
    

    // this.add(getJScrollPane(), null);
    }

    /**

    • This method initializes jPanelOperacoes

    • @return javax.swing.JPanel
      /
      private JPanel getJPanelOperacoes() {
      if (jPanelOperacoes == null) {
      jPanelOperacoes = new JPanel();
      jPanelOperacoes.setLayout(null);
      jPanelOperacoes.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
      jPanelOperacoes.add(getJComboFontSize(), null);
      jPanelOperacoes.add(getJComboBoxFontFamily(), null);
      }
      return jPanelOperacoes;
      }
      /
      *

    • This method initializes jButtonSelCor

    • @return javax.swing.JButton
      */
      private JButton getJButtonSelCor() {
      if (jButtonSelCor == null) {
      jButtonSelCor = new JButton();
      jButtonSelCor.setText(“Cor”);
      jButtonSelCor.addActionListener(new java.awt.event.ActionListener() {

       	@SuppressWarnings("static-access")
       	public void actionPerformed(java.awt.event.ActionEvent e) {
       		Color cor = Color.BLACK;
       		cor = escolherCor.showDialog(null, "Selecione", Color.BLACK);
       		setStyleValueFor(StyleConstants.Foreground, cor);					
       	}
       });
      

      }
      return jButtonSelCor;
      }

    /**

    • This method initializes jComboBoxFontFamily
    • @return javax.swing.JComboBox
      */
      private JComboBox getJComboBoxFontFamily() {
      if (jComboBoxFontFamily == null) {
      jComboBoxFontFamily = new JComboBox();
      jComboBoxFontFamily.setBounds(new Rectangle(44, 0, 200, 26));
      jComboBoxFontFamily.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent e) {
      setStyleValueFor(StyleConstants.FontFamily, jComboBoxFontFamily.getSelectedItem().toString());
      }
      });
      fontesDisponiveis(jComboBoxFontFamily);
      }
      return jComboBoxFontFamily;
      }

    /**

    • This method initializes jButtonNegrito
    • @return javax.swing.JButton
      */
      private JButton getJButtonNegrito() {
      if (jButtonNegrito == null) {
      jButtonNegrito = new JButton();
      jButtonNegrito.setText(“N”);
      jButtonNegrito.setToolTipText(“Negrito”);
      jButtonNegrito.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent e) {
      setStyleValueFor(StyleConstants.Bold, testValueStyle(StyleConstants.Bold));
      }
      });
      }
      return jButtonNegrito;
      }

    /**

    • This method initializes jButtonItalico
    • @return javax.swing.JButton
      */
      private JButton getJButtonItalico() {
      if (jButtonItalico == null) {
      jButtonItalico = new JButton();
      jButtonItalico.setText(" I ");
      jButtonItalico.setToolTipText(“Itálico”);
      jButtonItalico.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent e) {
      setStyleValueFor(StyleConstants.Italic, testValueStyle(StyleConstants.Italic));
      }
      });
      }
      return jButtonItalico;
      }

    /**

    • This method initializes jComboFontSize
    • @return javax.swing.JComboBox
      */
      private JComboBox getJComboFontSize() {
      if (jComboFontSize == null) {
      jComboFontSize = new JComboBox();
      jComboFontSize.setBounds(new Rectangle(0, 1, 43, 26));
      setFontSizes(jComboFontSize);
      jComboFontSize.setSelectedItem(12);
      jComboFontSize.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent e) {
      setStyleValueFor(StyleConstants.FontSize, jComboFontSize.getSelectedItem());
      }
      });
      }
      return jComboFontSize;
      }

    /**

    • This method initializes jButtonSubLinhado
    • @return javax.swing.JButton
      */
      private JButton getJButtonSubLinhado() {
      if (jButtonSubLinhado == null) {
      jButtonSubLinhado = new JButton();
      jButtonSubLinhado.setText(“S”);
      jButtonSubLinhado.setToolTipText(“Sublinhado”);
      jButtonSubLinhado.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent e) {
      setStyleValueFor(StyleConstants.Underline, testValueStyle(StyleConstants.Underline));
      }
      });
      }
      return jButtonSubLinhado;
      }

    /**

    • This method initializes jScrollPane
    • @return javax.swing.JScrollPane
    • @throws IOException
      */
      private JScrollPane getJScrollPane(File tempFile) throws IOException {
      if (jScrollPane == null) {
      jScrollPane = new JScrollPane();
      jScrollPane.setBounds(new Rectangle(8, 47, 591, 328));
      jScrollPane.setViewportView(getJTextPane(tempFile));
      }
      return jScrollPane;
      }

    /**

    • This method initializes jTextPane

    • @return javax.swing.JTextPane

    • @throws IOException
      */
      private JTextPane getJTextPane(File tempFile) throws IOException {
      if (textPane == null) {
      textPane = new JTextPane();
      textPane.setBounds(new Rectangle(9, 19, 543, 220));

       textPane.getStyledDocument();
       DefaultStyledDocument doc = new DefaultStyledDocument(sContext);
       textPane.setStyledDocument(doc);			
       
       tempFile = (null == tempFile)? getTempFile() : tempFile;
       	 
             textPane.setPage(tempFile.toURI().toURL());
             textPane.addKeyListener(new java.awt.event.KeyAdapter() {
             	public void keyReleased(java.awt.event.KeyEvent e) {
             		switch (e.getKeyCode()) {
       			case KeyEvent.VK_N:
       				setStyleValueFor(StyleConstants.Bold, testValueStyle(StyleConstants.Bold));
       				break;
       			case KeyEvent.VK_I:
       				setStyleValueFor(StyleConstants.Italic, testValueStyle(StyleConstants.Italic));
       				break;
       			case KeyEvent.VK_U:
       				setStyleValueFor(StyleConstants.Underline, testValueStyle(StyleConstants.Underline));
       				break;						
       			case KeyEvent.VK_F:
       				setStyleValueFor(StyleConstants.FontSize, jComboFontSize.getSelectedItem());
       				break;
       			default:
       				break;
       			} 
             	}
             });			 
      

      }
      return textPane;
      }

    /**

    • Método que monta o conteúdo do ComboBox de Tamanhos de Fonte com os disponíveis
    • @param combo - JComboBox
      */
      private void setFontSizes(JComboBox combo) {
      for (int i = 10; i <= 72; i += 2) {
      combo.addItem(i);
      }
      }

    /**

    • Método que monta o conteúdo do ComboBox de Fontes com as disponíveis
    • @param combo - JComboBox
      */
      private void fontesDisponiveis(JComboBox combo) {
      String[] fontes = GraphicsEnvironment.getLocalGraphicsEnvironment()
      .getAvailableFontFamilyNames();
      for (String fonte : fontes) {
      combo.addItem(fonte);
      }
      }

    /**

    • This method initializes jButtonFonte
    • @return javax.swing.JButton
      */
      private JButton getJButtonFonte() {
      if (jButtonFonte == null) {
      jButtonFonte = new JButton();
      jButtonFonte.setText(“Fonte”);
      jButtonFonte.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent e) {
      setStyleValueFor(StyleConstants.FontSize, jComboFontSize.getSelectedItem());
      }
      });
      }
      return jButtonFonte;
      }

    /**

    • This method initializes jToolBarTools

    • @return javax.swing.JToolBar
      */
      private JToolBar getJToolBarTools() {
      if (jToolBarTools == null) {
      jToolBarTools = new JToolBar();
      jToolBarTools.setBounds(new Rectangle(8, 9, 385, 32));
      jToolBarTools.add(getJButtonNegrito());
      jToolBarTools.add(getJButtonItalico());
      jToolBarTools.add(getJButtonSubLinhado());
      jToolBarTools.add(getJButtonSelCor());
      jToolBarTools.add(getJButtonFonte());
      jToolBarTools.add(getJPanelOperacoes());

       jToolBarTools.setFloatable(false);
      

      }
      return jToolBarTools;
      }

    /* ####################################################################
    Métodos de Controle
    #################################################################### */

    /**

    • Método que testa se o status da propriedade está igaual para toda a seleção e retorna

    • o valor que deve se setado à propriedade.

    • @param tipoEstilo - (Representa a propriedade a ser consultada, ex: bold)

    • – Object, mas, deve ser de StyleConstants

    • @return status - true ou false
      */
      private Object testValueStyle(Object tipoEstilo) {
      int ini = textPane.getSelectionStart();
      int fim = textPane.getSelectionEnd();

      StyledDocument styleDoc = (StyledDocument) textPane.getDocument();

      Boolean status = (styleDoc.getCharacterElement(ini).getAttributes().getAttribute(tipoEstilo) == null)? false : (Boolean) styleDoc.getCharacterElement(ini).getAttributes().getAttribute(tipoEstilo);

      for (int i = ini; i < fim; i++) {
      if(status.compareTo((Boolean) (styleDoc.getCharacterElement(ini).getAttributes().getAttribute(tipoEstilo) == null)? false : (Boolean) styleDoc.getCharacterElement(ini).getAttributes().getAttribute(tipoEstilo)) != 0){
      status = false;
      break;
      }
      }
      return !status;
      }

    /**

    • Método que seta o valor recebido na propriedade escolhida para todo o texto selecionado

    • @param tipoEstilo - Object tipo de estilo a ser alterado, necessariamente de ‘StyleConstants’

    • @param value - valor a ser atribuído no tipo de estilo
      /
      private void setStyleValueFor(Object tipoEstilo, Object value){
      if(null != value /
      && “” != value*/){
      int ini = textPane.getSelectionStart();
      int fim = textPane.getSelectionEnd();

       StyledDocument styleDoc = (StyledDocument) textPane.getDocument();
       
       for(int indAtual = ini; indAtual < fim; indAtual++){
       	String texto;
       	try {
       		texto = styleDoc.getText(indAtual, 1);
       		Style est = styleDoc.addStyle(null, null);    //styleDoc.getStyle("default");
       		est.addAttributes(styleDoc.getCharacterElement(indAtual).getAttributes());
       		est.removeAttribute(tipoEstilo);
       		est.addAttribute(tipoEstilo, value);
       	
       		styleDoc.remove(indAtual, 1);
       		styleDoc.insertString(indAtual, texto, est);					
       	} catch (BadLocationException e) {
       		e.printStackTrace();
       	}			
       }
       textPane.grabFocus();
       textPane.select(ini, fim);			
      

      }
      }

    /**

    • Salva por default nos documentos do usuario com o nome a.rtf
      */
      @Deprecated
      private void salvarComoRTF() throws IOException, BadLocationException{
      salvarComoRTF(System.getProperty(“user.home”)+"\a.rtf");
      }

    /**

    • Método que permite salvar o conteúdo do TextFormatPane em um arquivo rtf

    • @param localizacaoRTF, path incluindo o nome do rtf a ser salvo
      */
      private void salvarComoRTF(String localizacaoRTF) throws IOException, BadLocationException{
      StyledDocument styleDoc = (StyledDocument) textPane.getDocument();

      styleDoc.insertString(0, CORINGA, null);

      File tempFile = new File(localizacaoRTF);
      RTFEditorKit editor = new RTFEditorKit();
      FileOutputStream fos = null;

      try {
      fos = new FileOutputStream( tempFile );
      editor.write(fos, styleDoc, 0, styleDoc.getLength());
      } finally {
      if (null != fos) {
      fos.close();
      }
      }
      }

    /**

    • Método que retorna uma String com o texto e as tags de formatação em RTF

    • @return buildString - String que representa o texto formatado em RTF.
      */
      public String getRTFContent() throws IOException, BadLocationException{
      StringBuilder buildString = new StringBuilder();
      salvarComoRTF(pathTempRTF);
      File tempFile = new File(pathTempRTF);

      BufferedReader br = new BufferedReader(new FileReader(tempFile));
      String line = null;
      boolean initContent = false;

      while ((line = br.readLine()) != null) {
      if(!initContent && line.contains(CORINGA)){
      buildString.append(line.substring(0, line.indexOf(CORINGA)-1) +
      line.substring(line.indexOf(CORINGA)+5, line.length()) );
      initContent = true;
      } else if(!initContent){
      buildString.append(line);
      } else {
      buildString.append(" "+line);
      }

      }

      return buildString.toString();
      }

    public File setRTFContent(String content)throws IOException{
    return salvarRTFTemporario(content);
    }

    /**

    • Método que permite salvar uma String em um arquivo rtf

    • @param texto, String a ser salva
      */
      private File salvarRTFTemporario(String texto) throws IOException{
      File arq = new File(pathTempRTF);

      try{
      BufferedWriter grava = new BufferedWriter(new FileWriter(arq));
      grava.write(texto);
      grava.flush();
      grava.close();
      }catch (Exception e) {
      arq = null;
      e.printStackTrace();
      }

      return arq;
      }

    /**

    • Método que cria um arquivo temporário
    • @return File
    • @throws IOException
      */
      private File getTempFile() throws IOException{
      File tempFile = new File(pathTempRTF);
      FileOutputStream out = new FileOutputStream(tempFile);
      out.close();
      return tempFile;
      }

}[/code]

ta faltando o metodo main vc poderia inserir ?

Olá, não se deve usar o Main aí nessa classe(até pode), pois ela está extendendo de JPanel então você pode usá-la em qualquer JFrame, JInternalFrame…

Ummm entendi e como rodo sua aplicacao tem como rodar ela atravez de um jframe? obrigada pela atencao!

Em um JFrame por exemplo você pode fazer o seguinte:

Lembrando que você deve reservar uma área de 605x384 para o editor

Ok, malucocelo! Assim que eu tiver uma versão melhorada, posto aqui!!!

Ok, fique à vontade para melhorar o código e disponibilizar uma nova versão. :smiley:

eu consigui fazer tudo direitinho…soh deu erro na parte do taamnho da fonte…alguem pode me ajudar?

jcbTamanho.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { setStyleValueFor(StyleConstants.FontSize, jcbTamanho.getSelectedItem()); } });

ele da esse erro: Exception in thread “AWT-EventQueue-0” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

Desde já agradeço

Esse erro é de conversão de tipos, se você passa um inteiro para uma String dá erro de Casting e o contrário também, se você pretende converter String para Integer faça:

Se for de Integer para String faça:

nuss pode cre…shuahsuhsuahus…
esqeci completamente vlewwww

outra coisaaaa…quando eu salvo um arquivo ele tem suas “configurações”…se eh negrito ou nao, a fonte, o tamanho da letra, etc…soh q quando eu abro esse arquivo ele abre com as configurações padrao(arial, 12, plain)…tem como abrir o arquivo com as configurações q foram feitas pelo usuario quando o arquivo foi salvo?
desde ja agradeço

Use o metodo salvarComoRTF que ele já faz isso para você.

Hum, este é quase como eu estou procurando…

Queria algo no estilo do ekitCore, ekit 1.7
Ele tem opção de imprimir diretamente no componente…

Só que não está 100% … Alguem conhece outro?

Att. Jonas

Olá esse aqui fui eu que fiz com a colaboração do Usuário 71C4700 que disponibilizou um código inicial que me ajudou a sacar algumas coisas, o código poderia estar melhor se um método que precisei tivesse implementado pelo pessoal do swing( isso mesmo a equipe que desenvolveu o swing deixou pelo menos um método apenas com a assinatura e um comentário dizendo que talvez no futuro ele possa ser escrito), para imprimir tu pode gerar o rtf e verificar como mandar imprimir em java, vou dar uma olhada e se achar algo disponibilizo, se achar a solução, por favor disponibilize aqui.

Boa Tarde Galera,

Estou precisando de uma ajuda.

Quero fazer um editor de texto que insira imagens tbm

Procurando nos foruns eu consegui fazer um bem simples…mas a unica coisa que consigo inserir são botoes. e não uma imagem.
Quero que o usuario escolha uma imagem de qualquer diretorio e a adicione no textpane.

Segue o codigo atual

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

public class PaneInsertionMethods {

  public static void main(String[] args) {

    final JTextPane pane = new JTextPane();

    

    // button to insert a button
    JButton buttonButton = new JButton("Inserir Imagem");
    buttonButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        pane.insertComponent(new JButton("teste"));
      }
    });

    // layout da caixa de Texto
    JPanel buttons = new JPanel(); 
    buttons.add(buttonButton);

    JFrame frame = new JFrame("Caixa de Texto");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(pane, BorderLayout.CENTER);
    frame.getContentPane().add(buttons, BorderLayout.BEFORE_FIRST_LINE);
    frame.setSize(500, 600);
    frame.setVisible(true);
    
    JScrollPane scrollPane = new JScrollPane(pane);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
  }
}
           
         

Abraços…

Dei uma modificada pra tentar abrir uma janela para selecionar o arquivo desejado mas está dando erro no showOpenDialog

segue codigo:


mport java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

public class EditorTexto {

  public static void main(String[] args) {

    final JTextPane pane = new JTextPane();

    

    // button to insert a button
    JButton botao = new JButton("Inserir Imagem");
    
    botao.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
    	  
    		  JFileChooser arquivo = new JFileChooser();  
    		  arquivo.showOpenDialog(this);  
    		  arquivo.setVisible(true);
    		  
    	  
    	  
    	  
      }
    });

    // layout da caixa de Texto
    JPanel buttons = new JPanel(); 
    buttons.add(botao);

    JFrame frame = new JFrame("Caixa de Texto");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(pane, BorderLayout.CENTER);
    frame.getContentPane().add(buttons, BorderLayout.BEFORE_FIRST_LINE);
    frame.setSize(500, 600);
    frame.setVisible(true);
    
    JScrollPane scrollPane = new JScrollPane(pane);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
  }
}
           
         

alguem conseguiu implementar isso

http://www.guj.com.br/posts/list/222295.java