Editor HTML

8 respostas
carlosmaniero

Olá pessoal, sou novo no forúm e novo em java tambem pra falar a verdade comecei com java a três dias,
eu já programava PHP então OO pra mim foi facinho, a unica coisa que não estou me dando muito bem é swing,
ai pra isso eu uso o netBeans.

Então vamos ao meu problema eu encontrei esse pacote javax.swing.text.html que pode ser utilizado para criar um editor mais o problema é a forma que eu aplico ele procurei vários tutoriais mais não concegui aplicar nenhuma de suas classes.

Se alguem me ajudar a deixar só um texto em negrito utilizando o netbenas o resto eu consigo me virar;

já tenho um JEditorPane, no meu caso está nomeado de campo e um botao para deixar em negrito no caso botaoNegrito.

8 Respostas

L

Você tem que criar uma classe que estende de StyledEditorKit.StyledTextAction e implementar os métodos dela.

Anime

Oi carlosmaniero,

Nesta apostila ensina como deixar em negrito,mas não sei se tem algo com html,da uma olhadinha.

Baixe ela nesse link http://acervobrasil.blogspot.com/2008/10/apostila-java-2-com-banco-de-dados.html

Boa sorte!

carlosmaniero

não era isso não, essa apostila só ensina como ultilizar a class Font tentei utilizar ela mais não funciona.
mais mesmo assim obrigado.

carlosmaniero

lynux100 você poderia me dar um exemplo de como fazer isso?
grato.

L

A classe é essa abaixo. Agora você tem que criar um JButton passando como parâmetro a instância dela.

public class BoldAction extends StyledEditorKit.StyledTextAction {

	public BoldAction() {		
		super("");
	}

	public void actionPerformed(ActionEvent e) {
		JEditorPane editor = getEditor(e);
			if ( editor != null ) {
			StyledEditorKit kit = getStyledEditorKit ( editor ) ;
			MutableAttributeSet attr = kit.getInputAttributes();
			boolean bold = ( StyleConstants.isBold( attr )) ? false : true ;
			SimpleAttributeSet sas = new SimpleAttributeSet () ;
			StyleConstants.setBold(sas, bold);
			setCharacterAttributes(editor, sas, false);
		}
	}
carlosmaniero

Cara acho que eu sou muito burro,
quando você me falou do StyledEditorKit.StyledTextAction eu procurei na internet sobre o assunto e até achei esse metodo ai mais não consegui aplicar ao meu botão,
segue o código abaixo:

import java.awt.event.ActionEvent;
import javax.swing.JEditorPane;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
/*
 * editor.java
 *
 * Created on 10 de Outubro de 2010, 09:50
 */

/**
 *
 * @author  Carlos Maniero
 */
public class editor extends javax.swing.JFrame {
    
    /** Creates new form editor */
    public editor() {
        initComponents();
        botaoNegrito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionPerformed(evt);
            }
        });
    }
    public class BoldAction extends StyledEditorKit.StyledTextAction {

    public BoldAction() {        
        super("");
    }

    public void actionPerformed(ActionEvent e) {
        JEditorPane editor = getEditor(e);
            if ( editor != null ) {
            StyledEditorKit kit = getStyledEditorKit ( editor ) ;
            MutableAttributeSet attr = kit.getInputAttributes();
            boolean bold = ( StyleConstants.isBold( attr )) ? false : true ;
            SimpleAttributeSet sas = new SimpleAttributeSet () ;
            StyleConstants.setBold(sas, bold);
            setCharacterAttributes(editor, sas, false);
        }
    }
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        editor = new javax.swing.JEditorPane();
        botaoNegrito = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jScrollPane1.setViewportView(editor);

        botaoNegrito.setText("negrito");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addComponent(botaoNegrito, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botaoNegrito, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        pack();
    }// </editor-fold>                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new editor().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton botaoNegrito;
    private javax.swing.JEditorPane editor;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                   
    
}
L

Tenta assim:

public class Editor extends javax.swing.JFrame {

     private BoldAction boldAction;
     private JButton boldJButton;


     public Editor() {
           
           boldAction = new BoldAction();
           boldJButton = new javax.swing.JButton(boldAction);
     }

}

Eu trabalho com JTextPane.

carlosmaniero

Cara funcionou!!!
o problema é que eu colocava o código depois do metodo initComponents(); porque o netbeans não permite editar o código que ele gera,
ai eu abri com a melhor IDE que já inventaram (notepad)…rs
ai funcionou certinho.

brigadão ai. :stuck_out_tongue:

Criado 9 de outubro de 2010
Ultima resposta 10 de out. de 2010
Respostas 8
Participantes 3