这段代码是我写的。在这里,我想让 JScrollPane 与 JTextArea 一起使用。但它根本不起作用。早些时候我几乎做了同样的事情。它曾经有效。请提供解决方案。提前致谢。我已经发布了代码。
protected void startServerProcess(int port) {
serverFrame = new JFrame("SERVER NOTIFICATIONS PANEL | Labyrinth Developers");
serverFrame.setSize(500, 500);
serverFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
serverFrame.setLocationByPlatform(true);
serverFrame.setLocationRelativeTo(null);
serverFrame.setVisible(true);
notificationsTA = new JTextArea();
notificationsTA.setBounds(0,0,466,500);
notificationsTA.setLineWrap(true);
notificationsTA.setRows(1000);
notificationsSP = new JScrollPane();
notificationsSP.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
notificationsSP.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
notificationsSP.setViewportView(notificationsTA);
notificationsSP.setWheelScrollingEnabled(true);
notificationsSP.setBounds(470, 0, 30, 500);
serverFrame.add(notificationsTA);
serverFrame.add(notificationsSP);
}
最佳答案
JTextArea
已添加到 JScrollPane
中,因此无需在 JFrame
中再次添加它。删除以下行:
serverFrame.add(notificationsTA);
您可以使用其 Constructor 将组件添加到滚动 Pane 的视口(viewport)中以及内部调用 JScrollPane#setViewport()方法。
notificationsSP = new JScrollPane(notificationsTA);
<小时/>
一些要点:
JFrame默认使用 BorderLayout并且您只能在每个部分(北、南、东、西和中心)添加单个组件。
添加完所有组件后最后调用
serverFrame.setVisible(true);
。根本不要使用
setBounds()
。只需将其留给布局管理器来设置组件的大小和位置即可。使用
SwingUtilities.invokeLater()
确保 EDT已正确初始化。了解更多
关于java - 如何将 JScrollPane 与 JTextArea 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24095964/