Fabian S. Fabian S. - 5 months ago 30
Java Question

How to add an JPanel from an other class to an existing Frame

I have my MainWindow class where menue buttons and everything else are. In the middle of it is an Panel called content. I want to load JPanels from other classes into this field. But when i start the code below nothing shows up.

MainWindow Class:

public class MainWindow {

private JFrame frame;

private JScrollPane Content;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public MainWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

JPanel TopPanel = new JPanel();
scrollPane.setColumnHeaderView(TopPanel);

JLabel lblNewLabel = new JLabel("Made by " + Globals.Author);
TopPanel.add(lblNewLabel);

JButton btnHome = new JButton("Home");
TopPanel.add(btnHome);
btnHome.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Content.add(new Home());

}
});

Content = new JScrollPane();
scrollPane.setViewportView(Content);
}

}


JPanel Class:

public class Home extends JPanelContentTemplate {
/**
* Create the panel.
*/
protected void InitializeComponents(){
setLayout(new BorderLayout(0, 0));

JPanel OptionsMenuePanel = new JPanel();
add(OptionsMenuePanel, BorderLayout.WEST);

JPanel ConentPanel = new JPanel();
add(ConentPanel, BorderLayout.CENTER);
ConentPanel.setLayout(new GridLayout(1, 2, 0, 0));

JLabel lblConnectedWith = new JLabel("Connected With:");
ConentPanel.add(lblConnectedWith);

JTextPane textServerIP = new JTextPane();
ConentPanel.add(textServerIP);
}

@Override
protected void Refresh() {
// TODO Auto-generated method stub

}
}


The InitializeComponents method comes from an Self Created Superclass:

public abstract class JPanelContentTemplate extends JPanel {

/**
* Create the panel.
*/
public JPanelContentTemplate() {
InitializeComponents();
}

protected abstract void InitializeComponents();
protected abstract void Refresh();
}


I also tried an repaint etc.

Thanks for Help

Answer

Nothing shows up because you add nothing but empty JScrollPanes to your GUI:

Content = new JScrollPane();
scrollPane.setViewportView(Content);
Comments