How can I measure/calculate the size a Document needs to render itself?

后端 未结 3 2129
庸人自扰
庸人自扰 2020-11-28 15:34

I have a javax.swing.text.Document and I want to calculate the size of the bounding box that document needs to render itself.

Is that possible?

相关标签:
3条回答
  • 2020-11-28 16:05

    This code might give you some ideas:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class TextPanePerfectSize extends JFrame
    {
        JTextField textField;
        JTextPane textPane;
    
        public TextPanePerfectSize()
        {
            textField = new JTextField(20);
            textField.setText("add text");
            getContentPane().add(textField, BorderLayout.NORTH );
            textField.addActionListener( new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    try
                    {
                        Document doc = textPane.getDocument();
                        doc.insertString(doc.getLength(), " " + textField.getText(), null);
                        textField.setText("");
                        Dimension d = textPane.getPreferredSize();
                        Rectangle r = textPane.modelToView( textPane.getDocument().getLength() );
                        d.height = r.y + r.height;
                        textPane.setPreferredSize( d );
                        getContentPane().validate();
    //                  pack();
                    }
                    catch(Exception e2) {}
                }
            });
    
            JLabel label = new JLabel("Hit Enter to Add Text to Text Pane");
            getContentPane().add(label);
    
            JPanel south = new JPanel();
            textPane = new JTextPane();
            textPane.setText("Some text");
            textPane.setEditable( false );
    //      textPane.setPreferredSize( new Dimension(120, 23) );
    
            south.add( textPane );
    //      getContentPane().add(south, BorderLayout.SOUTH);
            getContentPane().add(textPane, BorderLayout.SOUTH);
        }
    
        public static void main(String[] args)
        {
            JFrame frame = new TextPanePerfectSize();
            frame.setSize(200, 200);
            frame.setLocationRelativeTo( null );
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 16:23

    The Document interface is a model for a text component, so the Document doesn't really have a boundary; but the View has a number of methods that "translate between the model and view coordinate systems." Depending on the goal, something there may help.

    0 讨论(0)
  • 2020-11-28 16:23

    Try to use this to measure height for fixed widht. http://java-sl.com/tip_text_height_measuring.html

    The getPreferred will return you the width and height.

    0 讨论(0)
提交回复
热议问题