我是一个使用NetBeans的Swing新手。我想要垂直滚动两个并排的JTextPane。滚动应该同步,并通过单个滚动条完成。
如果我从NetBean设计器中添加JTextPanes,它们会自动放置在JScrollPane中,因此它们可以独立滚动。我已经删除了包含的滚动窗格,并将它们放在JPanel中,以便JPanel可以成为单个JScrollPane的客户端。这似乎有效,但当JTextPanes非常长时,它们似乎超出了JPanel的末端。我可以滚动面板和两个文本窗格到一定程度。当我到达底部时,我可以在其中一个文本窗格中放置一个光标并向下箭头超出我的视野范围。
这是我的主要方法中的代码。我复制了由NetBeans设计器生成的布局。
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
topFrame aTopFrame = new topFrame();
JScrollPane scollBothDiffs = new javax.swing.JScrollPane();
JPanel bothDiffsPanel = new javax.swing.JPanel();
JTextPane leftDiffPane = diffPane1;
JTextPane rightDiffPane = diffPane2;
javax.swing.GroupLayout bothDiffsPanelLayout = new javax.swing.GroupLayout(bothDiffsPanel);
bothDiffsPanel.setLayout(bothDiffsPanelLayout);
bothDiffsPanelLayout.setHorizontalGroup(
bothDiffsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bothDiffsPanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(leftDiffPane, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rightDiffPane, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(52, Short.MAX_VALUE))
);
bothDiffsPanelLayout.setVerticalGroup(
bothDiffsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bothDiffsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(bothDiffsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(rightDiffPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
.addComponent(leftDiffPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE))
.addContainerGap())
);
scollBothDiffs.setViewportView(bothDiffsPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(aTopFrame.getContentPane());
aTopFrame.getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(scollBothDiffs, javax.swing.GroupLayout.DEFAULT_SIZE, 997, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(scollBothDiffs, javax.swing.GroupLayout.DEFAULT_SIZE, 671, Short.MAX_VALUE)
.addContainerGap())
);
aTopFrame.pack();
aTopFrame.setVisible(true);
}
});
这里有一张图片展示了我对第一个答案的实现,其中文本窗格不限于水平显示区域。
![图片展示了文本窗格宽度超出水平显示区域](https://istack.dev59.com/anncN.webp)