iText - Convert field names with square brackets to fields without square brackets? - itext

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfStamper;
import java.util.Set;
import java.io.FileOutputStream;
public class PDFFile {
public static final String xfaForm3 = "C:/PDF_Service/pdf-project/src/sample.pdf";
public static final String dest = "sample2.xml";
public static void main(String[] args)
{
PdfReader reader;
PdfReader.unethicalreading = true;
AcroFields form;
try{
reader = new PdfReader(xfaForm3);
PdfStamper stamper2 = new PdfStamper(reader, new FileOutputStream(dest));
form = stamper2.getAcroFields();
stamper2.close();
Set<String> fldNames = form.getFields().keySet();
for (String fldName : fldNames)
{
System.out.println( fldName + " : " + form.getField( fldName ) );
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
My code above is reading a PDF file that has the XFA format and it prints out something that looks like this:
F[0].P1[0].FFField1[14] : 11 Pine Drive
Instead of printing out "F[0].P1[0].FFField1[14]", how can I print out "Address"?
I would like my code to print out this:
Address : 11 Pine Drive

Related

How to read datamatrix embedded in document?

I try to read a datamatrix which is embedded into a document.
This is for an opensource project which helps to create and read 2DCODE standard.
I try with this code :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ZxingTest {
#Test
public void test() {
readQRCode("sfr-facture-1048469311-1.jpg");
readQRCode("sfr-facture-1048469311-1.png");
}
public static void readQRCode(String fileName) {
System.out.println("Try reading " + fileName);
File file = new File(fileName);
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image == null)
return;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
// hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.DATA_MATRIX));
decode(image, hints);
}
public static void decode(BufferedImage tmpBfrImage, Hashtable<DecodeHintType, Object> hintsMap) {
if (tmpBfrImage == null)
throw new IllegalArgumentException("Could not decode image.");
LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
Result tmpResult;
String tmpFinalResult;
try {
if (hintsMap != null && !hintsMap.isEmpty())
tmpResult = tmpBarcodeReader.decode(tmpBitmap, hintsMap);
else
tmpResult = tmpBarcodeReader.decode(tmpBitmap);
// setting results.
tmpFinalResult = String.valueOf(tmpResult.getText());
System.out.println("tmpFinalResult=" + tmpFinalResult);
} catch (Exception tmpExcpt) {
tmpExcpt.printStackTrace();
}
}
}
and those images found on the net :
sfr-facture-1048469311-1.jpg
sfr-facture-1048469311-1.png
But I get this exception regardless of the image format: com.google.zxing.NotFoundException
May you advise me an lib which parses the page and detect the datamatrix coordinates for a pre-processing cropping?
Or a better a example of code which read the datamatrix?
I have a solution to my problem. I use opencv to locate any barcode then, after extraction according to the returned coordinates, I read them with zxing.
I based my solution the work of http://karthikj1.github.io/BarcodeLocalizer/
this the code i use :
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import barcodelocalizer.Barcode;
import barcodelocalizer.CandidateResult;
import barcodelocalizer.ImageDisplay;
import barcodelocalizer.MatrixBarcode;
import barcodelocalizer.TryHarderFlags;
public class OpencvUtils {
private static boolean SHOW_INTERMEDIATE_STEPS = false;
private static boolean showImages = false;
public static String process_bufferedImage(BufferedImage bufferedImage) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(bufferedImage, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding buffered image " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
public static String process_image(String imgFile) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(imgFile, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding " + imgFile + " " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
private static String decodeBarcode(List<CandidateResult> candidateCodes, String filename, String caption) {
// decodes barcode using ZXing and either print the barcode text or says no
// barcode found
BufferedImage decodedBarcode = null;
String title = null;
Result result = null;
String barcodeText = null;
for (CandidateResult cr : candidateCodes) {
BufferedImage candidate = cr.candidate;
decodedBarcode = null;
LuminanceSource source = new BufferedImageLuminanceSource(candidate);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try {
result = reader.decode(bitmap, hints);
decodedBarcode = candidate;
title = filename + " " + caption + " - barcode text " + result.getText() + " " + cr.getROI_coords();
} catch (ReaderException re) {
}
if (decodedBarcode == null) {
title = filename + " - no barcode found - " + cr.getROI_coords();
if (showImages)
ImageDisplay.showImageFrame(candidate, title);
} else {
if (showImages)
ImageDisplay.showImageFrame(decodedBarcode, title);
System.out.println("Barcode text for " + filename + " is " + result.getText());
barcodeText = result.getText();
}
}
return barcodeText;
}
}
i added the method process_bufferedImage which process a java.awt.image.BufferedImage of a String filename.
And this sub-method to get the matrix of the BufferedImage bi.
protected Mat loadBufferedImage(BufferedImage bi) throws IOException {
// reads the BufferedImage passed in parameter
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bi, "png", byteArrayOutputStream);
byteArrayOutputStream.flush();
Mat mat = Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.IMREAD_UNCHANGED);
return mat;
}

JavaFX How can i save file with tabs?

I have a tabbed editor with TextArea and I want to save the selected file's textarea content.
But how can I do this?
Here I have my items defined (or what it's called on english. I'm danish) :
public static TabPane pane = new TabPane();
public static TextArea area;
public static ListView lines;
public static VBox box;
public static Tab tabs;
public static BorderPane bps;
My code for adding a tab:
public static void AddTab(String title, String con) {
area = new TextArea();
lines = new ListView();
box = new VBox();
bps = new BorderPane();
bps.setLeft(lines);
bps.setRight(area);
box.getChildren().addAll(bps);
tabs = new Tab(title);
tabs.setContent(box);
pane.getTabs().add(tabs);
}
When i add a tab i use this code :
int i;
for (i = 0; i < GUI.Editor.pane.getTabs().size(); i++) {
}
String title = "New File (" + i + ")";
GUI.Editor.AddTab(title, null);
GUI.Editor.pane.getSelectionModel().select(i);
But how can I save a file on this way?.
Oh and of course I know I need a file dialog (and I have try to save file).
The only thing I will need is how to get the content from the selected tab (when I mean content I mean the TextArea's content).
As you are setting tab content is VBox it's bit difficult to get the TextArea directly. One way is by doing multiple type casts from VBox to Textarea we can get the selected area.
private static TextArea getSelectedTabContent() {
Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
if(selectedTabContent instanceof VBox){
Node borderPane = ((VBox) selectedTabContent).getChildren().get(0);
if(borderPane instanceof BorderPane){
Node textAreaNode = ((BorderPane) borderPane).getRight();
if(textAreaNode instanceof TextArea){
return (TextArea) textAreaNode;
}
}
}
return null;
}
Below is the complete code to save to file.
package com.pw.jnotepad.app;
import com.pw.jnotepad.app.providers.AlertBox;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
public class StackOverflowAnswer extends Application {
public static TabPane pane = new TabPane();
public static TextArea area;
public static ListView lines;
public static VBox box;
public static Tab tabs;
public static BorderPane bps;
public static Stage window;
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
area = new TextArea();
lines = new ListView();
box = new VBox();
bps = new BorderPane();
bps.setTop(createMenuBar());
bps.setLeft(lines);
bps.setRight(area);
box.getChildren().addAll(bps);
tabs = new Tab("tab-1");
tabs.setContent(box);
pane.getTabs().add(tabs);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
// to create menu bar with file menu
private static MenuBar createMenuBar(){
Menu fileMenu = new Menu("File");
MenuItem saveFile = new MenuItem("Save");
saveFile.setOnAction(event -> {
System.out.println("Save file action triggered");
FileChooser fileChooser = createFileChooser("Save File");
File selectedFile = fileChooser.showSaveDialog(window);
if(selectedFile != null){
File savedFile = saveTextToFile(selectedFile);
if(savedFile!= null){
System.out.println("file saved successfully");
updateTabTitle(savedFile.getName());
}
}
});
fileMenu.getItems().addAll(saveFile);
return new MenuBar(fileMenu);
}
// to open save dialog window
private static FileChooser createFileChooser(String title) {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter onlyTextFilesFilter = new FileChooser.ExtensionFilter("Txt files(*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(onlyTextFilesFilter);
fileChooser.setTitle(title);
fileChooser.setInitialDirectory(Paths.get("").toAbsolutePath().toFile());
return fileChooser;
}
// to save the file into disk
public static File saveTextToFile(File file) {
TextArea selectedTabContent = getSelectedTabContent();
if(selectedTabContent!=null){
try(BufferedWriter buffer = new BufferedWriter(new FileWriter(file));) {
ObservableList<CharSequence> paragraphs = selectedTabContent.getParagraphs();
paragraphs.forEach(charSequence -> {
try {
buffer.append(charSequence);
buffer.newLine();
} catch (IOException e) {
System.out.println("failed to write to text file.");
AlertBox.display("File Save Error", "failed to write to text file.");
e.printStackTrace();
}
});
buffer.flush();
return file;
} catch (IOException e) {
System.out.println("failed to write to text file.");
AlertBox.display("File Save Error", "failed to write to text file.");
e.printStackTrace();
}
}
return null;
}
// to get selected text area
private static TextArea getSelectedTabContent() {
Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
if(selectedTabContent instanceof VBox){
Node borderPane = ((VBox) selectedTabContent).getChildren().get(0);
if(borderPane instanceof BorderPane){
Node textAreaNode = ((BorderPane) borderPane).getRight();
if(textAreaNode instanceof TextArea){
return (TextArea) textAreaNode;
}
}
}
return null;
}
// to update tab title by saved file name
private static void updateTabTitle(String name){
pane.getSelectionModel().getSelectedItem().setText(name);
}
}

Only one of the two AutoCompleteTextView are showing suggestions

I have two AutoCompleteTextView controls on the same page: ACTV1 and ACTV2 and only one (ACTV1 ) is showing suggestions from my database . For each databinding action I've made a java class separetely: ACTV1.java and ACTV2.java.
But if I am adding an intent filter (MAIN, LAUNCHER) in my manifest file for ACTV2.java class and setting in run configuration ACTV2.java as Launch Action then I won't get suggestions anymore for ACTV1 control but this time I'll get suggestions for ACTV2 control.
The two java classes are identically just that differ the name of some constants/controls name.
package com.fishing2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class CompleteBalti extends Activity {
//private CustomAutoCompleteView CompleteBalti;
private ArrayAdapter<String> adaperbalti;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partida);
}
final TextWatcher textChecker = new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void onTextChanged(CharSequence s, int start, int before, int count)
{
adaperbalti.clear();
callPHP1();
}
};
private void callPHP1(){
String result = "";
InputStream is=null;
AutoCompleteTextView CompleteBalti = (AutoCompleteTextView) findViewById(R.id.nume_localitate);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("st",CompleteBalti.getText().toString()));
{
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.3.159/wtf/balti.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
result = result.substring(1);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i=0;i<jArray.length(); i++)
{
json_data = jArray.getJSONObject(i);
adaperbalti.add(json_data.getString("nume_balta"));
}
} catch(Exception e1){
Log.e("log_tag", "Error converting result "+e1.toString());
}
}
}
}

ireport 3.7.4 on netbeans 6.9.1 won't execute

I'm new to java and jasperreport. I have a hard time executing a small report. I've added all the required jar file and encountered no errors.
How can I produce a pdf file using netbeans auto generated "mouseclicked" event of a jbutton?
Following is the code I've been working from the tutorial of thainetbeans and ireport tutorial site:
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.*;
import net.sf.jasperreports.view.*;
import net.sf.jasperreports.engine.xml.*;
public class MyiReportViewer extends javax.swing.JFrame {
/** Creates new form MyiReportViewer */
final String JDBC = "com.mysql.jdbc.Driver";
final String DB = "jdbc:mysql://localhost/afemdb?user=root&password";
private Connection con;
/** Creates new form NewJPanel */
public MyiReportViewer() {
initComponents();
try{
Class.forName(JDBC).newInstance();
con =DriverManager.getConnection(DB);
}
catch(Exception e){
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addComponent(jButton1)
.addContainerGap(230, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(jButton1)
.addContainerGap(205, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
try{
//JasperDesign jasperDesign = JRXmlLoader.load("C:\\Documents and Settings\\Lelou\\Desktop\\presentation\\InstructorQuestionaire.jrxml");
//JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
//JasperViewer.viewReport(jasperPrint, true);
JasperReport report = JasperCompileManager.compileReport("C:\\Documents and Settings\\Lelou\\Desktop\\presentation\\InstructorQuestionaire.jrxml");
JasperPrint print = JasperFillManager.fillReport(report, null, con);
JRViewer viewer = new JRViewer(print);
viewer.setOpaque(true);
viewer.setVisible(true);
}
catch(Exception e){
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// try{
// JasperDesign jasperDesign = JRXmlLoader.load("C:\\Documents and Settings\\Lelou\\Desktop\\presentation\\InstructorQuestionaire.jrxml");
// JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
// JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
// JasperViewer.viewReport(jasperPrint, true);
//JasperReport report = JasperCompileManager.compileReport("C:\\Documents and Settings\\Lelou\\Desktop\\presentation\\InstructorQuestionaire.jrxml");
//JasperPrint print = JasperFillManager.fillReport(report,null, con);
//JRViewer viewer = new JRViewer(print);
//viewer.setOpaque(true);
//viewer.setVisible(true);
// }
// catch(Exception e){
//}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyiReportViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
Add this in your jButton1ActionPerformed method. You do not need the MouseClickedEvent.
try {
URL reportFileURL = getClass().getResource("C:/Documents and Settings/Lelou/Desktop/presentation/InstructorQuestionaire.jrxml");
File reportFile = new File(reportFileURL.toURI());
JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
JasperViewer jv = new JasperViewer(jasperPrint);
JDialog viewer = new JDialog(this, "Batch Report", true);
viewer.setBounds(jv.getBounds());
viewer.getContentPane().add(jv.getContentPane());
viewer.setResizable(true);
viewer.setIconImage(jv.getIconImage());
viewer.setVisible(true);
} catch (JRException exc) {
System.out.println(exc.getMessage());
} catch (URISyntaxException exs) {
System.out.println(exs.getMessage());
}
(*) Note the slashes at the path-name. Get rid of the double back-slashes!
Here are your imports:
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JDialog;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;
import net.sf.jasperreports.engine.JasperPrint;
Here are the libraries you need (i use iReport 4.0.1):
Most of them are here: C:\Program Files\JasperSoft\iReport-4.0.1\ireport\modules\ext
Check your connection string. In doubt use this constructor:
public MyiReportViewer() {
initComponents();
try {
Class.forName(JDBC);
//con =DriverManager.getConnection(DB);
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/afemdb?useUnicode=true&characterEncoding=UTF-8",
"root", "password");
} catch (SQLException e) {
System.out.println("Con " + e);
}
} catch (ClassNotFoundException e) {
System.out.println("SQL" + e);
}
}
If it still does not work, there must be something wrong with your iReport.

How to run a main class from a GUI Jbutton?

I've created a main class (class file). As fas as i'm concerned, it works properly. Now, i'm creating a GUI which contains a button to launch that class file. How do I write the code for the actionListener in order to run mainProgram class?
This is the main class:
import java.io.*;
import java.util.*;
public class MainProgram
{
public static void main (String args[]) throws IOException
{
//Declare variables
Scanner in = new Scanner (System.in); // Scanner used for user input
BufferedReader inputQuote;
BufferedReader inputTheme;
BufferedReader inputCharacterAnalysis;
BufferedReader inputSignificance;
BufferedReader inputPlotEnhancement;
BufferedReader inputSpeaker;
String [][] quotes;
String text;
int quoteSelection;
int analysisSelection;
int howMany=0;
int count;
//Count the number of lines in a text file
FileReader fr = new FileReader ("CrucibleQuotations.txt");
LineNumberReader ln = new LineNumberReader (fr);
while (ln.readLine() != null)
{
howMany++;
}
//import information from the text file
inputQuote = new BufferedReader (new FileReader ("CrucibleQuotations.txt"));
inputTheme = new BufferedReader (new FileReader("CrucibleTheme.txt"));
inputCharacterAnalysis = new BufferedReader (new FileReader("CrucibleCharacterAnalysis.txt"));
inputSignificance = new BufferedReader (new FileReader("CrucibleSignificance.txt"));
inputPlotEnhancement = new BufferedReader (new FileReader("CruciblePlotEnhancement.txt"));
inputSpeaker = new BufferedReader (new FileReader("CrucibleSpeaker.txt"));
//Create array based on how many quotes available in the text file
quotes = new String [howMany][6];
//Store quote information in the array and display the list of quotations
for (int i=0; i<howMany; i++)
{
quotes [i][0] = inputQuote.readLine();
System.out.println (i+1 + ") " + quotes [i][0]);
quotes [i][1] = inputTheme.readLine();
quotes [i][2] = inputCharacterAnalysis.readLine();
quotes [i][3] = inputSignificance.readLine();
quotes [i][4] = inputPlotEnhancement.readLine();
quotes [i][5] = inputSpeaker.readLine();
}
//Ask user to choose the quote they want to analyze
System.out.println ("Choose a quotation by inputting the number. If the quotation you would like to analyse is unavailable, you may create your own by entering the number 0. ");
quoteSelection = in.nextInt ();
if (quoteSelection!=0)
{
//Show user selections to analyze
System.out.println ("Choose your analysis");
System.out.println ("1. Theme");
System.out.println ("2. Character Analysis");
System.out.println ("3. Significance");
System.out.println ("4. Plot Enhancement");
System.out.println ("5. Speaker");
analysisSelection = in.nextInt ();
//Display the analysis
if (analysisSelection <= 5 || analysisSelection > 0)
{
System.out.println (quotes [quoteSelection-1][analysisSelection]);
}
}
This would be my GUI class
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
public class GUI
{
public GUI()
{
JFrame frame = new JFrame ("Quotes");
frame.setSize(500, 500);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
cButton.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent ae) {
try{
MainProgram.main (new String[]);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void main (String [] args)
{
new GUI();
}
}
Remember to call
frame.pack();
frame.setVisible(true);
or your JFrame will not be shown.
As for the ActionListener code, you've to add [0] for the String Array dimension such as:
cButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
MainProgram.main(new String[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
});