对于我的应用程序,我正在设计脚本编辑器.目前我有一个JPanel,其中包含另一个保存行号(位于左侧)的JPanel,以及一个JTextArea,用于允许用户键入其代码(位于右侧).
目前,我已在JTextArea上实现了一个JScrollPane,以允许用户滚动其代码.
对于包含行号的JPanel,每次用户按下回车键时,它们都会递增.
但是,问题是我想要相同的JScrollPane(在JTextArea上实现的那个)来控制行号JPanel的滚动;即,当用户在JTextArea上滚动时,行号JPanel也应该滚动.但由于行号保存在JPanel中,我无法将该组件添加到JTextArea.
包含JTextArea和行号JPanel的JPanel类的构造函数:
private ScriptEditor() {
setBackground(Color.WHITE);
lineNumPanel = new LineNumberPanel();
scriptArea = new JTextArea();
scriptArea.setLineWrap(true);
scriptArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
scriptArea.setMargin(new Insets(3, 10, 0, 10));
JScrollPane scrollPane = new JScrollPane(scriptArea);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setPreferredSize(new Dimension(width, height));
scriptArea.addKeyListener(this);
add(lineNumPanel);
add(scrollPane);
}
行号JPanel的构造函数,它在其自身中添加JLabel以表示行号:
public LineNumberPanel() {
setPreferredSize(new Dimension(width, height));
box = Box.createVerticalBox();
add(box);
//setup the label
label = new JLabel(String.valueOf(lineCount));
label.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
//setup the label alignment
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
setAlignmentY(TOP_ALIGNMENT);
box.add(label);
}
解决方法:
创建一个外部面板,其中包含“行号”面板和“文本区域”.
然后将这个新面板放入Scroll Pane中,这样你就可以得到这样的安排:
在代码中是这样的:
private ScriptEditor() {
setBackground(Color.WHITE);
JPanel outerPanel = new JPanel();
lineNumPanel = new LineNumberPanel();
scriptArea = new JTextArea();
scriptArea.setLineWrap(true);
scriptArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
scriptArea.setMargin(new Insets(3, 10, 0, 10));
outerPanel.add(lineNumPanel, BorderLayout.WEST)
outerPanel.add(scriptArea, BorderLayout.CENTER)
JScrollPane scrollPane = new JScrollPane(outerPanel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setPreferredSize(new Dimension(width, height));
scriptArea.addKeyListener(this);
add(lineNumPanel);
add(scrollPane);
}
标签:jtextarea,java,swing,jscrollpane
来源: https://codeday.me/bug/20190923/1814386.html