gpt4 book ai didi

java - 将 JPanel 背景设置为透明,setOpaque() 不允许我绘画

转载 作者:行者123 更新时间:2023-12-01 19:06:40 24 4
gpt4 key购买 nike

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),看起来绘制方法不会绘制。

编辑:根据要求,我发布了一个简单的代码,TetraBoard 被添加到 GamePanel(使用 GridBagLayout),并且 GamePanel 被添加到框架,这 3 个类是单独的文件。我希望TetraBoard有一个透明的背景,这样我就可以看到GamePanel的背景,但是我在tetraboard上画的东西必须是可见的。如果我 setOpaque(false),TetraBoard 是透明的,但它会将我在其上绘制的所有内容设置为透明。

最佳答案

编辑:假设我了解您要执行的操作,请替换 TetrisBoard 构造函数中的以下行:

setOpaque(false);

与:

setBackground(new Color(0,0,0,0));

关于java - 将 JPanel 背景设置为透明,setOpaque() 不允许我绘画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9803844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com