java软件开发 jpanel_java – 出现在JPanel上的Visual Artifacts

我正在尝试使用BorderLayout创建一个包含2个JPanel的程序.中间面板用于随机绘制矩形,而南面板用于按钮.

每当我将鼠标光标悬停在北或南按钮上时,我会得到JFrame左上角按钮的奇怪图像.我做了一些研究,发现这可能是拥有透明背景的原因.我尝试使用super.paintComponent(g)作为面板,但之前绘制的其余矩形消失了.我需要将矩形留在JPanel中,而不是左上角的奇怪图像.

我不知道我做错了什么,希望有人可以帮助或提供一些如何解决这个问题的线索.

public class TwoBRandomRec extends JFrame{

private static final long serialVersionUID = 1L;

public static void main(String[] args) {

TwoBRandomRec rec = new TwoBRandomRec();

rec.setSize(500,500);

rec.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

rec.setVisible(true);

}

public TwoBRandomRec() {

//Create the buttons

JButton north = new JButton("North");

JButton south = new JButton("South");

DrawPanel drawPanel = new DrawPanel(500,500);

JPanel southP = new JPanel();

southP.add(south);

southP.add(north);

this.add(drawPanel, BorderLayout.CENTER);

this.add(southP, BorderLayout.SOUTH);

this.setTitle("TwoButtonRandomRec");

this.pack();

}

public class DrawPanel extends JPanel {

private static final long serialVersionUID = 1L;

private Random rand = new Random();

private int x,y,xSize,ySize;

private int height,width;

public DrawPanel(int w,int h) {

width = w;

height = h;

}

public void RandomX(){

x=rand.nextInt(width-1);

xSize=rand.nextInt(width-x);

}

public void RandomY(){

y=rand.nextInt(height-1);

ySize=rand.nextInt(height-y);

}

public Color RandomColour(){

rand.nextInt(height);

return new Color(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255));

}

@Override

protected void paintComponent(Graphics g) {

RandomX();

RandomY();

g.setColor(RandomColour());

g.fillRect(x, y, xSize, ySize);

try {

Thread.sleep(50);

} catch (InterruptedException e) {

}

repaint();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值