java控制组件,java – 使JScrollPane控制多个组件

对于我的应用程序,我正在设计脚本编辑器.目前我有一个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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值