这是关于Java和Swing的问题。
我将两个JEditorPane放入两个JScrollPane中,然后将两个JScrollPane放入一个JSplitPane中。问题是当我拖动以调整JScrollPane的大小时,会扩展一个JEditorPane,但是当我向后拖动时,视图会缩小但编辑区域不会缩小,水平滚动条会出现。
代码如下所示:
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
public class Main {
private static final int DEFAULT_WIDTH = 800;
private static final int DEFAULT_HEIGHT = 600;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
JEditorPane editor = new JEditorPane();
JEditorPane preview = new JEditorPane();
System.out.println(DEFAULT_WIDTH / 2);
// editor.setSize(DEFAULT_WIDTH / 2, DEFAULT_HEIGHT);
editor.setMinimumSize(new Dimension(0, 0));
// preview.setSize(DEFAULT_WIDTH / 2, DEFAULT_HEIGHT);
preview.setMinimumSize(new Dimension(0, 0));
final JScrollPane scrollEditor = new JScrollPane(editor);
final JScrollPane scrollPreview = new JScrollPane(preview);
final JSplitPane innerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollEditor, scrollPreview);
innerPane.setContinuousLayout(false);
frame.add(innerPane, BorderLayout.CENTER);
innerPane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
editor.setSize(innerPane.getLeftComponent().getBounds().width, editor.getHeight());
scrollEditor.setSize(innerPane.getLeftComponent().getBounds().width, editor.getHeight());
}
});
frame.setVisible(true);
}
});
}
}
我尝试使用JEditorPane.setSize,但它不起作用。
我该如何解决?
感谢。
答案 0 :(得分:2)
您需要覆盖Scrollable
的{{1}}界面的默认实现。基本上你需要告诉JScrollPane,JEditorPane的宽度应该总是适合滚动窗格的视口。
您可以使用以下代码执行此操作:
JEditorPane
正如我在评论中提到的,你不需要PropertyChangeListener。
答案 1 :(得分:0)
final JScrollPane scrollEditor = new JScrollPane(editor, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
final JSplitPane innerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, scrollEditor, scrollPreview);
innerPane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
editor.setSize(innerPane.getLeftComponent().getBounds().width, editor.getHeight() - 10); // If you want more edge space make 10 to 15 or 20
scrollEditor.setSize(innerPane.getLeftComponent().getBounds().width, editor.getHeight());
}
});