Tuesday, October 28, 2014

Java: Copy a directory recursively to a new location

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class DirectoryCopy {
      public static void main(String[] args) {
            try {
                  DirectoryCopy runner = new DirectoryCopy();
                  runner.copyFile("R:\\FileDepot", "C:\\MyFiles\\ProjectDesign");
            }catch(IOException e) {
                  e.printStackTrace();
            }
      }

      public void copyFile(String sourceDir, String desDir) throws IOException {
        File file = new File(sourceDir);
        File file2 = new File(desDir);
        if (file.isDirectory()) {
            if (!file2.exists()) {
                file2.mkdir();
            }
            String[] allFiles = file.list();
            for (String f : allFiles) {
                copyFile(sourceDir+"\\"+f, desDir+"\\"+f);
            }
        } else {
            if (!file2.exists()) {
                file2.createNewFile();
            }
            Files.copy(file.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

    }
}

--------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Windows: How to get all the local drives and remote sites mounted/mapped to your computer?

Open the Command Prompt and type 'net use' without the quotes.

-------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, October 23, 2014

Launch default web browser for displaying page section/particular position/sub topic like "page.html#namelink" in Java - resolved




import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetDefaultBrowser {

    public static void main(String[] args) {
        System.out.println(new GetDefaultBrowser().getDefaultBrowser());
    }

    public String getDefaultBrowser() {
        String defaultBrowser = "";
        try {
            //1.  Find the default browser in registry
            String browser = "";
            Process process0 = Runtime.getRuntime().exec("REG QUERY HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice");
            Scanner kb = new Scanner(process0.getInputStream());
            while(kb.hasNextLine()){
                String line = kb.nextLine();
                if (line.toUpperCase().indexOf("PROGID")>=0){
                    String[] elements = line.split(" ");
                    browser = elements[elements.length-1];
                    System.out.println(browser);
                }
            }

            //2. Get the default browser path from registry
            Process process = Runtime.getRuntime().exec("REG QUERY HKEY_CLASSES_ROOT\\"+browser+"\\shell\\open\\command");
            kb = new Scanner(process.getInputStream());
            while (kb.hasNextLine()) {
                String registry = (kb.nextLine()).replaceAll("\\\\", "/").trim();
                if (registry.indexOf("Default") < 0){
                    continue;
                }
             
                int fidx = registry.indexOf("\"");
                int lidx = registry.indexOf("exe");
             
                if (fidx > 0 && lidx > 0) {
                    defaultBrowser = registry.substring(fidx+1, lidx+3);
                 
                    Runtime.getRuntime().exec(defaultBrowser +
                            " file:///C:/MyFiles/GreatJouney.htm#T01_FLORIDA");
                    break;
                }
            }
         
            kb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defaultBrowser;
    }
}

--------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, October 22, 2014

JSch: Transfer file between remote and local computers/machines/systems in Java

There are many ways to do this. One way is use JSch to open a SftpChannel between your local machine and remote machine. You can download JSch from its offical site: http://www.jcraft.com/jsch/

Following is an example of the code.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class RemoteSftp {
    public static void main(String[] args){
        try{
            JSch jsch=new JSch();

            Session session = jsch.getSession("<username>","<host name or IP address>");
            session.setPassword("<password>");
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp)channel;
       
            sftpChannel.get("<source file path/file name>", "<destination file path>");
            sftpChannel.put("<source file path/file name>", "<destination file path>");

            sftpChannel.disconnect();
            session.disconnect();
        }catch(JSchException e){
            e.printStackTrace();
        }catch(SftpException se){
            se.printStackTrace();
        }
    }
}

------------------------------------------------------------------------------------------------------------------
    
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, October 21, 2014

JSch: com.jcraft.jsch.jschexception unknownhostkey: rsa key fingerprint is - resolved

This exception is thrown because for security purpose, it needs to check if the host key you set in the program matches the host key in the ~/.ssh/known_hosts file.

The following code throws such an exception at the marked line.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class FileCopy {
    public static void main(String[] args){
        try{
            JSch jsch=new JSch();
            Session session = jsch.getSession("<username>","<host name or IP address>");
            session.setPassword("<password>");

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp)channel;
         
            sftpChannel.get("<source file path/file name>", "<destination file path>");
            sftpChannel.disconnect();
            session.disconnect();
        }catch(JSchException e){
            e.printStackTrace();
        }catch(SftpException se){
            se.printStackTrace();
        }
    }
}

To fix it, you may do one of the followings.


1. Add this line of  code before you call session.connect()

          session.setConfig("StrictHostKeyChecking", "no");

2. Copy the ~/.ssh/known_hosts file from the host to your machine, and add the following line of code before you call session.connect().

         jsch.setKnownHosts("<known_hosts>");
          
-------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, October 20, 2014

NetBeans: Use an old/previous version/revision of code/file/project, Revert vs Checkout

If for some reason, one of your code users could not accommodate the recent modifications of the code at the moment and would like to go back to an old version of the code, you could either revert your current code to the old version or checkout the old version, and then do a build and send the jar to your code user.

A. Revert

  1. Open the window explorer, find the file or project that you are interested in, make a copy of it and save it some where.
  2. In NetBeans, right-click on the file/project, select "Subversion", then "Revert Modifications"
  3. In the pop-up window, select "Revert Modifications from Single Commit", then click the "Search" button.
  4. In the new pop-up window, click the "List" button, click on the revision that you would like to revert to, then click the "OK" button at the bottom.
  5. Click the "Revert" button.
Revert may generate conflicts in file.

After you have sent the jar to the particular user, you can follow the procedure to revert your code back to the current revision. Or simply update the code to the HEAD.

B. Checkout

  1. In NetBeans, close the project.
  2. In Window Explorer, rename the project to something else.
  3. In NetBeans, click "Team" on the top menu, select "Checkout"
  4. Enter the correct information related to your repository n the pop-up window, and click the "Next" button.
  5. Click the "Browse" button at the line of "Repository Folder(s) to choose the project that you would like to checkout
  6. Click the "Search" button at line Repository Revision.
  7. In the new pop-up window, click the "List" button, click on the revision that you would like to revert to, then click the "OK" button at the bottom.
  8. Click the "Finish" button.

After you have finished with the old code, you can update the code to your current working version and close the project in NetBeans. In window explorer, rename the old project and rename the current revision of the project back to the project name and open the project in NetBeans.

-------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, October 17, 2014

DynamicReport: Setting font name, size and style for report, column, text component and subreport


JasperReportBuilder report = DynamicReports.report();

1. The default font for the whole report.

          report.setDefaultFont(stl.font("<font name>", isBold, isItalic, fontSize ));

          //Or
          // report.setDefaultFont(stl.fontArial().setFontSize(9));
          // report.setDefaultFont(stl.font().boldItalic());
          // report.setDefaultFont(stl.font().setUnderline(true));

2. Font for a column

           report.columns(col.column("Name", type.stringType())
                     .setStyle(stl.style().setFont(stl.font("<font name>", isBold, isItalic, fontSize ))));

           //Or
           // TextColumnBuilder clmn = col.column("Name", type.stringType());
           // clmn.setStyle(stl.style().setFontSize(9).bold().italic());
           //report.addColumn(clmn);

4. Font for a text component

           cmp.text("<your text>").setStyle(stl.style().setFont(stl.font("<font name>", isBold, isItalic, fontSize )));

5. Font for a sub-report

            SubreportBuilder subreport = <your sub-report>;
            subreport.setStyle(stl.style().setFont(stl.font("<font name>", isBold, isItalic, fontSize )));

---------------------------------------------------------------------------------------------------------      

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, October 8, 2014

DynamicReports: How to make subreport display at a fixed page position / bottom of last page - resolved

Lets say that you have a subreport which displays a message. The length of the message can be from 0 to 20 lines. Following this message subreport, you have another subreport which displays some data and you would like it to be always displayed at the bottom one third of the page regardless the length of the message.

One way to make the second data subreport to be always displayed at a certain height of the page is to set the height of the first message subreport above it. The way to do it is to put the subreport in a vertical list or a horizontal list and set the height/width/dimension of that vertical list or horizontal list.

However, if the message has so many lines that it overflows the space you specified, the message subreport will expand and push your data subreport down. If this happens and you would like the data subreport to be displayed at the bottom one third of the next page, you need to count the lines of your message and need to know how many lines of message the space you specified can hold and the whole page can hold. If the lines of message is larger than the lines of message your space can hold, you need to add empty lines to the message until it starts to display on the next page. You need to let it display at least one line on the next page, only then the height you specified for the message subreport will apply to the message on the next page and let your data subreport be displayed at the right position.


import java.util.ArrayList;
import java.util.List;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import static net.sf.dynamicreports.report.builder.DynamicReports.cmp;
import static net.sf.dynamicreports.report.builder.DynamicReports.col;
import static net.sf.dynamicreports.report.builder.DynamicReports.exp;
import static net.sf.dynamicreports.report.builder.DynamicReports.stl;
import net.sf.dynamicreports.report.builder.component.SubreportBuilder;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class ReportDimensionDemo {
    private int messageRows = 0;

    public static void main(String[] args){
        new ReportDimensionDemo();
    }
 
    public ReportDimensionDemo() {
        JasperReportBuilder report = DynamicReports.report();
        report.setDataSource(createDataSource());
     
        SubreportBuilder messageSubreport = cmp.subreport(buildMessageSubreport())
                .setDataSource(exp.subDatasourceBeanCollection("messageData"));
        SubreportBuilder dataSubreport = cmp.subreport(buildDataSubreport())
                .setDataSource(exp.subDatasourceBeanCollection("dataData"));
     
        report.detail(cmp.verticalList(messageSubreport).setFixedHeight(300),
               // .setFixedWidth(200)
                //.setFixedDimension(200, 300)
                dataSubreport );
       //to display at the bottom of last page
       //report.summary(dataSubreport);      
        try {
            report.show(false);
        }catch(DRException de){
            de.printStackTrace(System.out);
        }
    }
 
    private JasperReportBuilder buildMessageSubreport() {
        JasperReportBuilder report = DynamicReports.report();
        report.columns(col.column("message", DataTypes.stringType()));
     
        return report;
    }
 
    private JasperReportBuilder buildDataSubreport() {
        JasperReportBuilder report = DynamicReports.report();
        report.columns(col.column("Name", "name", DataTypes.stringType())
                    .setStyle(stl.style(stl.pen1Point())),
                col.column("Price", "price", DataTypes.doubleType())
                        .setStyle(stl.style(stl.pen1Point()))
                        .setPattern("$##0.00"));
     
        return report;
    }
 
    private JRDataSource createDataSource() {
        List<ReportData> dataSource = new ArrayList<ReportData>();
        ReportData reportData = new ReportData();
        List<MessageData> messageList = new ArrayList<MessageData>();
        MessageData messageData = new MessageData();
        List<DataData> dataList = new ArrayList<DataData>();
        DataData dataData = new DataData();
     
        for (i=0; i<50; i++) {
             messageData.setMessage("The most useful report in the universe - "+i);
             messageList.add(messageData);
             //count the lines of message
             messageRows++;
             messageData = new MessageData();
        }

        //If the message overflow the height you specified, push the message band
        //to the next page so that the data subreport is displayed at the right
         //position on the next page.
        int remainder = messageRows%<message lines per whole page>
        if (remainder > <message lines in specified space>) {
              while (remainder < (<message lines per whole page> + 2)) {
                      messageData.setMessage("");
                      messageList.add(messageData);
                      messageData = new MessageData();
              }
       }
     
        reportData.setMessageData(messageList);
     
        dataData.setName("Apple");
        dataData.setPrice(1.68);
        dataList.add(dataData);
        dataData = new DataData();
        dataData.setName("Papaya");
        dataData.setPrice(3.14);
        dataList.add(dataData);
        reportData.setDataData(dataList);
     
        dataSource.add(reportData);
        return new JRBeanCollectionDataSource(dataSource);
    }
 
    public class ReportData {
        private List<MessageData> messageData;
        private List<DataData> dataData;
     
        public List<MessageData> getMessageData() {return messageData;}
        public void setMessageData(List<MessageData> m) {messageData=m;}
        public List<DataData> getDataData() {return dataData;}
        public void setDataData(List<DataData> d) {dataData=d;}
    }
 
    public class MessageData{
        private String message;
     
        public String getMessage() {return message;}
        public void setMessage(String m) {message=m;}
    }
 
    public class DataData {
        private String name;
        private Double price;
     
        public String getName() {return name;}
        public void setName(String n) {name=n;}
        public Double getPrice() {return price;}
        public void setPrice(Double p) {price=p;}
    }
}
   
----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, October 3, 2014

setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

For JFrame:
          Always use setSize for setPreferredSize does nothing.

For JPanel, JButton and JLabel:
          No need to set their sizes for their sizes are always expanding to the space available. You need to use some invisible components or fillers to occupy the space that you don't want these components to be.

For JTextField:
         The setColumns method designates the size of the JTextField.
         The setPreferredSize makes the JTextField disappear, while the setSize does nothing.

For JTextArea:
          The setRows and setColumns methods designate the size of the JTextArea.

         The setPreferredSize fixes the displaying area. If the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line, however the width of the JTextArea will not expand and it only displays the number of characters its width can hold. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached. However, when the height of the displaying area is reached, the height of the displaying area will not expand even though the input characters are keeping adding to the end of the text.

        When setSize is used instead of setPreferredSize, the behavior of the JTextArea is the same as it is not used, if the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line and the width of the JTextArea expands accordingly. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached and when the height of the displaying area is reached, the height of the displaying area will expand accordingly.

          If you really want to use the setPreferredSize or the setSize to set the size of the JTextArea instead of using setRows and setColumns, do not call the setRows and setColumns methods and call the setLineWrap(true) before you call the setPreferredSize or the setSize method.

           The setPreferredSize mthod will set the size of the JTextArea to the size specified in the method. The size is fixed and will not expand according to the size of the text you put in it.

           The setSize method will set the width to the specified amount, but will not set the height. The height dynamically expands according to the the text put in the text area.

When the JTextArea is put in a JScrollPane:
          No matter whether the setRows and setColumns or the setPreferredSize or the setSize is used, the size of the JTextArea will occupy the whole available space in the JScrollPane. When setSize is used, it will automatically scroll, where else when setPreferredSize is used the JScrollPane will not scroll.

           However, when a JTextArea is put in a JScrollPane, it is better to not use either setPreferredSize or setSize on the JTextArea and the JScrollPane will scroll when it is needed.

---------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, October 2, 2014

\AppData\Local\NetBeans\Cache\7.4\executor-snippets\junit.xml:134: The following error occurred while executing this line:

To fix the following error

C:\Users\user\AppData\Local\NetBeans\Cache\7.4\executor-snippets\junit.xml:134: The following error occurred while executing this line:

C:\Users\user\AppData\Local\NetBeans\Cache\7.4\executor-snippets\junit.xml:78: The <classpath> for <junit> must include junit.jar if not in Ant's own classpath
BUILD FAILED (total time: 0 seconds)

1. If you are doing JUnit test, add the JUnit jars to your class path.

2. Check to see if the class you are executing has a main method. If it doesn't have one, add a public static void main method to it to make it executable.

------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

How to make JTextArea display a maximum number of characters?

Following are the steps of setting the maximum numbers of characters that a JTextArea can take.


  1. Create a Document class that extends the PlainDocument class. 
    • In the class create a maxSize field. 
    • Override the insertString method so that only the maxSize or less number of characters can be inserted into the document. 
    • Create a setMaxSize method for setting the value of the maxSize.
  2. Create a Text Area class that extends the JTextArea, which uses the Document created in step 1 as its default document. Add a setMaxSize method to the class that calls the Document's setMaxSize mthod to set the max size for the Document.
Here is the sample code.


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class TextAreaSize {
    
    private class MyDocument extends PlainDocument {
        private int maxSize = 1000000000;
        
        @Override
        public void insertString(int offset, String s, AttributeSet attributeSet)
                throws BadLocationException {
            int length = s.length();
            if (length == 0) {
                return;
            }

            if (offset + length > maxSize) {
                s = s.substring(0, maxSize - offset);
            }
            super.insertString(offset, s, attributeSet);
        }
        
        public void setMaxSize(int size) {
            maxSize = size;
        }
    }
    
    private class MyTextArea extends JTextArea {
        private MyDocument document;
        
        public MyTextArea (MyDocument d){
            super(d);
            document = d;
        }
        
        public void setMaxSize(int s){
            document.setMaxSize(s);
        }
    }
    
    public TextAreaSize() {
        MyTextArea textArea = new MyTextArea(new MyDocument());
        textArea.setMaxSize(30);
        textArea.setRows(2);
        textArea.setColumns(20);
        
        JPanel panel = new JPanel();
        panel.add(textArea);
        
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setSize(500, 300);
        frame.setVisible(true); 
    }
    
    public static void main(String[] args){
        new TextAreaSize();
    }
}

----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


How to make JTextArea display a fixed number of characters each line

There are two ways to achieve this result. One way is to use the setRows and setColumns method to set the size of the JTextArea. The other way is making your text area the subclass of the JTextArea and override the paint() method to get the width and height of the font used. Then, set the size of your text area.

Since for many types of font, the characters do not always have the same widths, some characters are wider than the others, it is better that you use the monospaced font for achieving a constant result.

Following is an example.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class CharInLine {
    private int charWidth = 0;
    private int charHeight = 0;
    private int charPerLine = 30;
 
    public CharInLine() {
        MyTextArea textArea = new MyTextArea();
        textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
     
        //Method 1
        //setting the rows and columns is important for an
        //empty JTextArea to show its size.
        textArea.setRows(5);
        textArea.setColumns(30);
        textArea.setBorder(BorderFactory.createTitledBorder("Text Area"));
     
        //Method 2
        //designate 30 characters per line and 5 lines in the text area
        textArea.setLineWrap(true);
        textArea.setSize(new Dimension(charWidth*charPerLine, charHeight*5));
        //textArea.setPreferredSize(new Dimension(charWidth*charPerLine, charHeight*5));    

        JPanel panel = new JPanel();
        panel.add(textArea);
     
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel,BorderLayout.CENTER);
        frame.setSize(500, 300);
     
        frame.setVisible(true);
    }
 
    private class MyTextArea extends JTextArea {
        @Override
        public void paint(Graphics g){
            super.paint(g);
            FontMetrics fm = g.getFontMetrics();
            charWidth = fm.charWidth('M');
            charHeight = fm.getHeight();
        }
    }
 
    public int getCharWidth() {
        return charWidth;
    }
 
    public static void main(String[] args){
        new CharInLine();
    }
}

Reference:

1. setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.