How to change text size to print on thermal printer - java

I have a java applicato that use the thermal print to printer a text. I use this printer to print the order for the bar.
This is an example of the ticket:
--> BAR
Coca Cola 1 x 1.5
Fanta 1 x 1.5
-------------------
TOTALE 3.00 euro
And the code to print this ticket works.
But I wanto to change the font size because the font is to small. How can I change the font ??
This is the code that I use to create and printer a ticket:
PrinterBean localPrinterBean = null;
StringBuffer localStringBuffer = null;
HashMap localHashMap=null;
if(emettiScontrinoCartaceo){
//PER LA STAMPA SCOTRNIO
localPrinterBean = getPrinterBean();
localStringBuffer = new StringBuffer();
localHashMap = null;
if ((localPrinterBean.isPrn_Enabled()) && (!localPrinterBean.isPrn_Onlyticket()))
{
//log.info("" + localPrinterBean.getPrn_driver());
localHashMap = PrinterManager.loadEscDriver(localPrinterBean);
//localStringBuffer.append("\n");
localStringBuffer.append(String.format("\t%s->> %s%s\n", new Object[] { localHashMap.get("size2w"), "BAR", localHashMap.get("size2w-off") }));
localStringBuffer.append("\n");
}
//FINE STAMPA SCOTNRINO
}
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
ArticoliScontrini artSco = (ArticoliScontrini) (entry.getValue());
//devo inserire nella lista le righe di stampa dello scontrino
//INIZIO STAMPA SCONTRINO
localStringBuffer.append(String.format("%s\n", new Object[] { artSco.getDescrizioneArticolo() }));
String quantita = artSco.getQuantita() + " x " +artSco.getPrezzoTotStringFormattato();//toString(artSco.getQuantita(), true);
localStringBuffer.append(String.format("\t %s", new Object[] { quantita }));
localStringBuffer.append("\n");
//FINE STAMPA SCONTRINO
}
localStringBuffer.append("------------------------------------------");
localStringBuffer.append("\n");
String totale = "TOTALE " + decimalFormatter2.format(totaleScontrinoCartaceo) + " euro";
localStringBuffer.append(String.format("%s\n", new Object[] { totale }));
String str = localStringBuffer.toString();
try{
cbPrintBuffer(localPrinterBean);
}
catch(Exception e){
VisualMessageScontrini.getErroreStampaScontrino();
}
public void cbPrintBuffer(PrinterBean paramPrinterBean)
throws Exception
{
/*Object localObject1 = JabirCfg.hexItIfn(paramPrinterBean.getPrn_Hexinit());
if ((localObject1 != null) && (!((String)localObject1).equals(""))) {
printRawBytes(paramPrinterBean, ((String)localObject1).getBytes());
}*/
Object localObject1 = null;
if (paramPrinterBean.hasPrn_Bitopt(2))
{
localObject1 = new FileOutputStream(paramPrinterBean.getPrn_driver());
((FileOutputStream)localObject1).write(cbGetFlow());
((FileOutputStream)localObject1).close();
return;
}
localObject1 = PrinterManager.getPrintService_cached(paramPrinterBean);
if (paramPrinterBean.isPrnGd())
{
boolean bool = paramPrinterBean.hasPrn_Bitopt(32);
PrinterJob localObject2 = PrinterJob.getPrinterJob();
((PrinterJob)localObject2).setPrintService((PrintService)localObject1);
((PrinterJob)localObject2).setJobName("easy ticket");
PageFormat localPageFormat = ((PrinterJob)localObject2).defaultPage();
PrinterExtra.deserialize_pagejson_to_PageFormat(paramPrinterBean.getPrn_pagejson(), localPageFormat);
Printable localPrintable = null;
for (int i = 0;; i++)
{
if (bool) {
localPrintable = cbPrintable(i);
} else {
localPrintable = cbPrintable(-1);
}
if (localPrintable == null) {
break;
}
((PrinterJob)localObject2).setPrintable(localPrintable, ((PrinterJob)localObject2).validatePage(localPageFormat));
((PrinterJob)localObject2).print();
if (!bool) {
break;
}
String str = JabirCfg.hexItIfn("0x1b 0x6d");
printRawBytes(paramPrinterBean, str.getBytes());
}
return;
}
DocPrintJob localDocPrintJob = ((PrintService)localObject1).createPrintJob();
Object localObject2 = new SimpleDoc(cbGetFlow(), DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
localDocPrintJob.print((Doc)localObject2, new HashPrintRequestAttributeSet());
}

Related

Problem with reading textfiles with scanner in Java and ArrayLists

I'm having a problem where I read a textfile named "songs.txt" with Scanner in a function called loadFiles() which every line is:
Music ID # Song Name # Release Date
And with this I create a Song object, and then store said object in a ArrayList. After reading the file, I clone this ArrayList so I can return a ArrayList with the songs read and clear the first ArrayList to prevent the cases where for exemple:
(PS: I use the ArrayLists as global variables)
songs.txt has this structure:
1oYYd2gnWZYrt89EBXdFiO#Message In A Bottle#1979
7zxc7dmd82nd92nskDInds#Sweet Child of Mine#1980
And the loadFiles() is called 2 times, the ArrayList would have a size of 4 instead of 2 as it should be. So that's why after songs.txt is read I copy the arrayList and then clear the first ArrayList that way the ArrayList that's returned only has the size of 2.
This is my code:
package pt.ulusofona.aed.deisiRockstar2021;
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static ArrayList < Song > teste6 = new ArrayList < > ();
public static ArrayList < Song > getSongsArray = new ArrayList < > ();
public static ArrayList < Artista > testeSongArtists = new ArrayList < > ();
public static ParseInfo parseInfoSongsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsArtistsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsDetailsTxT = new ParseInfo(0, 0);
public static void main(String[] args) throws IOException {
ArrayList < Song > teste7 = new ArrayList < Song > ();
loadFiles();
loadFiles();
teste7 = getSongs();
ParseInfo teste8 = getParseInfo("songs.txt");
System.out.println("\n----------------------TESTE DO MAIN----------------------");
System.out.println(teste7.toString());
System.out.println(teste8.toString());
System.out.println(getSongsArray.size());
}
public static void loadFiles() throws IOException {
//Aqui lê-se o ficheiro songs.txt
System.out.println("----------------------LEITURA DO FICHEIRO songs.txt------------");
String nomeFicheiro = "songs.txt";
try {
File ficheiro = new File(nomeFicheiro);
FileInputStream fis = new FileInputStream(ficheiro);
Scanner leitorFicheiro = new Scanner(fis);
while (leitorFicheiro.hasNextLine()) {
String linha = leitorFicheiro.nextLine();
String dados[] = linha.split("#");
if (dados.length != 3) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[2].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
//Meter para ignorar a acabar com espaço
parseInfoSongsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String nome = dados[1];
int anoLancamento = Integer.parseInt(dados[2]);
Song song = new Song(idTemaMusical, nome, null, anoLancamento, 0, false, 0, 0, 0, 0);
teste6.add(song);
}
leitorFicheiro.close();
getSongsArray = (ArrayList < Song > ) teste6.clone();
teste6.clear();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro + " nao foi encontrado.";
System.out.println(mensagem);
}
System.out.println(teste6.toString());
System.out.println("Ok: " + parseInfoSongsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_artists.txt------------");
//Aqui é lido o ficheiro song_artists.txt, mas falta ver se é preciso separar vários artistas com o mesmo ID para posições diferentes no ArrayList
String nomeFicheiro2 = "song_artists.txt";
try {
File song_artists = new File(nomeFicheiro2);
FileInputStream fis2 = new FileInputStream(song_artists);
Scanner leitorFicheiro2 = new Scanner(fis2);
while (leitorFicheiro2.hasNextLine()) {
String linha = leitorFicheiro2.nextLine();
String dados[] = linha.split("#");
if (dados.length != 2) {
parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsArtistsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String artista = dados[1];
Artista artista2 = new Artista(idTemaMusical, artista);
testeSongArtists.add(artista2);
}
leitorFicheiro2.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro2 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println(testeSongArtists.toString());
System.out.println("Ok: " + parseInfoSongsArtistsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_details.txt------------");
//Aqui lê-se o ficheiro song_details.txt
boolean letra = false;
ArrayList < Song > testeSongDetails = new ArrayList < Song > ();
String nomeFicheiro3 = "song_details.txt";
try {
File song_details = new File(nomeFicheiro3);
FileInputStream fis3 = new FileInputStream(song_details);
Scanner leitorFicheiro3 = new Scanner(fis3);
while (leitorFicheiro3.hasNextLine()) {
String linha = leitorFicheiro3.nextLine();
String dados[] = linha.split("#");
if (dados.length != 7) {
parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[3].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[4].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[5].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[6].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsDetailsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
//System.out.println(idTemaMusical);
int duracao = Integer.parseInt(dados[1]);
//System.out.println(duracao);
int letraExplicita = Integer.parseInt(dados[2]);
//System.out.println(letraExplicita);
if (letraExplicita == 0) {
letra = false;
} else {
letra = true;
}
//System.out.println(letra);
int populariedade = Integer.parseInt(dados[3]);
//System.out.println(populariedade);
double dancabilidade = Double.parseDouble(dados[4]);
//System.out.println(dancabilidade);
double vivacidade = Double.parseDouble(dados[5]);
//System.out.println(vivacidade);
double volumeMedio = Double.parseDouble(dados[6]);
//System.out.println(volumeMedio);
Song song = new Song(idTemaMusical, null, null, 0, duracao, letra, populariedade, dancabilidade, vivacidade, volumeMedio);
testeSongDetails.add(song);
}
leitorFicheiro3.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro3 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println("Ok: " + parseInfoSongsDetailsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED);
}
public static ArrayList < Song > getSongs() {
return getSongsArray;
}
public static ParseInfo getParseInfo(String fileName) {
if (fileName == "songs.txt") {
return parseInfoSongsTxT;
}
if (fileName == "song_artists.txt") {
return parseInfoSongsArtistsTxT;
}
if (fileName == "song_details.txt") {
return parseInfoSongsDetailsTxT;
}
return null;
}
}
The problem is that when I made a test to check the function where the ArrayList is returned to see the size of the ArrayList it always comes as 0.
I think it's because only the function the returns the ArrayList is tested so loadFiles() isn't executed so the ArrayListo never gets cloned and that makes the ArrayList that is returned stay the same.
I thought about calling loadFiles() inside getSongs() and that way I would guarantee that the ArrayList is cloned but that would make getSongs use "throws IOException" and since I have to respect the school's project guide and getSongs doesn't include "throws IOException" i can't put it there.
But the more I think about it, that doesn't even make sense because how can they test it with a file of their own and loadFiles() isn't executed?
I'm out of ideas how to solve this problem, any help is welcome thank you.

How to get bookmarked table and rows in text file?

I'm having the docx file with the following string
"My name is santhanam"
"I'm from India"
"I love docx4j"
And I bookmarked the above three paragraph with the bookmark name para0,para1,para2. I need to get the output as text file with following string
{para0}My name is santhanam{para0}
{para1}I'm from India{para1}
{para2}I love docx4j{para2}
Which I already succeeded with following code.
public class GetBookMark {
public static void main(String[] args) throws Exception {
String docString = "";
String outputfilepath = "5.txt";
String inputfilepath = "bookmark.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
// String bookmark[] = new String[100000];
GetBookMark gb = new GetBookMark();
ClassFinder finder = new ClassFinder(CTBookmark.class); // <----- change
// this to suit
new TraversalUtil(documentPart.getContent(), finder);
for (Object o : finder.results)
{
CTBookmark BookMkStart = (CTBookmark) o;
String BookMarkName = BookMkStart.getName();
if (BookMarkName.startsWith("para")) {
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + BookMarkName + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + BookMarkName + ">");
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
}
}
// System.out.println("Document\n---------------\n" + docString);
try {
// BufferedWriter bw = new BufferedWriter(new
// FileWriter(outputfilepath));
Writer writer = new OutputStreamWriter(new FileOutputStream(outputfilepath), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(docString);
bw.close();
} catch (Exception e) {
System.out.println("Exception while writing to file : " + e);
}
}
public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement)
obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
private P findBookmarkedParagraphInMainDocumentPart(String name, MainDocumentPart documentPart)
throws JAXBException, Docx4JException {
final String xpath = "//w:bookmarkStart[#w:name='" + name + "']/..";
List<Object> objects = documentPart.getJAXBNodesViaXPath(xpath, false);
return (org.docx4j.wml.P) XmlUtils.unwrap(objects.get(0));
}
// No xpath implementation for other parts than main document; traverse
// manually
private P findBookmarkedParagraphInPart(Object parent, String bookmark) {
P p = traversePartForBookmark(parent, bookmark);
return p;
}
// Used internally by findBookmarkedParagrapghInPart().
private P traversePartForBookmark(Object parent, String bookmark) {
P p = null;
List children = TraversalUtil.getChildrenImpl(parent);
if (children != null) {
for (Object o : children) {
o = XmlUtils.unwrap(o);
if (o instanceof CTBookmark) {
if (((CTBookmark) o).getName().toLowerCase().equals(bookmark)) {
return (P) parent; // If bookmark found, the surrounding
// P is what is interesting.
}
}
p = traversePartForBookmark(o, bookmark);
if (p != null) {
break;
}
}
}
return p;
}
}
Now I bookmarked the docx file which contains tables with table0 to table(etc) with bookmarked (Tr)rows and (Tc)cells.Is it possible to get the output as
{table0}{row0}{cello}{para0}text string{para0}{para1}text string{para1}{cell0}{row0}
{row1}{cell1}{para2}text string{para2}{para3}text string{para3}{cell1}{row1}{table0}
Thanks in advance.
UPDATE
Now,I'm halfway there with the following code
public class GetBookMark {
public static void main(String[] args) throws Exception {
String docString = "";
String outputfilepath = "BMChapter 14.txt";
String inputfilepath = "BMTable.docx";
String rowbm = null;
String tblbm = null;
String parabm = null;
String cellbm = null;
String tblparabm = null;
List<Object> tblTexts = null;
String partDocString = null;
String prtblbm = null;
String prrowbm = null;
String prcellbm = null;
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
GetBookMark gb = new GetBookMark();
ClassFinder finder = new ClassFinder(CTBookmark.class); // <----- change
new TraversalUtil(documentPart.getContent(), finder);
for (Object o : finder.results) {
CTBookmark BookMkStart = (CTBookmark) o;
String BookMarkName = BookMkStart.getName();
if (BookMarkName.startsWith("para")) {
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + BookMarkName + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + BookMarkName + ">");
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
} else {
if (BookMarkName.startsWith("table")) {
// rowbm = "</"+BookMarkName+">";
// tblbm = "<"+BookMarkName+">";
tblbm = BookMarkName;
}
if (BookMarkName.startsWith("row")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm +="<"+BookMarkName+">";
rowbm = BookMarkName;
}
if (BookMarkName.startsWith("cell")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm+="<"+BookMarkName+">";
cellbm = BookMarkName;
}
if (BookMarkName.startsWith("tble")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm+="<"+BookMarkName+">";
tblparabm = BookMarkName;
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
if (prtblbm != tblbm) {
docString += "<" + tblbm + ">";
}
if (prrowbm != rowbm) {
docString += "<" + rowbm + ">";
}
if (prcellbm != cellbm) {
docString += "<" + cellbm + ">";
}
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + tblparabm + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + tblparabm + ">");
}
prtblbm = tblbm;
prrowbm = rowbm;
prcellbm = cellbm;
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
}
}
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(outputfilepath), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(docString);
bw.close();
} catch (Exception e) {
System.out.println("Exception while writing to file : " + e);
}
}
System.out.println(docString);
}

JTextField Doesn't show properly

I'm making a application where you can manage the inventory of a store. I want to have the ability to change the current stock of certain items. First you select the items you want to change from a JTable using checkboxes then you click a JButton which triggers an ActionEvent then a JOptionPane appears where you can input the new stock numbers.
The problem is that ,depending on what you select, it doesn't show the proper info asbout the article and sometimes it doesn't even show the JTextField I use for the input
Here is my Code:
if (eventSource == bestelBrandstof) {
ArrayList<Integer> brandstofTID = new ArrayList<Integer>();
ArrayList<String> brandstofType = new ArrayList<String>();
ArrayList<JTextField> aantallen = new ArrayList<JTextField>();
for (int i = 0; i < modelBrandstof.getRowCount(); i++) {
if ((boolean) modelBrandstof.getValueAt(i, 0)) {
brandstofType.add((String) modelBrandstof.getValueAt(i, 1));
brandstofTID.add(Integer.parseInt((String) modelBrandstof.getValueAt(i, 2)));
aantallen.add(new JTextField("", 5));
}
}
if (brandstofType.size() > 0) {
bestellenBrandstof = new JPanel();
bestellenBrandstof.setLayout(new FlowLayout());
bestellenBrandstof.add(new JLabel("Hoeveel liter wilt u van de volgende brandstof(fen) bestellen?"));
for (String a : brandstofType) {
bestellenBrandstof.add(new JLabel(a + " " + brandstofTID.get(brandstofType.indexOf(a))));
bestellenBrandstof.add(aantallen.get(brandstofType.indexOf(a)));
}
int n = JOptionPane.showConfirmDialog(null, bestellenBrandstof);
if (n == JOptionPane.YES_OPTION) {
boolean empty = false;
for (JTextField a : aantallen) {
if (a.getText().equals(""))
empty = true;
}
if (empty == false) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String datumVandaag = dateFormat.format(new Date());
FileWriter fw = new FileWriter("./bestellingen/Bestellen_Brandstof_" + datumVandaag + ".txt");
PrintWriter pw = new PrintWriter(fw);
for (Integer a : brandstofTID) {
pw.print("Nr: " + a.toString() + ", Type: " + brandstofType.get(brandstofTID.indexOf(a)) + ", Tankstation Identificatie: " + aantallen.get(brandstofTID.indexOf(a)).getText());
pw.print(System.lineSeparator());
}
pw.close();
} catch (IOException exc) {
exc.printStackTrace();
}
JOptionPane.showMessageDialog(null, "De Bestellijst in aangemaakt");
} else {
JOptionPane.showMessageDialog(null, "Aantal Liters niet volledig ingevuld");
}
}
} else {
JOptionPane.showMessageDialog(null, "Selecteer onder het kopje 'Bestellen?' welke onderdelen u wilt bestellen");
}
}
Edit:
Here is some similar code I wrote where it works properly
if (eventSource == bestelOnderdelen) {
ArrayList<Integer> onderdeelNrs = new ArrayList<Integer>();
ArrayList<String> onderdeelOmschrijving = new ArrayList<String>();
ArrayList<JTextField> aantallen = new ArrayList<JTextField>();
for (int i = 0; i < modelOnderdelen.getRowCount(); i++) {
if ((boolean) modelOnderdelen.getValueAt(i, 0)) {
onderdeelNrs.add(Integer.parseInt((String) modelOnderdelen.getValueAt(i, 1)));
onderdeelOmschrijving.add((String) modelOnderdelen.getValueAt(i, 2));
aantallen.add(new JTextField("", 5));
}
}
if (onderdeelNrs.size() > 0) {
bestellenOnderdelen = new JPanel();
bestellenOnderdelen.setLayout(new FlowLayout());
bestellenOnderdelen.add(new JLabel("Hoeveel wilt u van de volgende artikelen bestellen?"));
for (Integer a : onderdeelNrs) {
bestellenOnderdelen.add(new JLabel(Integer.toString(a) + " " + onderdeelOmschrijving.get(onderdeelNrs.indexOf(a))));
bestellenOnderdelen.add(aantallen.get(onderdeelNrs.indexOf(a)));
}
int n = JOptionPane.showConfirmDialog(null, bestellenOnderdelen);
if (n == JOptionPane.YES_OPTION) {
boolean empty = false;
for (JTextField a : aantallen) {
if (a.getText().equals(""))
empty = true;
}
if (empty == false) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String datumVandaag = dateFormat.format(new Date());
FileWriter fw = new FileWriter("./bestellingen/Bestellen_Onderdelen_" + datumVandaag + ".txt");
PrintWriter pw = new PrintWriter(fw);
for (Integer a : onderdeelNrs) {
pw.print("Nr: " + a.toString() + ", Omschrijving: " + onderdeelOmschrijving.get(onderdeelNrs.indexOf(a)) + ", Aantal: " + aantallen.get(onderdeelNrs.indexOf(a)).getText());
pw.print(System.lineSeparator());
}
pw.close();
} catch (IOException exc) {
exc.printStackTrace();
}
JOptionPane.showMessageDialog(null, "De Bestellijst in aangemaakt");
} else {
JOptionPane.showMessageDialog(null, "Aantallen niet volledig ingevuld");
}
}
} else {
JOptionPane.showMessageDialog(null, "Selecteer onder het kopje 'Bestellen?' welke onderdelen u wilt bestellen");
}
}
Edit:
I added ArrayList<Integer> uniqueID = new ArrayList<Integer>(); and edited this part
for (Integer a : uniqueID) {
bestellenBrandstof.add(new JLabel(brandstofType.get(uniqueID.indexOf(a)) + " " + brandstofTID.get(uniqueID.indexOf(a))));
bestellenBrandstof.add(aantallen.get(uniqueID.indexOf(a)));
}
I got it the issue is with below line
bestellenBrandstof.add(aantallen.get(brandstofType.indexOf(a)));
If aantallen.get(brandstofType.indexOf(a)) returns same JTextField then it is not added in JPanel again hence some JTextField are not shown.
Please check the value of brandstofType and onderdeelNrs array.

How to add Headers to multiple sheets in a workbook using Apache POI

I have created a Batch Reporting using Apache POI. I need to know how to add Headers to both sheets. I used getHeader() but that adds same Headers for both sheets and I need to add different headers to both sheets. My code is following.
Excel Writer:
public class ExcelWriter {
Logger log = Logger.getLogger(ExcelWriter.class.getName());
private HSSFWorkbook excel;
public ExcelWriter() {
excel = new HSSFWorkbook();
}
public HSSFWorkbook getWorkbook() {
return excel;
}
public void writeExcelFile(String filename, String[] columns, Object[][] data, HSSFCellStyle[] styles,
HSSFCellStyle columnsStyle, String[] header, String[] footer) throws IOException {
FileOutputStream out = new FileOutputStream(filename);
HSSFSheet sheet = excel.createSheet("Daily Screening");
HSSFSheet sheet1 = excel.createSheet("Parcel Return");
int numHeaderRows = header.length;
createHeader(sheet,header,columns.length, 0);
createColumnHeaderRow(sheet,columns,numHeaderRows,columnsStyle);
int rowCtr1 = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr1;
else
rowCtr1 = rowCtr1 + 2;
createRow(sheet, data[i], rowCtr1, styles);
}
int totalRows = rowCtr1 + 1;
createHeader(sheet1,footer,columns.length, totalRows);
excel.write(out);
out.close();
}
private void createHeader(HSSFSheet sheet1, String[] header, int columns, int rowNum) {
for( int i = 0; i < header.length ; i++ ) {
HSSFRow row = sheet1.createRow(i + rowNum);
HSSFCell cell = row.createCell((short) 0);
String text = header[i];
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(text);
HSSFCellStyle style = excel.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont arialBoldFont = excel.createFont();
arialBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
arialBoldFont.setFontName("Arial");
arialBoldFont.setFontHeightInPoints((short) 12);
style.setFont(arialBoldFont);
if (!isEmpty(header[i]) && rowNum < 1) {
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
}
cell.setCellStyle(style);
sheet1.addMergedRegion( new Region(i+rowNum,(short)0,i+rowNum,(short)(columns-1)) );
}
}
private HSSFRow createColumnHeaderRow(HSSFSheet sheet, Object[] values, int rowNum, HSSFCellStyle style) {
HSSFCellStyle[] styles = new HSSFCellStyle[values.length];
for( int i = 0; i < values.length; i++ ) {
styles[i] = style;
}
return createRow(sheet,values,rowNum,styles);
}
private HSSFRow createRow(HSSFSheet sheet1, Object[] values, int rowNum, HSSFCellStyle[] styles) {
HSSFRow row = sheet1.createRow(rowNum);
for( int i = 0; i < values.length; i++ ) {
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(styles[i]);
try{
Object o = values[i];
if( o instanceof String ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
else if (o instanceof Double) {
Double d = (Double) o;
cell.setCellValue(d.doubleValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if (o instanceof Integer) {
Integer in = (Integer)o;
cell.setCellValue(in.intValue());
}
else if (o instanceof Long) {
Long l = (Long)o;
cell.setCellValue(l.longValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if( o != null ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return row;
}
public boolean isEmpty(String str) {
if(str.equals(null) || str.equals(""))
return true;
else
return false;
}
}
Report Generator which includes Headers, footer, and columns:
public class SummaryReportGenerator extends ReportGenerator {
Logger log = Logger.getLogger(SummaryReportGenerator.class.getName());
public SummaryReportGenerator(String reportDir, String filename) {
super( reportDir + filename + ".xls", reportDir + filename + ".pdf");
}
public String[] getColumnNames() {
String[] columnNames = {"ISC\nCode", "Total\nParcels", "Total\nParcel Hit\n Count",
"Filter Hit\n%", "Unanalyzed\nCount", "Unanalyzed\n%",
"Name\nMatch\nCount", "Name\nMatch\n%", "Pended\nCount",
"Pended\n%", "E 1 Sanction\nCountries\nCount", "E 1 Sanction\nCountries\n%", "Greater\nthat\n$2500\nCount", "Greater\nthat\n$2500\n%",
"YTD\nTotal Hit\nCount", "YTD\nLong Term\nPending", "YTD\nLong Term\n%"};
return columnNames;
}
public HSSFCellStyle getColumnsStyle(HSSFWorkbook wrkbk) {
HSSFCellStyle style = wrkbk.createCellStyle();
style.setWrapText(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont timesBoldFont = wrkbk.createFont();
timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
timesBoldFont.setFontName("Arial");
style.setFont(timesBoldFont);
return style;
}
public Object[][] getData(Map map) {
int rows = map.size();// + 1 + // 1 blank row 1; // 1 row for the grand total;
int cols = getColumnNames().length;
Object[][] data = new Object[rows][cols];
int row = 0;
for (int i=0; i < map.size(); i++ ){
try{
SummaryBean bean = (SummaryBean)map.get(new Integer(i));
data[row][0] = bean.getIscCode();
data[row][1] = new Long(bean.getTotalParcelCtr());
data[row][2] = new Integer(bean.getTotalFilterHitCtr());
data[row][3] = bean.getFilterHitPrctg();
data[row][4] = new Integer(bean.getPendedHitCtr());
data[row][5] = bean.getPendedHitPrctg();
data[row][6] = new Integer(bean.getTrueHitCtr());
data[row][7] = new Integer(bean.getRetiredHitCtr());
data[row][8] = new Integer(bean.getSanctCntryCtr());
data[row][9] = new Integer(bean.getC25Ctr());
data[row][10] = new Integer(bean.getCnmCtr());
data[row][11] = new Integer(bean.getCndCtr());
data[row][12] = new Integer(bean.getCnlCtr());
data[row][13] = new Integer(bean.getCneCtr());
data[row][14] = new Integer(bean.getVndCtr());
data[row][15] = new Integer(bean.getCilCtr());
data[row][16] = new Integer(bean.getHndCtr());
data[row][17] = new Integer(bean.getCnrCtr());
++row;
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return data;
}
public String[] getHeader(String startDate, String endDate) {
Date today = new Date();
String reportDateFormat = Utils.formatDateTime(today, "MM/dd/yyyyHH.mm.ss");
String nowStr = Utils.now(reportDateFormat);
String[] header = {"","EXCS Daily Screening Summary Report ","",
"for transactions processed for the calendar date range",
"from " + startDate + " to " + endDate,
"Report created on " + nowStr.substring(0,10)+ " at "
+ nowStr.substring(10)};
return header;
}
public HSSFCellStyle[] getStyles(HSSFWorkbook wrkbk) {
int columnSize = getColumnNames().length;
HSSFCellStyle[] styles = new HSSFCellStyle[columnSize];
HSSFDataFormat format = wrkbk.createDataFormat();
for (int i=0; i < columnSize; i++){
styles[i] = wrkbk.createCellStyle();
if (i == 0){
styles[i].setAlignment(HSSFCellStyle.ALIGN_LEFT);
}else{
styles[i].setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}
if (i == 1 || i == 2){
styles[i].setDataFormat(format.getFormat("#,###,##0"));
}
HSSFFont timesFont = wrkbk.createFont();
timesFont.setFontName("Arial");
styles[i].setFont(timesFont);
}
return styles;
}
public String[] getFooter() {
String[] header = {"","Parcel Return Reason Code Reference","",
"DPM = Sender and/or recipient matches denied party",
"HND = Humanitarian exception not declared",
"CNM = Content not mailable under export laws",
"VND = Value of content not declared",
"CNR = Customer non-response",
"C25 = Content Value greater than $2500",
"CIL = Invalid license",
"C30 = More than one parcel in a calendar month",
"CNL = Content description not legible",
"CNE = Address on mailpiece not in English",
"RFN = Requires full sender and addressee names",
"DGS = Dangerous goods",
"R29 = RE-used 2976 or 2976A",
"ANE = PS Form 2976 or 2976A not in English",
"ICF = Incorrect Customs Declaration Form used",
"DPR = Declaration of purpose required",
"ITN = Internal Transaction Number (ITN), Export Exception/Exclusion Legend (ELL), or Proof of Filing Citation (PFC) is required",
"OTH = Other","",};
return header;
}
}
Report Generator Abstract class
public void generateExcelReport(Map map, String startDate, String endDate) throws IOException {
ExcelWriter writer = new ExcelWriter();
writer.writeExcelFile( getXlsFilename(), getColumnNames(), getData(map),
getStyles(writer.getWorkbook()), getColumnsStyle(writer.getWorkbook()),
getHeader(startDate, endDate), getFooter());
Report Driver:
public class ReportDriver {
static Logger log = Logger.getLogger(ReportDriver.class.getName());
public static void main (String args[]){
if (args.length == 0) {
log.error("Usage - ReportDriver [Day|Week|Month|Year]");
System.exit(1);
}
String reportPeriod = args[0];
log.info("Begin Prior " + reportPeriod + " Report");
String dir = "c:\\excsbatch\\report\\";
Dates dates = new Dates();
dates.setDates(reportPeriod);
String startDate = dates.getStartDate();
String endDate = dates.getEndDate();
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
Calendar cal = Calendar.getInstance();
String timeStamp = dateFormat.format(cal.getTime());
String fileName = "prior" + reportPeriod + "Report" + timeStamp;
SummaryDAO dao = new SummaryDAO();
Map map = dao.extractData(startDate, endDate);
SummaryReportGenerator report = new SummaryReportGenerator(dir, fileName);
try {
report.generateExcelReport(map, startDate, endDate);
}
catch(Exception e) {
log.error(e.getMessage());
System.exit(2);
}
log.info("End Prior " + reportPeriod + " Report");
}
}

Loading contact from phone book in J2ME

I implemented this code below in order to read contacts from the addressbook of the phone
The problem is, In a case when all the numbers in the phonebook are saved in the SIM it reads and displays the contacts for selection.
But in a case whereby any number is included on the phone memory, it gives an application error.(OutOfMemoryException)
What do I do (PS do not mind some System.out.println statements there. I used them for debugging)
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i] + " " + allContactLists[1]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute() error");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
// ----
// System.out.println("loadErr1");
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// System.out.println(contactList.getName());//--Phone Contacts or Sim Contacts
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME)
&& contactList.isSupportedField(Contact.TEL)) {
// ContactLst.append("Reading contacts...", null);
// System.out.println("sup1");
Enumeration items = contactList.items();
// System.out.println("sup2");
Vector telNumbers = new Vector();
telNames = new Vector();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
// System.out.println(telCount);
// System.out.println(nameCount);
// we're only interested in contacts with a phone number
// nameCount should always be > 0 since FORMATTED_NAME is
// mandatory
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone numbers
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
System.out.println(telNumber + " " + "tel");
// check if ATTR_MOBILE is supported
if (contactList.isSupportedAttribute(Contact.TEL, Contact.ATTR_MOBILE)) {
if ((telAttributes & Contact.ATTR_MOBILE) != 0) {
telNames.insertElementAt(telNames, i);
telNumbers.insertElementAt(telNumber, i);
} else {
telNumbers.addElement(telNumber);
telNames.addElement(telNames);
}
}
// else {
//// telNames.addElement(contactName);
// telNumbers.addElement(telNumber);
// }
System.out.println("telephone nos");
}
// Shorten names which are too long
shortenName(contactName, 20);
for (int i = 0; i <= telNumbers.size(); i++) {
System.out.println(contactName + " here " + telNames.size());
telNames.addElement(contactName);
System.out.println(telNames.elementAt(i) + " na " + i);
}
names = new String[telNames.size()];
for (int j = 0; j < names.length; j++) {
names[j] = (String) telNames.elementAt(j);
System.out.println(names[j] + "....");
}
// allTelNames.addElement(telNames);
System.out.println("cap :" + telNames.size() + " " + names.length);
// telNames.removeAllElements();
// telNumbers.removeAllElements();
}
}
available = true;
} else {
// ContactLst.append("Contact list required items not supported", null);
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}

Categories

Resources