Internal padding for JTextArea with background Image

前端 未结 4 1861
既然无缘
既然无缘 2020-11-27 20:37

My ultimate goal is to have a JTextArea with a background image. I found code online that showed me how to do this, but now I\'m having an issue with the text b

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 21:01

    You should use an Border for that, more specifictly you should use BorderFactory.createEmptyBorder(int top, int left, int bottom, int right):

    textArea.setBorder(BorderFactory.createEmptyBorder(10,10,15,10));
    

    You should also override paintComponent instead of paint. Also, use setRows() and setColumns() to set the size of the textArea, then you can use pack() instead of setSize(400,400) which is not recommended. See this example:

    enter image description here

    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    
    
    public class Test extends JFrame {
    
        class MyTextArea extends JTextArea {
    
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setColor(Color.PINK);
                g2.setStroke(new BasicStroke(4));
                g2.drawRoundRect(3, 3, getWidth()-7, getHeight()-7, 5, 5);
            }
    
        }
    
        public Test() {
            JPanel panel = new JPanel(new BorderLayout());
            JTextArea textArea = new MyTextArea();
            textArea.setRows(3);
            textArea.setColumns(25);
            textArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            panel.add(textArea, BorderLayout.NORTH);
    
            add(panel);
            pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new Test();
        }
    
    }
    

提交回复
热议问题