【发布时间】:2020-09-01 08:50:39
【问题描述】:
我有这样一段代码,应该在JTextArea 上添加按钮放在JScrollPane 中。按钮不在滚动窗格内!
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 340, 375, 242);
contentPane.add(scrollPane);
JButton btnClean = new JButton();
btnClean.setBounds(340, 341, 26, 23);
contentPane.add(btnClean);
taLog = new JTextArea();
taLog.setEditable(false);
taLog.setLineWrap(true);
taLog.setFont(new Font("Arial", Font.PLAIN, 12));
scrollPane.setViewportView(taLog);
epInfo = new JEditorPane();
epInfo.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
epInfo.setFont(new Font("Tahoma", Font.PLAIN, 12));
epInfo.setContentType("text/html");
epInfo.setEditable(false);
epInfo.setBackground(null);
epInfo.setBorder(null);
epInfo.setBounds(10, 241, 375, 37);
setInfoText();
contentPane.add(epInfo);
问题是每当JTextArea 更改其值时,按钮都不会刷新 - 它只是消失了 - 直到我将鼠标光标拖到它上面。我想随后会启动一些repaint()。
我发现我可以将DocumentListener 添加到JTextArea 并手动刷新按钮,但它可以工作,直到滚动条出现在JScrollPane 中。
我也可以用
scrollPane.getViewport().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e)
{}});
但它被多次调用,所有这些刷新都不是必需的。
是否有任何合理(有效)的方法来检查JScrollPane 是否更改?
【问题讨论】:
-
不要使用空布局。不要使用 setBounds()。 Swing 旨在与布局管理器一起使用。我无法建议使用哪个布局管理器,因为我不了解您想要的布局。发布图片或使用 ascii 艺术来展示您想要的布局。
-
@camickr Null 布局在这种情况下很有用,因为主窗口是固定的。我也在 Eclipse 中使用 WindowBuilder,然后我不手动放置 XY。我添加了图片。按钮在红色圆圈中。
标签: java swing jbutton jscrollpane