Drawing rectangles on a JPanel

后端 未结 3 1250
生来不讨喜
生来不讨喜 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: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);
        }
    }
    

提交回复
热议问题