How to apply Stylededitorkit to a Jtextpane without inheriting this class on my screen?

Asked

Viewed 207 times

6

I have a problem with tabulation in JTextPane and I’m trying to reduce the default value assigned to it but it’s giving an error because I have to inherit two classes (one for the JFrame and the other to overwrite the tab functions) but Java apparently, the way I’m trying not to accept it, follows the code:

import javax.lang.model.element.Element;
import javax.swing.JFrame;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.StyleConstants;
import static javax.swing.text.StyleConstants.TabSet;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.TabSet;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;



public class TAB extends javax.swing.JFrame,StyledEditorKit  {
public static final int TAB_SIZE=36;
    /**
     * Creates new form TAB
     */
    public TAB() {
        initComponents();

    }
     @Override
    public ViewFactory getViewFactory() {
        return new MyViewFactory();
    }
    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jTextPane1);

        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.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(56, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */





    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                new TAB().setVisible(true);
            }
        });
        class MyViewFactory implements ViewFactory {

        @Override
        public View create(javax.swing.text.Element elem) {
            String kind = elem.getName();
            if (kind != null) {
                if (kind.equals(AbstractDocument.ContentElementName)) {
                    return new LabelView(elem);
                } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                    return new CustomTabParagraphView(elem);
                } else if (kind.equals(AbstractDocument.SectionElementName)) {
                    return new BoxView(elem, View.Y_AXIS);
                } else if (kind.equals(StyleConstants.ComponentElementName)) {
                    return new ComponentView(elem);
                } else if (kind.equals(StyleConstants.IconElementName)) {
                    return new IconView(elem);
                }
            }

            return new LabelView(elem);
        }
    }


    class CustomTabParagraphView extends ParagraphView {

        public CustomTabParagraphView(javax.swing.text.Element elem) {
            super(elem);
        }

        @Override
        public float nextTabStop(float x, int tabOffset) {
            TabSet tabs = getTabSet();
            if(tabs == null) {
                // a tab every 72 pixels.
                return (float)(getTabBase() + (((int)x / TAB_SIZE + 1) * TAB_SIZE));
            }

            return super.nextTabStop(x, tabOffset);
        }

    }

    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration                   
}

Does anyone know how to solve this problem?

  • 1

    There is no multiple java inheritance. Use composition for one of the two inherited classes (in this case, I recommend doing this for Jframe)

  • Possible duplicate of Java has no multiple inheritance?

2 answers

6

Java does not have multiple inheritance by design. Java creators decided that providing multiple inheritance would add too much complexity and too few benefits to the language.

For example, what to do when two classes define the same method and a third class tries to extend the first two?

public class Humano {
    public void Andar() {
        // Andar feito Humano
    }
}

public class Robo {
    public void Andar() {
        // Andar feito Robo
    }
}

public class Ciborgue extends Humano, Robo {
    // O ciborgue andaria como robo ou humano? 
}

Consider using composition. Choose a class for TAB extend and maintain a reference from one instance of the other class. Example:

// imports...

public class TAB extends javax.swing.JFrame {
    private StyledEditorKit editorKit;

    public TAB(){
        editorKit = new StyledEditorKit();
    }

    public void FazerAlgoComEditorKit(){
        // Use a propriedade editorKit
    }
}
  • Just one detail, the class StyledEditorKit is not part of a Jframe, but part of a specific component that will be part of Jframe, in this case, JEditorPane. I believe that turning into an attribute is not necessary.

4


In the case of your code, just separate the class TabSizeEditorKit of its screen class and instantiating within the method setEditorKit(), as shown in the example of another answer.

Would something like this:

import java.awt.EventQueue;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;

    public class Tela extends JFrame {

        private JPanel contentPane;
        private JEditorPane editorPane;


        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        Tela frame = new Tela();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         * @throws BadLocationException 
         */
        public Tela() throws BadLocationException {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 332, 300);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);

            editorPane = new JEditorPane();
            GroupLayout gl_contentPane = new GroupLayout(contentPane);
            gl_contentPane.setHorizontalGroup(
                gl_contentPane.createParallelGroup(Alignment.LEADING)
                    .addGroup(gl_contentPane.createSequentialGroup()
                        .addGap(31)
                        .addComponent(editorPane, GroupLayout.PREFERRED_SIZE, 251, GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(142, Short.MAX_VALUE))
            );
            gl_contentPane.setVerticalGroup(
                gl_contentPane.createParallelGroup(Alignment.LEADING)
                    .addGroup(gl_contentPane.createSequentialGroup()
                        .addGap(37)
                        .addComponent(editorPane, GroupLayout.PREFERRED_SIZE, 186, GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(29, Short.MAX_VALUE))
            );
            contentPane.setLayout(gl_contentPane);
            //aqui que você seta o editorkit customizado
            //para o editorpane
            editorPane.setEditorKit(new TabSizeEditorKit());
        }
    }

and the class TabSizeEditorKit you remove the main and leaves only the essentials for it to function:

import javax.swing.text.*;


public class TabSizeEditorKit extends StyledEditorKit {

    public static final int TAB_SIZE=36;

    @Override
    public ViewFactory getViewFactory() {
        return new MyViewFactory();
    }

    static class MyViewFactory implements ViewFactory {

        @Override
        public View create(Element elem) {
            String kind = elem.getName();
            if (kind != null) {
                if (kind.equals(AbstractDocument.ContentElementName)) {
                    return new LabelView(elem);
                } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                    return new CustomTabParagraphView(elem);
                } else if (kind.equals(AbstractDocument.SectionElementName)) {
                    return new BoxView(elem, View.Y_AXIS);
                } else if (kind.equals(StyleConstants.ComponentElementName)) {
                    return new ComponentView(elem);
                } else if (kind.equals(StyleConstants.IconElementName)) {
                    return new IconView(elem);
                }
            }

            return new LabelView(elem);
        }
    }


    static class CustomTabParagraphView extends ParagraphView {

        public CustomTabParagraphView(Element elem) {
            super(elem);
        }

        @Override
        public float nextTabStop(float x, int tabOffset) {
            TabSet tabs = getTabSet();
            if(tabs == null) {
                // a tab every 72 pixels.
                return (float)(getTabBase() + (((int)x / TAB_SIZE + 1) * TAB_SIZE));
            }

            return super.nextTabStop(x, tabOffset);
        }

    }
}

As you will only make use of TabSizeEditorKit just for the sake of spacing, there’s no need to turn it into a class attribute.

  • we’re almost there. I’ve already adjusted the spacing to the size I wanted but it still keeps showing those values at the start. There’s a way he doesn’t show it so I don’t have to overwrite jTextPane every time I start ?

  • Okay, now it’s working. Thanks for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.