I have a repaint() problem. I nailed it down the minimum code.
A JFrame with a BorderLayout.
In the center a JPanel panel whith a GridLayout filled with an array of JLabel.
The size of the JFrame is determined by the number of rows/columns
In the real life the program decides that it needs more JLabel, here I simulate the situation with the JButton "GO" in BorderLayout South.
When the button is clicked
The JPanel is removed from the JFrame
I increment the number of rows and columns by 10
Create a new JPanel panel with gridLayout +10
fill it with a new array of JLabel
add it BorderLayout.CENTER
size of the JFrame is set accordingly
then
repaint();
What happens is that the JFrame size is refreshed but not the the JLabel and the JPanel don't show.
Je JButton stays where it used to be.
If I resize, with the mouse, by 1 pixel the JFrame... everyting is displayed correctly.
Do I have a repaint() missing somewhere.
Thanks
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Problem extends JFrame implements ActionListener {
// Size of the initial Grid
private int nbRows = 10, nbColumns = 10;
// label width and height
private int labelWH = 20;
// the JLabel inthe grid
JLabel[][] label;
JButton button = new JButton("GO");
// will hold the GridLayout
JPanel panel;
// constructor
Problem() {
// frame stuff
super("V1.0");
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// build Panel and its labels
buildPanelAndLabels();
add(panel, BorderLayout.CENTER);
// the JButton
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
// set size of frame according to labelWH
setSize(nbColumns*labelWH, nbRows*labelWH + 24);
setVisible(true);
}
// build the JPanel panel
void buildPanelAndLabels() {
panel = new JPanel(new GridLayout(nbRows, nbColumns, 1, 1));
panel.setBackground(Color.BLUE);
// and fill its grid with JLabel
label = new JLabel[nbRows][nbColumns];
for(int i = 0; i < nbRows; i++) {
for(int j = 0; j < nbColumns; j++) {
label[i][j] = new JLabel("");
label[i][j].setOpaque(true);
label[i][j].setBackground(Color.WHITE);
panel.add(label[i][j]);
}
}
}
public void actionPerformed(ActionEvent arg0) {
// we create a new the JPanel
nbRows += 10;
nbColumns += 10;
// remove old panel
getContentPane().remove(panel);
buildPanelAndLabels();
// put the new Panel in the Center
add(panel, BorderLayout.CENTER);
setSize(nbColumns*labelWH, nbRows * labelWH + 24);
repaint();
}
// an to test all that
public static final void main(String[] arg) {
new Problem();
}
}

New Topic/Question
Reply



MultiQuote






|