Drawing rectangles on a JPanel

后端 未结 3 1247
生来不讨喜
生来不讨喜 2020-12-04 03:01

I have a JScrollPane and on top of it I have a JPanel named \'panel1\'. I want some rectangles to be drawn on this JPanel.

I have a class named DrawRectPanel which e

相关标签:
3条回答
  • 2020-12-04 03:20

    instead of adding

    contentPane.add(new DrawRectPanel());
    

    you should do

    contentPane.add(panel1);
    

    Because you already have new DrawRectPanel in panel1. But in your code you are adding another instance of DrawRectPanel in contentPane. And never added panel1 in none of your container.

    0 讨论(0)
  • 2020-12-04 03:27

    to fix your problem, change "paintComponent" to "paint" when the window repaints automatically, it should work.

    0 讨论(0)
  • 2020-12-04 03:41

    still no idea,

    for example

    enter image description here

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    
    public class CustomComponent extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        public CustomComponent() {
            setTitle("Custom Component Graphics2D");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        public void display() {
            add(new CustomComponents());
            pack();
            // enforces the minimum size of both frame and component        
            setMinimumSize(getSize());
            setVisible(true);
        }
    
        public static void main(String[] args) {
            CustomComponent main = new CustomComponent();
            main.display();
        }
    }
    
    class CustomComponents extends JComponent {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        public Dimension getMinimumSize() {
            return new Dimension(100, 100);
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 300);
        }
    
        @Override
        public void paintComponent(Graphics g) {
            int margin = 10;
            Dimension dim = getSize();
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
        }
    }
    
    0 讨论(0)
提交回复
热议问题