4
我试图让JTextPane
根据我提供的任何内容来调整其高度。我所能做的就是使用Dimension设置固定的像素高度。使JTextPane将高度调整为内容
我该如何使JTextPane
折叠/展开以适应内容?
我可能会补充说,我在GridBagLayout
'JPanel
'中使用了这个,它已被添加到JScrollPane
。
我试图让JTextPane
根据我提供的任何内容来调整其高度。我所能做的就是使用Dimension设置固定的像素高度。使JTextPane将高度调整为内容
我该如何使JTextPane
折叠/展开以适应内容?
我可能会补充说,我在GridBagLayout
'JPanel
'中使用了这个,它已被添加到JScrollPane
。
我不知道任何直接的方式做到这一点,但是这可能给你一些想法:
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);
}
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);
}
}
JTextPane tp = new JTextPane();
setLayout(new BorderLayout()); // set layout on parent
add(tp, BorderLayout.CENTER);
这对我的作品。
它的工作,然后不是。 modelToView返回null。根据文件,组件必须已经确定尺寸才能工作。我试过验证(),repaint(),pack(),但没有任何帮助。我是否需要在某个祖先组件上调用这些方法之一? JTextPane被添加到一个JPanel中,该JPanel存在于一个JPanel中,该JPanel又被添加到一个JFrame中的JScrollPane中... – fiskeben 2009-07-15 21:14:30