代码之家  ›  专栏  ›  技术社区  ›  MZX

为什么paintComponent绘图JMenu除了红圈之外?[副本]

  •  0
  • MZX  · 技术社区  · 3 年前

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

    我在的左上角看到了一个奇怪的按钮图像 JFrame 每当我将鼠标光标悬停在“北”或“南”按钮上时。我做了一些研究,发现这可能是拥有透明背景的原因。我试着使用 super.paintComponent(g) 对于面板,但是先前绘制的其余矩形消失。我需要矩形保持在 面板 但不是左上角那张奇怪的照片。

    我不知道我做错了什么,希望有人能帮助或提供一些线索来解决这个问题。

        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();
            }
        }
    }
    
    0 回复  |  直到 8 年前