Forcing layout ?
Here is the code:
package ui.components;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
publicclass GuiTest{
publicstaticvoid main(String[] args)
{
final JFrame frame =new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 600, 600);
frame.setBackground(Color.blue);
JPanel panel =new JPanel();
panel.setLayout(new GridBagLayout());
for (int i = 0; i < 20; i++){
for (int j = 0; j < 7; j++){
panel.add(
new JButton("r: " + i +" c: " + j),
new GridBagConstraints(
j, i, 1, 1, 1.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 0, 0),
0, 0
)
);
}
}
frame.setContentPane(panel);
panel.doLayout();
SwingUtilities.invokeLater(
new Runnable(){
publicvoid run()
{
frame.setVisible(true);
}
}
);
}
}
The sequence is as follows:
1. The jframe is shown on screen
2. Background color (blue) is drawn inside frame
3. Components are drawn.
Can I get rid of step 2 ?
Sort of force swing to layout components before the frame is shown so when I issue setVisible everything is ready to be painted on screen.
I'm asking how to force swing to layout components before the frame is shown on screen.
They are. There's no need to call doLayout().
There is an ungly effect. Empty frame is shown, then it is filled with components.
I doubt you want to be setting the background of the frame. For a start it's pointless since it's obliterated by the content pane ('panel') but generally you should only use frames as holders for content panes rather than as components in their own right.
I've modified your code so it all runs on the EDT and sets the background of the content pane instead of the frame.
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GuiTest {
public static void main(String[] args)
{
SwingUtilities.invokeLater(
new Runnable() {
public void run()
{
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 600, 600);
JPanel panel = new JPanel();
panel.setBackground(Color.blue);
panel.setLayout(new GridBagLayout());
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 7; j++) {
panel.add(
new JButton("r: " + i + " c: " + j),
new GridBagConstraints(
j, i, 1, 1, 1.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 0, 0),
0, 0
)
);
}
}
frame.setContentPane(panel);
frame.setVisible(true);
}
}
);
}
}