Editor de texto em aplicação java Swing!

Boa tarde pessoal !!

Estou com desenvolvendo um sistema de controle ortodontico e preciso de ajuda pra desenvolver um pequeno editor de textos, que seja incorporado na aplicação, com ferramentas como stilo do texto, tamanho, cor, fonte, pra editar e imprimir atestados médicos e outros documentos direto do meu sistema. Se alguem puder ajudar eu agradeço.

Acho que os componentes JEditorPane e JTextPane são adequados à sua necessidade:

http://java.sun.com/docs/books/tutorial/uiswing/components/text.html

certa vez fiz um editor de texto txt bem simples só por diversão rsrsrs
acho que pode ser util
segue o código

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;

public class EditorTxt extends JFrame {
	private JPanel panelCentral = new JPanel();
	private JPanel panelInferior = new JPanel();
	private JScrollPane jscroll = new JScrollPane();
	private JTextArea areaTexto = new JTextArea();
	private JButton salvar = new JButton("Salvar");
	private JButton abrir = new JButton("Abrir");
	private JButton sair = new JButton("Sair");
	private String arquivo;

	public EditorTxt() {
		initComponents();
		this.setTitle("Editor Txt Simples");
		this.setSize(300, 250);
		this.setMinimumSize(new Dimension(300, 250));
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}

	public void initComponents() {
		this.setLayout(new BorderLayout());
		panelCentral.setBorder(new TitledBorder("Texto"));
		panelCentral.setLayout(new BorderLayout());

		jscroll.add(areaTexto);
		jscroll.setViewportView(areaTexto);
		panelCentral.add(jscroll, BorderLayout.CENTER);

		panelInferior.setLayout(new FlowLayout(FlowLayout.RIGHT));
		panelInferior.add(abrir);
		panelInferior.add(salvar);
		panelInferior.add(sair);

		this.add(panelCentral, BorderLayout.CENTER);
		this.add(panelInferior, BorderLayout.PAGE_END);

		abrir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				Action(evt);
			}
		});

		salvar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				Action(evt);
			}
		});

		sair.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				Action(evt);
			}
		});
	}

	public void Action(ActionEvent evt) {
		if (evt.getSource().equals(abrir)) {
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.showOpenDialog(this);
			fileChooser.setVisible(true);
			ler(fileChooser.getSelectedFile());
		} else if (evt.getSource().equals(salvar)) {
			escrever(new File(arquivo));
		}else if(evt.getSource().equals(sair)){
			System.exit(0);
		}
	}

	public void ler(File file) {
		arquivo = file.getAbsolutePath();
		try {
			areaTexto.setText("");
			Scanner scanner = new Scanner(file);
			while (scanner.hasNext()) {
				areaTexto.append(scanner.nextLine() + "\n");
			}
			scanner.close();
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(this, "Arquivo não encontrato", "ERRO", JOptionPane.ERROR_MESSAGE);
		}
	}

	public void escrever(File file) {
		try {
			FileWriter escrever = new FileWriter(file);
			escrever.write(areaTexto.getText());
			escrever.close();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "Não foi possível salvar o arquivo", "ERRO", JOptionPane.ERROR_MESSAGE);
		}
	}

	public static void main(String args[]) {
		EditorTxt edit = new EditorTxt();
		edit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
1 curtida

até ai tudo bem, mas queria saber se alguem tem alguma referencia de como implementar estilo (negrito, italico e sublinhado), como colocar as fontes dentro de uma combobox, etc. Dei uma olhada na documentação que o “roger_rf” postou, mas ainda não vi como implementar essas funcionalidades.

Seria o que o Marlon Meneses postou com as outras funcionalidades.

Amigo dê uma olhada nas classes StyledDocument e StyleConstants vai encontrar o que precisa.

Fiz um exemplo alterando cor, fonte, tamanho, negrito,itálico,sublinhado

não repara o código porco hehehe

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Janela extends JFrame implements ActionListener {

    private JCheckBox negrito = new JCheckBox("Negrito");
    private JCheckBox italico = new JCheckBox("Itálico");
    private JCheckBox sublinhado = new JCheckBox("Sublinhado");
    private JComboBox fontes = new JComboBox();
    private JComboBox tamanho = new JComboBox();
    private JTextPane areaDeTexto = new JTextPane();
    private JPanel painelEstilo = new JPanel();
    private JScrollPane scroll = new JScrollPane();
    private JColorChooser escolherCor = new JColorChooser();
    private JButton botao = new JButton("Escolher Cor");
    private Color cor = null;

    public Janela() {

        configuraJanela();

        scroll.add(areaDeTexto);
        scroll.setViewportView(areaDeTexto);
        this.add(scroll, BorderLayout.CENTER);

        botao.addActionListener(this);

        negrito.addActionListener(this);
        italico.addActionListener(this);
        sublinhado.addActionListener(this);
        fontes.addActionListener(this);
        tamanho.addActionListener(this);
        painelEstilo.add(negrito);
        painelEstilo.add(italico);
        painelEstilo.add(sublinhado);
        painelEstilo.add(botao);
        adicionaTamanhosNaCombo(tamanho);
        adicionaFontesNaCombo(fontes);
        tamanho.setSelectedIndex(3);
        fontes.setSelectedIndex(2);
        painelEstilo.add(fontes);
        painelEstilo.add(tamanho);
        this.add(painelEstilo, BorderLayout.SOUTH);

        this.setVisible(true);
    }

    private void adicionaFontesNaCombo(JComboBox combo) {
        String[] fontes = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getAvailableFontFamilyNames();
        for (String fonte : fontes) {
            combo.addItem(fonte);
        }
    }

    private void adicionaTamanhosNaCombo(JComboBox combo) {
        for (int i = 8; i <= 72; i += 2) {
            combo.addItem(i);
        }
    }

    private void configuraJanela() {
        this.setSize(400, 400);
        this.setTitle("TESTE ESTILO");
        this.setLayout(new GridLayout(2, 0));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand() == "Escolher Cor") {
            cor = escolherCor.showDialog(null, "Selecione", Color.BLACK);
        }
        modificaEstilo();
    }

    public static void main(String[] args) {
        new Janela();
    }

    public void modificaEstilo() {
        StyledDocument documento = (StyledDocument) areaDeTexto.getDocument();
        Style estilo = documento.getStyle(documento.addStyle("StyleAdd", null)
                .getName());

        // sublinhado, negrito, itálico
        StyleConstants.setBold(estilo, negrito.isSelected());
        StyleConstants.setItalic(estilo, italico.isSelected());
        StyleConstants.setUnderline(estilo, sublinhado.isSelected());

        // cor
        if (cor != null) {
            StyleConstants.setForeground(estilo, cor);
        }

        // fonte
        String fonte = (String) fontes.getSelectedItem();
        if (fonte != null) {
            StyleConstants.setFontFamily(estilo, fonte);
        }

        // tamanho
        int tamanhoFonte = 8;
        tamanhoFonte = (Integer) tamanho.getSelectedItem();
        StyleConstants.setFontSize(estilo, tamanhoFonte);

        String textoFormatado = areaDeTexto.getText();
        areaDeTexto.setText("");
        documento.addStyle("Style", estilo);

        try {
            documento.insertString(documento.getLength(), textoFormatado,
                    estilo);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }

    }

}

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);
  }
}