开发者

Swing Painting issue?

开发者 https://www.devze.com 2023-04-07 11:05 出处:网络
Ihave 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 (

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();
}


  1. The default layout of a content pane is BorderLayout
  2. If a component is added to a BorderLayout with no constraint, it is placed in the CENTER.
  3. The CENTER position 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);


  1. Strange code snippet, not compilable (for example setDefaultCloseOperation(EXIT_O…)
  2. getContentPane() is useless in Java 5 and higher, remove that
  3. You have set Focus for TPanel
  4. Look for KeyBindings instead of KeyListener, then your keys will be works correctly
  5. Add KeyBinding to TPanel
  6. I hope that you have Icons for Tetris,
    • Put JLabels to the TPanel
    • JLabel.setIcon(myTetrisIcon)
  7. Your code could be outside of EDT, more in "Concurency in Swing", wrap output to the GUI (code for Icon Repainting) into invokeLater()
  8. Use only javax.swing.Timer for animations
  9. Use revalidate() and repaint()
  10. But if is there custom painting in Swing then problem(s) should came from anywhere
0

精彩评论

暂无评论...
验证码 换一张
取 消