JTextArea border in java swing

Rajesh picture Rajesh · Mar 9, 2017 · Viewed 11.5k times · Source

I am new to java and creating UI widgets using java and created the following class for the same. But in order to add border to textarea I know that I have to use borderfactory class. But as I have separate class for JFrame and JTextArea I could not do it. Any help?

class

import javax.swing.*;
import java.awt.*;
import javax.swing.BorderFactory;

    public class UIFactory {

        //Border border = BorderFactory.createLineBorder(Color.BLACK);
        public JButton newButton(int posx, int posy, int buttonWidth, int buttonHeight) {
            JButton b = new JButton("Test");
            b.setBounds(posx, posy, buttonWidth, buttonHeight);
            return b;
        }

        public JFrame newFrame(int width, int height) {
            JFrame f = new JFrame();
            f.setSize(width, height);
            f.setLayout(null);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            return f;
        }

        public JTextArea newTextArea(int xpos, int ypos, int twidth, int theight) {
            JTextArea t = new JTextArea(300,300);
            JScrollPane sp = new JScrollPane(t);            
            t.setBounds(xpos, ypos, twidth, theight);
            t.setBackground(Color.orange);  
            t.setForeground(Color.black); 
         //   t.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(10, 10, 10, 10)));            
            return t;
        }

}

and my main program

import javax.swing.*;
import java.awt.*;
public class MyUI {
public static void main(String[] args) {
        UIFactory ui = new UIFactory();    
        JFrame mainf = ui.newFrame(800, 800);        
        mainf.setLocation(400, 400);

        JButton b2;
        JButton b3;


        mainf.add(b2 = ui.newButton(50, 50, 100, 50));
        mainf.add(b3 = ui.newButton(50, 100, 100, 50));   

        JTextArea area;
        mainf.add(area = ui.newTextArea(170,50,1600,300));
        mainf.setVisible(true);
        mainf.add(area = ui.newTextArea(170,400,1600,300));
        mainf.setVisible(true);
    }
}

Answer

SAQ picture SAQ · Mar 9, 2017

try below in newTextArea

Border border = BorderFactory.createLineBorder(Color.BLACK);
    t.setBorder(BorderFactory.createCompoundBorder(border,
            BorderFactory.createEmptyBorder(10, 10, 10, 10)));