Resize TAB spacing in Jtextpane

Asked

Viewed 263 times

2

I want to change the tab key of jTextPane because it has many spaces, for example:

It is currently found like this:

Uma casa azul 

// após TAB

                Uma casa azul 

And what I want would be like this :

Uma casa azul 

// após TAB

       Uma casa azul 

You can do it?

Follow an example of my code:

public class TAB extends javax.swing.JFrame {

    /**
     * Creates new form TAB
     */
    public TAB() {
        initComponents();
    }

    /**
     * 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();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jTextPane1);

        jLabel1.setText("Como mudar o TAB ?");

        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)
            .addGroup(layout.createSequentialGroup()
                .addGap(151, 151, 151)
                .addComponent(jLabel1)
                .addContainerGap(150, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(24, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .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);
            }
        });
    }

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

And that’s all the main class does :

 new TAB().setVisible(true);
  • 1

    Please. add a code with the mentioned problem, which is a [mcve] so that it is possible to evaluate possible solutions. I suggest you also read [Ask]

  • I have a jTextPane and I want its TAB not to be too exaggerated (like the default value). It’s just.

  • Without seeing the code to test, it becomes complicated to help. I recommend reading [Ask]

  • Example code inserted in the query

1 answer

4


Need to change the way the method nextTabStop() class ParagraphView works. In the example below, the constant TAB_SIZE is that you are setting the size between these tabs, in pixels, just change according to what you think is best for your component:

import javax.swing.text.*;
import javax.swing.*;

public class TabSizeEditorKit extends StyledEditorKit {

    public static final int TAB_SIZE=36;

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


    public static void main(String[] args) {
        JFrame frame=new JFrame("Custom default Tab Size in EditorKit example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JEditorPane edit=new JEditorPane();
        edit.setEditorKit(new TabSizeEditorKit());
        try {
            edit.getDocument().insertString(0,"1\t2\t3\t4\t5", new SimpleAttributeSet());
        } catch (BadLocationException e) {
            e.printStackTrace(); 
        }
        frame.getContentPane().add(new JScrollPane(edit));

        frame.setSize(300,100);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

    }
}

Which results in:

inserir a descrição da imagem aqui


Reference:

  • Edited question

  • @Beto you seem to have changed the doubt, which was like reducing the size of the tab. That would be another question and not an edit.

Browser other questions tagged

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