Swing Painting issue?
I have a JPanel extension called TPanel, which paints the word Tetris on the right hand side of the JFrame. The curr() method returns the current piece that is moving, and is bounded to the left side (x < 400) of the JFrame. Now for some reason when I add them both to 开发者_高级运维the JFrame I can only see the second one I added, so basically it overrides the other one. I have tried the validate method and it doesn't work.
How do I show them both simultaneously?
Here's the code:
public Tetris()
{
// frame stuff
super("Tetris");
this.setSize(616,636);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_O…
// components
occ = new boolean [30][20];
rnd = new Random();
info = new TPanel();
for(int i=0;i<occ.length;i++)
for(int j=0; j< occ[i].length;j++)
occ [i][j] = false;
pieces.add(initPiece());
this.getContentPane().add(info);
this.getContentPane().add(curr());
this.getContentPane().validate();
repaint();
this.addKeyListener(this);
run();
}
- The default layout of a content pane is
BorderLayout - If a component is added to a
BorderLayoutwith no constraint, it is placed in theCENTER. - The
CENTERposition can only contain one component or container.
So as an immediate guess on how to fix the code snippet, try changing:
this.getContentPane().add(curr());
To:
this.getContentPane().add(curr(), BorderLayout.LINE_END);
Or better still:
add(curr(), BorderLayout.LINE_END);
- Strange code snippet, not compilable (for example
setDefaultCloseOperation(EXIT_O…) getContentPane()is useless in Java 5 and higher, remove that- You have set
Focusfor TPanel - Look for
KeyBindingsinstead ofKeyListener, then your keys will be works correctly - Add
KeyBindingto TPanel - I hope that you have
Iconsfor Tetris,- Put
JLabelsto the TPanel JLabel.setIcon(myTetrisIcon)
- Put
- Your code could be outside of EDT, more in "Concurency in Swing", wrap output to the GUI (code for
IconRepainting) intoinvokeLater() - Use only
javax.swing.Timerfor animations - Use
revalidate()andrepaint() - But if is there custom painting in Swing then problem(s) should came from anywhere
加载中,请稍侯......
精彩评论