AR8*_*R89 0 java swing transparency paint paintcomponent
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();
}
Run Code Online (Sandbox Code Playgroud)
}
使用这段代码的结果是它根本不绘制任何东西。我只是希望背景是透明的,而不是在背景上绘制的图像,但如果我 setOpaque(false),看起来绘制方法不会绘制。
编辑:根据要求,我发布了一个简单的代码,TetraBoard 被添加到 GamePanel(使用 GridBagLayout),并且 GamePanel 被添加到框架,这 3 个类是单独的文件。我希望TetraBoard有一个透明的背景,这样我就可以看到GamePanel的背景,但是我在tetraboard上画的东西必须是可见的。如果我 setOpaque(false),TetraBoard 是透明的,但它会将我在其上绘制的所有内容设置为透明。
编辑:假设我理解您要做什么,请替换 TetrisBoard 构造函数中的以下行:
setOpaque(false);
Run Code Online (Sandbox Code Playgroud)
和:
setBackground(new Color(0,0,0,0));
Run Code Online (Sandbox Code Playgroud)