我写了这段代码。在这里,我想让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);
}
答案 0 :(得分:2)
JTextArea
已添加到JScrollPane
中,因此无需再次在JFrame
中添加它。删除以下行:
serverFrame.add(notificationsTA);
您可以使用其Constructor以及内部调用JScrollPane#setViewport()方法在滚动窗格的视口中添加该组件。
notificationsSP = new JScrollPane(notificationsTA);
JFrame默认使用BorderLayout,您只能在每个部分(北,南,东,西和中)添加单个组件。
在添加所有组件后,最后调用serverFrame.setVisible(true);
。
根本不要使用setBounds()
。只需将其留给布局管理器即可设置组件的大小和位置。
使用SwingUtilities.invokeLater()
确保EDT已正确初始化。
了解更多