java如何在JTextArea旁边使用JScrollPane?
我已经写了这段代码。在这里,我想让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);
}
# 1 楼答案
JTextArea
已经添加到了JScrollPane
中,因此也不需要在JFrame
中再次添加它。删除以下行:您可以使用其Constructor以及内部调用JScrollPane#setViewport()方法的Constructor在滚动窗格的视口中添加组件
一些要点:
JFrame默认情况下使用BorderLayout,并且您只能在每个部分(北部、南部、东部、西部和中部)中添加单个组件
阅读更多How to Use BorderLayout
添加所有组件后,最后调用
serverFrame.setVisible(true);
根本不要使用
setBounds()
。只需让布局管理器设置组件的大小和位置即可使用
SwingUtilities.invokeLater()
确保EDT已正确初始化阅读更多
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater