Draw multiple shapes using loop - Android Canvas - java

I am very new to android development and have been trying to draw a square comprised of multiple smaller rectangles of different colours... Like a Mosaic essentially.
Basically at the moment I am reading values from a file which assigns the colour to the smaller Rects. I am using a pair of nested for loops to try to draw the small Rects sequentially, line by line. However when the program finishes there is only one small Rect drawn which is the last one to be drawn and its colour corresponds to the first value read from the file.
Here is some of my code to show you what I mean:
public SnapshotDraw(Context context) {
super(context);
for(int a = 0; a < 63; a++){
for(int b = 0; b < 63; b++){
fileName = PREFIX + "2" + EXTENSION;
try {
bf = new BufferedReader(new FileReader(fileName));
tokens = new StringTokenizer(bf.readLine(), " \n");
weight = Byte.parseByte(tokens.nextToken());
x_scalar = b*MAG;
y_scalar = a*MAG;
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setColor(colour.getColour(weight));
mDrawable.setBounds((X_OFFSET + x_scalar), (Y_OFFSET + y_scalar), ((MAG + X_OFFSET) + x_scalar), ((MAG + Y_OFFSET) + y_scalar));
} catch (FileNotFoundException ex) {
Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
This except is from a class which extends View and is called inside an onCreate() method in an Activity.
I would appreciate any guidance in this and thanks in advance!!
Cheers.

You are constructing the BufferedReader inside the loops, so bf.readLine() will always return the same line. Try moving bf and tokens (be aware that the use of StringTokenizer is discouraged) out of the loops.

Ok I got it sorted! Here is what I did to solve it:
public SnapshotDraw(Context context) {
super(context);
setFocusable(true);
mBitmap = Bitmap.createBitmap(475, 720, Bitmap.Config.ALPHA_8);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Paint p = new Paint();
float y = 10;
try {
fileName = PREFIX + "2" + EXTENSION;
bf = new BufferedReader(new FileReader(fileName));
for(int a = 0; a < 63; a++){
tokens = bf.readLine().split(" \n");
for(int b = 0; b < 63; b++){
weight = Byte.parseByte(tokens[b]);
x_scalar = b*MAG;
y_scalar = a*MAG;
p.setColor(new Colour().getColour(weight));
canvas.drawRect((X_OFFSET + x_scalar), (Y_OFFSET + y_scalar), ((MAG + X_OFFSET) + x_scalar), ((MAG + Y_OFFSET) + y_scalar), p);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
}
canvas.drawBitmap(mBitmap, 10, y, p);
}
Much the same as before but changed the way I draw to the Bitmap. It looks beautiful btw!!

Related

Printing a text document using Java

Alright, I have made a program that makes a text file. The text file is a different size every time the program is ran. I simply just want to add a print button that allows the user to print out the text file to a printer. I made a button with an action listener that brings up my print class. It is almost working except it only prints one page with my text displayed in horizontal columns extremely small. I think my problem has something to do with my printJob setup. Any help would be greatly appreciated.
public class PrintingClass implements Printable {
// Global variables
int[] pageBreaks;
String [] textLines;
static String fileName;
public static void print(String filename){
fileName = filename;
PrintingClass object = new PrintingClass();
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(object);
Boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
}
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
Font font = new Font("Monospaced", Font.PLAIN, 12);
FontMetrics metrics = g.getFontMetrics(font);
int lineHeight = metrics.getHeight();
if (pageBreaks == null) {
initTextLines();
int linesPerPage = (int)(pf.getImageableHeight()/lineHeight);
System.out.println("Lines per page = " + linesPerPage);
int numBreaks = (textLines.length-1)/linesPerPage;
System.out.println("number of pages = " + numBreaks);
pageBreaks = new int[numBreaks];
for (int b=0; b<numBreaks; b++) {
pageBreaks[b] = (b+1)*linesPerPage;
}
}
if (pageIndex > pageBreaks.length) {
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
* Since we are drawing text we
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Draw each line that is on this page.
* Increment 'y' position by lineHeight for each line.
*/
int y = 0;
int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex-1];
int end = (pageIndex == pageBreaks.length)
? textLines.length : pageBreaks[pageIndex];
for (int line=start; line<end; line++) {
y += lineHeight;
g.drawString(textLines[line], 0, y);
}
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
/**
* This will initialize the textLines[] variable
* and read in my file
* #param fileName
*/
public void initTextLines(){
// Get file size
int fileSize = counter();
// Initialize textLine
textLines = new String[fileSize];
// Read text to set lines
BufferedReader file;
try {
file = new BufferedReader(new FileReader(fileName));
String line = null;
int x = 0;
while((line = file.readLine()) != null){
textLines[x] = line;
x++;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* This will simply count the size of the file
* and return it
* #return
*/
public int counter(){
int count = 0;
try {
BufferedReader file = new BufferedReader(new FileReader(fileName));
while(file.readLine() != null){
count++;
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
}
Most of this code comes straight from Javas own tutorial page. Thank you.

java.io.IOException: RandomAccessBuffer already closed, when reading a PDPage

I've created a program to convert a PDF to Excel. The conversion takes a long time (100 page=10 minutes). It runs fine for about 15-20 minutes, after that an error occurs when reading the PDPage.
Is it possible the Java GC "clean" the variable before the programs end?
the code:
private class Search_Text implements Runnable {
private int x, y, width, height;
private PDPage pdPage;
private Object lock;
private ArrayList<Object[]> result;
private PDFTextStripperByArea strip;
public Search_Text(int x, int y, int width, int height, PDPage pdPage, Object lock) throws IOException {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.pdPage = pdPage;
this.lock = lock;
this.result = new ArrayList<>();
this.strip = new PDFTextStripperByArea();
}
#Override
public void run() {
if (height < 10) {
int upper = y;
int bottom = 1;
ArrayList<Object[]> st = new ArrayList<>();
String str = "";
while (upper + bottom <= y + height) {
strip.addRegion("cell", new Rectangle(x, upper, width, bottom));
//System.out.println("prova.Pdf2Excell.log_extract()BEFORE LOCK" + init);
synchronized (lock) {
try {
strip.extractRegions(pdPage);
} catch (IOException ex) {
Logger.getLogger(Pdf2Excell.class.getName()).log(Level.SEVERE, null, ex);
}
}
str = strip.getTextForRegion("cell");
if (!emptyString(str)) {
st.add(new Object[]{str, upper + bottom, upper});
upper += bottom;
bottom = 1;
while (upper + bottom < height + y && !emptyString(str)) {
strip.addRegion("cell", new Rectangle(x, upper, width, bottom));
synchronized (lock) {
try {
strip.extractRegions(pdPage);
} catch (IOException ex) {
Logger.getLogger(Pdf2Excell.class.getName()).log(Level.SEVERE, null, ex);
}
}
str = strip.getTextForRegion("cell");
upper++;
//System.out.println("prova.Pdf2Excell.pdf2EX()DENTRO");
}
} else {
bottom += 1;
//System.out.println("prova.Pdf2Excell.pdf2EX()UPPER;;"+upper+";;BOTTOM;;" + bottom);
}
if (upper == y) {
st.add(new Object[]{"", y + height, upper});
}
result = st;
}
} else {
try {
int half_rec = height / 2;
Rectangle first_rec = new Rectangle(x, y, width, half_rec);
Rectangle last_rec = new Rectangle(x, y + half_rec, width, height - half_rec);
Search_Text first_search = new Search_Text(x, y, width, half_rec, pdPage, lock);
Search_Text last_search = new Search_Text(x, y + half_rec, width, height - half_rec, pdPage, lock);
Thread first = new Thread(first_search);
Thread last = new Thread(last_search);
strip.addRegion("cell", first_rec);
synchronized (lock) {
strip.extractRegions(pdPage);
}
String temp = strip.getTextForRegion("cell");
if (!emptyString(temp)) {
first.start();
}
strip.addRegion("cell", last_rec);
synchronized (lock) {
strip.extractRegions(pdPage);
}
temp = strip.getTextForRegion("cell");
if (!emptyString(temp)) {
last.start();
}
first.join();
last.join();
result = first_search.getResult();
ArrayList<Object[]> temp_res = last_search.getResult();
for (int i = 0; i < temp_res.size(); i++) {
result.add(temp_res.get(i));
}
} catch (InterruptedException | IOException ex) {
Logger.getLogger(Pdf2Excell.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is the error message:
Exception in thread "Thread-214418" java.lang.RuntimeException: java.io.IOException: RandomAccessBuffer already closed
at org.apache.pdfbox.pdfparser.PDFStreamParser$1.tryNext(PDFStreamParser.java:198)
at org.apache.pdfbox.pdfparser.PDFStreamParser$1.hasNext(PDFStreamParser.java:205)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:255)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:235)
at org.apache.pdfbox.util.PDFStreamEngine.processStream(PDFStreamEngine.java:215)
at org.apache.pdfbox.util.PDFTextStripper.processPage(PDFTextStripper.java:458)
at org.apache.pdfbox.util.PDFTextStripperByArea.extractRegions(PDFTextStripperByArea.java:153)
at prova.Pdf2Excell$Search_Text.run(Pdf2Excell.java:954)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: RandomAccessBuffer already closed
at org.apache.pdfbox.io.RandomAccessBuffer.checkClosed(RandomAccessBuffer.java:325)
at org.apache.pdfbox.io.RandomAccessBuffer.seek(RandomAccessBuffer.java:105)
at org.apache.pdfbox.io.RandomAccessFileInputStream.read(RandomAccessFileInputStream.java:96)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:284)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at java.io.FilterInputStream.read(FilterInputStream.java:83)
at java.io.PushbackInputStream.read(PushbackInputStream.java:139)
at org.apache.pdfbox.io.PushBackInputStream.read(PushBackInputStream.java:90)
at org.apache.pdfbox.io.PushBackInputStream.peek(PushBackInputStream.java:68)
at org.apache.pdfbox.pdfparser.PDFStreamParser.hasNextSpaceOrReturn(PDFStreamParser.java:560)
at org.apache.pdfbox.pdfparser.PDFStreamParser.parseNextToken(PDFStreamParser.java:408)
at org.apache.pdfbox.pdfparser.PDFStreamParser.parseNextToken(PDFStreamParser.java:374)
at org.apache.pdfbox.pdfparser.PDFStreamParser.access$000(PDFStreamParser.java:49)
at org.apache.pdfbox.pdfparser.PDFStreamParser$1.tryNext(PDFStreamParser.java:193)
... 8 more
PDFBox has been developed for single-threaded use per document while the OP accesses the same document using multiple threads. While this may still work (because it is a read-only use case), proper synchronization is necessary.
This synchronization most likely would have slowed down everything still more. Thus, the solution was to use a different architecture altogether, namely to
take PDFTextStripper, override writeString(String text, List<TextPosition> textPositions), and collect the required information from that List<TextPosition> textPositions. TextPosition contains information on a small piece of text (usually a single letter, I think), including its position.
The result turned out to be
like 4 times faster.

An array of BufferedImage is showing null for the values set

In the class getPathGiveIcon, am passing an array of strings to getPaths() method. This getPaths() is expected to return an array of ImageIcons. In this process, am trying to create a file out of a every path name in the array of strings but at this line am getting error.
img[i] = ImageIO.read(fa);// in this line the error
Kindly guide me to over come this error...
Here is full code of the getPaths() method.
public class GetPathGiveIcon {
ImageIcon[] iic;
File f = new File(" ");
int i = 0;
public ImageIcon[] getPaths(String[] s)
{
BufferedImage[] img = null;
for(String st : s)
{
System.out.println(st);
}
for(String st : s)
try
{
{
File fa = new File(st);
img[i] = ImageIO.read(fa);
System.out.println(" inside try block the value of every string = " + st);
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(" Value of I before scaling " + i);
i = 0;
for(BufferedImage bi : img)
{
iic[i] = new ImageIcon(bi);
Image scaled = iic[i].getImage().getScaledInstance(150,150,
Image.SCALE_DEFAULT);
iic[i] = new ImageIcon(scaled);
i++;
}
System.out.println(" Value of I after scaling " + i);
return iic;
}
}
That is because
BufferedImage[] img = null;
You have to initialize img array with
BufferedImage[] img = new BufferedImage[s.length];
i always equals 0 so your code will only fill the first element of your array.
Here is the solution :
BufferedImage[] img = new BufferedImage[s.length];
for(String st : s)
{
try
{
File fa = new File(st);
img[i++] = ImageIO.read(fa);
System.out.println(" inside try block the value of every string = " + st);
}
catch(Exception e)
{
e.printStackTrace();
}
}
edit
Same issue with iic, it has to be initialized
iic = new ImageIcon[img.length];
i = 0;
for(BufferedImage bi : img)
{
iic[i] = new ImageIcon(bi);
// [...]

Fonts do not display correctly - Java

I have some words in English that have been translated into Tamil. The task requires me to display them. An example line is given below. The first and second lines are in Tamil while the last is in Bengali.
> unpopular ஜனங்கலால் வெறுக்கப்பட்ட ¤µ£»ªÀ»õu
inactive ஜடமான ö\¯»ØÓ
doctor வைத்தியர் ©¸zxÁº
apart வேறாக uµ
If you notice above, the text in some lines does not render correctly because it is written in custom fonts. The custom font can be downloaded from here. My problem:
1. All Tamil fonts (custom and pre-loaded) have been installed. None of the text displays correctly. Why?
2. Is there a problem with the way that I am loading custom fonts?
3. In the above lines, the second column is pre-loaded font while the third column is written in custom fonts. The third column does not seem like it is Unicode, which is why application of any font also fails. What is going on?
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
/* This is the imageMaker class.
* It loads a plain white image, writes text taken from another file
* and creates a new image from it.
*
* Steps:
* 1. A plain white image is loaded.
* 2. Text is taken from a file.
* 3. Text is written to the image.
* 4. New image is created and saved.
*/
public class imgMaker_so {
/**
* #param args
*/
private static String tgtDir = "YOUR_tgt directory to store images goes here";
private static String csvFile = "csv file goes here";
private static int fontSize = 22; //default to a 22 pt font.
private static Font f;
private static String fontName = "WTAM001";
public static void main(String[] args) {
// TODO Auto-generated method stub
//Step 0. Read the image.
//readPlainImage(plainImg);
//Step 0.a: Check if the directory exists. If not, create it.
File tgtDir_file = new File(tgtDir);
if(!tgtDir_file.exists()) { //this directory does not exist.
tgtDir_file.mkdir();
}
Font nf = null;
try {
nf = Font.createFont(Font.TRUETYPE_FONT, new File("C:\\Windows\\Fonts\\" + fontName + ".ttf"));
} catch (FontFormatException | IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
if(nf != null) {
f = nf.deriveFont(Font.BOLD, fontSize);
}
if(f == null) {
System.out.println("Font is still null.");
}
//Step 1. Read csv file and get the string.
FileInputStream fis = null;
BufferedReader br = null;
try {
fis = new FileInputStream(new File(csvFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String temp = "\u0b85";
System.out.println(temp.length());
for(int i = 0; i < temp.length(); i++) {
System.out.print(temp.charAt(i));
}
//SAMPLE CODE ONLY. CHECK IF IT CAN PRINT A SINGLE CHARACTER IN FONT.
BufferedImage img = new BufferedImage(410, 200, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 410, 200);
System.out.println("String being printed = " + temp.codePointAt(0));
g.setColor(Color.BLACK);
g.setFont(f);
if(f.canDisplay('\u0b85')) {
System.out.println("Can display code = \u0b85");
} else {
System.out.println("Cannot display code = \u0b85");
}
g.drawString(temp, 10, 35);
//g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
g.dispose();
try {
ImageIO.write(img, "jpeg", new File(tgtDir + "\\" + "a.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File written successfully to a");
//System.out.println("Cat,,बिल्ली,,,");
if(fis != null) {
try {
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
System.out.print("Unsupported encoding");
}
String line = null;
if(br != null) {
try {
while((line = br.readLine()) != null) {
if(line != null) {
System.out.println("Line = " + line);
List<String> word_translation = new ArrayList<String>();
parseLine(line, word_translation); //function to parse the line.
//printImages(word_translation);
if(word_translation.size() > 0) {
printImages_temp(word_translation);
}
//now that images have been read, read the plain image afresh.
//readPlainImage(plainImg);
word_translation.clear();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
public static void printImages_temp(List<String> list) {
/* Function to print translations contained in list to images.
* Steps:
* 1. Take plain white image.
* 2. Write English word on top.
* 3. Take each translation and print one to each line.
*/
String dest = tgtDir + "\\" + list.get(0) + ".jpg"; //destination file image.
//compute height and width of image.
int img_height = list.size() * 35 + 20;
int img_width = 0;
int max_length = 0;
for(int i = 0; i < list.size(); i++) {
if(list.get(i).length() > max_length) {
max_length = list.get(i).length();
}
}
img_width = max_length * 20;
System.out.println("New dimensions of image = " + img_width + " " + img_height);
BufferedImage img = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, img_width, img_height);
//image has to be written to another file. Do not write English word, which is why list starts iteration from 1.
for(int i = 1; i < list.size(); i++) {
System.out.println("String being printed = " + list.get(i).codePointAt(0));
g.setColor(Color.BLACK);
g.setFont(f);
g.drawString(list.get(i), 10, (i + 1) * 35);
}
//g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
g.dispose();
try {
ImageIO.write(img, "jpeg", new File(dest));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File written successfully to " + dest);
}
public static void purge(String line) {
//This removes any inverted commas and tabs from the line apart from trimming it.
System.out.println("Line for purging = " + line);
int fromIndex = line.indexOf("\"");
//System.out.println("from index = " + fromIndex);
if(fromIndex != -1) {
line = line.substring((fromIndex + 1));
int toIndex = line.lastIndexOf("\"", line.length() - 1);
if(toIndex != -1) {
line = line.substring(0, (toIndex));
}
}
line.replaceAll("\t", " ");
line.trim();
System.out.println("Line after purging = " + line);
}
public static void parseLine(String line, List<String> result) {
/*
* This function parses the string and gets the different hindi meanings.
*/
//int index = line.indexOf(",");
//int prev_index = 0;
String[] arr = line.split(",");
List<String> l = new ArrayList<String>(Arrays.asList(arr));
for(int i = 0; i < l.size(); i++) {
if(l.get(i).isEmpty()) { //if the string at position i is empty.
l.remove(i);
}
}
for(int i = 0; i < l.size(); i++) { //inefficient copy but should be short.
String ith = l.get(i).trim();
if(!(ith.isEmpty())) { //add a string to result only if it is non-empty.
//in some entries, there are commas. they have been replaced with !?. find them and replace them.
if(ith.contains("!?")) {
//System.out.println(r + " contains !?");
String r = ith.replace("!?", ",");
result.add(r);
} else if(ith.contains("\n")) {
String r = ith.replace("\n", " ");
System.out.println("found new line in " + ith);
result.add(r);
} else {
result.add(ith);
}
}
}
for(int i = 0; i < result.size(); i++) {
System.out.println("Result[" + i + "] = " + result.get(i));
}
//System.out.println("Line being printed = " + line);
}
}
The above text was written by professional translators. So, is there something here that I am missing?
to test the concrete Font with methods in API Font.canDisplay
required to test in Unicode form (for mixing chars from a few languages (Tamil & Bengali))
please can you post and SSCCE, with used Font and can be based on

First line and last line in jtextarea viewport

i am looking for a function which gives the viewport starting line and viewport ending line from jtextarea. The below code works fine. But when the number of lines in the jtextarea is too big, say 10,000 lines, response of the cursor becoming very slow. I narrowed down the line which is causing it, it is,
startLine = getRow(topLeft, editorTextArea) - 1; //editorTextArea is jtextarea name
endLine = getRow(bottomRight, editorTextArea);
I am calling the startAndEndLine() on every keyPressEvent
Can someone suggest me a better code, which is efficient?
private void startAndEndLine() {
Rectangle r = editorTextArea.getVisibleRect();
Point topLeft = new Point(r.x, r.y);
Point bottomRight = new Point(r.x + r.width, r.y + r.height);
try {
startLine = getRow(topLeft, editorTextArea) - 1;
endLine = getRow(bottomRight, editorTextArea);
} catch (Exception ex) {
// System.out.println(ex);
}
}
public int getViewToModelPos(Point p, JTextComponent editor) {
int pos = 0;
try {
pos = editor.viewToModel(p);
} catch (Exception ex) {
}
return pos;
}
public int getRow(Point point, JTextComponent editor) {
int pos = getViewToModelPos(point, editor);
int rn = (pos == 0) ? 1 : 0;
try {
int offs = pos;
while (offs > 0) {
offs = Utilities.getRowStart(editor, offs) - 1;
rn++;
}
} catch (BadLocationException e) {
System.out.println(e);
}
return rn;
}
This is based on a solution by JigarJoshi from this question Java: column number and line number of cursor's current position ... You gotta love this site ;)
protected int getLineNumber(int modelPos) throws BadLocationException {
return textArea.getLineOfOffset(modelPos) + 1;
}
Rectangle viewRect = scrollPane.getViewport().getViewRect();
Point startPoint = viewRect.getLocation();
int pos = textArea.viewToModel(startPoint);
try {
int startLine = getLineNumber(pos);
Point endPoint = startPoint;
endPoint.y += viewRect.height;
pos = textArea.viewToModel(endPoint);
int endLine = getLineNumber(pos);
System.out.println(startLine + " - " + endLine);
} catch (BadLocationException exp) {
}
This is not entirely accurate, but gives you a starting point.

Categories