0

我在 Java 桌面应用程序中工作,我不熟悉 JAVA,我在面板之间切换时遇到问题,所以当我从 JMenu 中选择一个 JMenuItem 时,实际面板应该改变。我有一个主 Jframe,只有一个 Panel,所以我如何为其他 JmenuItem 添加其他面板,在同一个 Jframe 中,我尝试以下代码:

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
    TextArea ta; 

    Dimension d = mainPanel.getSize();  
    mainPanel.removeAll();        
    JPanel painel3 = new JPanel();  
    painel3.setSize(d);  
    ta = new TextArea();  
    ta.setSize(d);

    painel3.add(ta);

    JScrollPane scrollPane = new JScrollPane();  
    scrollPane.add(painel3);  
    mainPanel = painel3; 
}
4

1 回答 1

0

Something like:

private void menuItem1ActionPerformed(ActionEvent evt) {
    scrollPane.getViewport().removeAll();
    scrollPane.getViewport().add(panel1);
}                                          

private void menuItem2ActionPerformed(ActionEvent evt) {
    scrollPane.getViewport().removeAll();
    scrollPane.getViewport().add(panel2);
}                                          

The JScrollPane has a "view port" on a generally unbounded plane where you place your JPanel. So one does not add immediately to the scroll pane. One could do new JScrollPane(panel3) however for initialisation.

于 2013-08-02T16:20:18.737 回答