tags:

views:

2733

answers:

5

I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.

When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically.

Ive been trying to use JPanels like usercontrols in C#. I created a JPanel form called BlurbEditor. This has a few simple controls on it. I am trying to add it to another panel at runtime on a button event.

Here is the code that I thought would work:

mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();

This unfortunately is not working. What am I doing wrong?

A: 

Try mainPanel.invalidate() and then if necessary, mainPanel.validate(). It also might be worth checking that you're doing this all in the event dispatch thread, otherwise your results will be spotty and (generally) non-deterministic.

Daniel Spiewak
Adding the invalidate method call did not help. I am calling this from the mouseclick event generated by netbeans.
BFreeman
+1  A: 

I figured it out. The comments under the accepted answer here explain it: http://stackoverflow.com/questions/121715/dynamically-added-jtable-not-displaying

Basically I just added the following before the mainPanel.add()

mainPanel.setLayout(new java.awt.BorderLayout());
BFreeman
A: 

As with all swing code, don't forget to call any gui update within event dispatch thread. See this for why you must do updates like this

// Do long running calculations and other stuff outside the event dispatch thread
while (! finished )
  calculate();
SwingUtilities.invokeLater(new Runnable(){
  public void run() {
    // update gui here
  }
}
dhiller
A: 

Swing/AWT components generally have to have a layout before you add things to them - otherwise the UI won't know where to place the subcomponents. BFreeman has suggested BorderLayout which is one of the easiest ones to use and allows you to 'glue' things to the top, bottom, left, right or center of the parent. There are others such as FlowLayout which is like a textarea - it adds components left-to-right at the top of the parent and wraps onto a new row when it gets to the end; and GridBagLayout which has always been notorious for being impossible to figure out, but does give you nearly all the control you would need. A bit like those HTML tables we used to see with bizarre combinations of rowspan, colspan, width and height attributes - which never seemed to look quite how you wanted them.

Leigh Caldwell
A: 

mainPanel.add(new BlurbEditor());

mainPanel.validate();

mainPanel.repaint();

Flavio Lozano Morales