import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tetris extends JFrame {
public Tetris() {
add(new GamePanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setSize(800, 600);
setVisible(true);
setLocationRelativeTo(null);
setTitle("Tetris");
}
public class GamePanel extends JPanel {
public GamePanel(){
TetrisBoard tetraBoard= new TetrisBoard();
GridBagLayout layout= new GridBagLayout();
this.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 1;
c.ipadx = 190;
c.ipady = 390;
c.insets.left= 360;
layout.setConstraints(tetraBoard, c);
this.add(tetraBoard);
setBackground(Color.WHITE);
}
@Override
public void paint(Graphics g){
super.paint(g);
g.setFont(new Font("Birth Std", Font.PLAIN, 12));
g.setColor(Color.LIGHT_GRAY);
g.drawString("200", 36, 63);
g.drawString("200", 36, 88);
g.drawString("200", 36, 114);
}
}//GamePanel class
public class TetrisBoard extends JPanel implements Runnable{
private Thread animator= new Thread(this);
private final int DELAY= 50;
public TetrisBoard(){
setFocusable(true);
//setBackground(Color.WHITE);
setDoubleBuffered(true);
//this.setBackground(Color.BLACK);
setOpaque(false);
}
@Override
public void addNotify() {
super.addNotify();
animator = new Thread(this);
animator.start();
}//addNotify
@Override
public void paint (Graphics g){
super.paint(g);
g.drawRect (20, 30, 130, 50);
}//paint
@Override
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true) {
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
}//TetrisBoard class
public static void main(String[] args) {
Tetris t = new Tetris();
}
}
使用此代码,结果是它根本不绘制任何内容。我只是希望背景是透明的而不是背景上绘制的图像,但是如果我设置了setOpaque(false),看起来像paint方法不会绘制。
编辑:按照要求我发布了一个简单的代码,将TetraBoard添加到GamePanel(使用那个GridBagLayout),并将GamePanel添加到框架中,这3个类是单独的文件。我希望TetraBoard有一个透明的背景,这样我就可以看到GamePanel的背景,但是我在tetraboard上绘制的内容必须是可见的。如果我setOpaque(假),TetraBoard是透明的,但它设置透明我在其上绘制的所有内容。
答案 0 :(得分:4)
编辑:假设我了解您要尝试的操作,请替换TetrisBoard构造函数中的以下行:
setOpaque(false);
使用:
setBackground(new Color(0,0,0,0));
答案 1 :(得分:0)
例如:
JPanel p = new JPanel() {
@Override
public void paintComponent(Graphics g) { // as suggested Andrew
g.setColor(Color.RED);
g.drawArc(0, 0, 100, 100, 0, 360); // arc will be painted on transparent bg
}
};
p.setBackground(new Color(0, 0, 0, 0)); // as suggested Perry
...
所以,你必须做两件事:
1)覆盖JPanel的paintComponent(Graphics g)
2)并将bg颜色设置为透明:new Color(0, 0, 0, 0)