我明白的JTextPane不自然環繞文字
這是不對的。默認情況下,JTextPane將包裝文本。
請參閱Text Pane No Wrap瞭解關於此主題的更多信息,這些信息構成了下面解決方案的基礎。
您需要覆蓋getScrollableTrackViewportWidth()
方法。我覺得應該是:
JTextPane textPane = new JTextPane()
{
public boolean getScrollableTracksViewportWidth()
{
return getParent().getSize().width > 100;
}
};
編輯:
這個問題似乎是相關的文本窗格中的文本。不知道如果是文本或文本中的非字母字符導致的不同長度:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TextPaneNoWrap
{
private static void createAndShowGUI()
{
JTextPane textPane = new JTextPane()
{
@Override
public boolean getScrollableTracksViewportWidth()
{
Dimension d = getParent().getSize();
System.out.println(d);
return false;
}
};
textPane.setText("one two three four five six\nthis wraps at 39");
// textPane.setText("import javax.swing.event.*;\nthis wraps at 111");
JFrame frame = new JFrame("TextPaneNoWrap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Some Component"), BorderLayout.LINE_START);
frame.add(new JScrollPane(textPane));
frame.setSize(300, 100);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() -> createAndShowGUI());
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
EDIT2:
似乎用「包裝」面板時工作確定該實現Scrollable接口:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TextPaneNoWrap
{
private static void createAndShowGUI()
{
JTextPane textPane = new JTextPane();
// textPane.setText("one two three four five six\nthis wraps at 39");
textPane.setText("import javax.swing.event.*;\nthis wraps at 111");
JPanel wrapper = new NoWrapPanel(textPane);
JFrame frame = new JFrame("TextPaneNoWrap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Some Component"), BorderLayout.LINE_START);
frame.add(new JScrollPane(wrapper));
frame.setSize(300, 100);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
static class NoWrapPanel extends JPanel implements Scrollable
{
public NoWrapPanel(JComponent component)
{
setLayout(new BorderLayout());
add(component);
}
@Override
public Dimension getPreferredScrollableViewportSize()
{
return getPreferredSize();
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
{
return 20;
}
@Override
public boolean getScrollableTracksViewportHeight()
{
return true;
}
@Override
public boolean getScrollableTracksViewportWidth()
{
// return false;
return getParent().getSize().width > 100;
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
{
return 10;
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(() -> createAndShowGUI());
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
在你的paintComponent方法中使用'if(this.getWidth> 100)...'。 – Nathan
因此,將ComponentListener添加到您的文本窗格並根據大小切換打開/關閉包裝。 – StanislavL