JavaFX How can i save file with tabs? - select

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);
}
}

Related

Image from clipboard not correctly displayed in JavaFX 8 application

This program shall paste an image from clipboard into an ImageView (on Windows 10). Unfortunately the image is not correctly displayed.
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Clipboard cb = Clipboard.getSystemClipboard();
if (cb.hasImage()) {
Image image = cb.getImage();
imageView.setImage(image);
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
}
Steps to reproduce:
Start cmd.exe
Press ALT-Print to copy the cmd window into the clipboard
Start program PasteImageFromClipboard
Press "Paste" button in PasteImageFromClipboard
This result is displayed on my computer:
It should be like this:
Is there more code required to draw the image correctly?
found this solution by the help of
https://community.oracle.com/thread/2238566
package com.wilutions.jiraddin;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
java.awt.Image image = getImageFromClipboard();
if (image != null) {
javafx.scene.image.Image fimage = awtImageToFX(image);
imageView.setImage(fimage);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
private java.awt.Image getImageFromClipboard() {
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
try {
return (java.awt.Image) transferable.getTransferData(DataFlavor.imageFlavor);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private static javafx.scene.image.Image awtImageToFX(java.awt.Image image) throws Exception {
if (!(image instanceof RenderedImage)) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = bufferedImage;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write((RenderedImage) image, "png", out);
out.flush();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
return new javafx.scene.image.Image(in);
}
}

How to set a web page while clicking on a button ? with JavaFX

i'm trying to get an URL from TextField exapmle: http://www.google.com and i have a WebViewthat it will be visible by clicking on the "Enter key" but the problem is when i run the application it didn't show anything note that i'm using FXML File.This is the code i've traied:
#FXML
private void onpressed (ActionEvent ee) {
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent evt) {
if (evt.getCode() == KeyCode.ENTER){
String az = text1.getText();
//c.1
if(text1.getText().equals("1")){
web1.setVisible(true);
String hh = text11.getText();
Socket socket = new Socket();
try {
//open cursor
text1.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
writ.setCursor(Cursor.WAIT);
ancpa.setCursor(Cursor.WAIT);
web1.setCursor(Cursor.WAIT);
web2.setCursor(Cursor.WAIT);
web3.setCursor(Cursor.WAIT);
web4.setCursor(Cursor.WAIT);
web5.setCursor(Cursor.WAIT);
web6.setCursor(Cursor.WAIT);
web7.setCursor(Cursor.WAIT);
web8.setCursor(Cursor.WAIT);
web9.setCursor(Cursor.WAIT);
//do work
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load("http://www.google.com");
//close the window chooser
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//close cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
}
catch (IOException e){
final Stage stg = new Stage();
stg.initModality(Modality.APPLICATION_MODAL);
stg.initOwner(stg);
stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
labelno.setText("Cannot connect to the internet...");
//close chooser
Stage stage = new Stage();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
}
}
});
}
So please can any body explain for me where is the problem for this code and i'll be so thankful :)
Here is a simple example application that goes to the web page you typed in when you press enter in the text field:
package application;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage stage) throws Exception {
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
final TextField text1 = new TextField();
WebView web = new WebView();
final WebEngine webEngine= web.getEngine();
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
if (ke.getCode().toString().equalsIgnoreCase("ENTER")) {
String urlString = text1.getText().trim();
webEngine.load(urlString);
}
}
});
pane.getChildren().addAll(web,text1);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch("application.Main");
}
}
You can try typing in https://www.google.com and it should take you there
If you exclude the http or https it should not work
Depending on your jre you may need to remove the #Override
I hope this helps
I am not really sure if you want 'if(text1.getText().equals("1")){' the if statement will only be true if someone types in the character "1" but how you set the web engine is by getting the text from the text field (text1) and getting the web engine to load it and it is good practice to put a .trim() at the end incase the user accidentally types in a space at the beginning of the end.
So your code should look something like this:
String urlString = text1.getText().trim();
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load(urlString);
And you complet code should look something like this:
#FXML
private void onpressed (ActionEvent ee) {
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent evt) {
if (evt.getCode() == KeyCode.ENTER){
String az = text1.getText();
web1.setVisible(true);
String hh = text11.getText();
Socket socket = new Socket();
try {
//open cursor
text1.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
writ.setCursor(Cursor.WAIT);
ancpa.setCursor(Cursor.WAIT);
web1.setCursor(Cursor.WAIT);
web2.setCursor(Cursor.WAIT);
web3.setCursor(Cursor.WAIT);
web4.setCursor(Cursor.WAIT);
web5.setCursor(Cursor.WAIT);
web6.setCursor(Cursor.WAIT);
web7.setCursor(Cursor.WAIT);
web8.setCursor(Cursor.WAIT);
web9.setCursor(Cursor.WAIT);
String urlString = text1.getText().trim();
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load(urlString);
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//close cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
}
catch (IOException e){
final Stage stg = new Stage();
stg.initModality(Modality.APPLICATION_MODAL);
stg.initOwner(stg);
stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
labelno.setText("Cannot connect to the internet...");
//close chooser
Stage stage = new Stage();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
}
}
});
}
I hope this helps. If you have any questions just ask.

GWT RPC - Why the results from database are printed twice ?

I am writing a simple app to enter a user into database & display list of users using GWT RPC, Hibernate in Eclipse. The problem I am getting is that the list of users is printed twice.
Here is my code where I call insert user & display users list methods.
package rpctest.client;
import java.util.ArrayList;
import rpctest.shared.User;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
//final Label label1 = new Label("First Name");
//final Label label2 = new Label("Last Name");
private FlexTable userFlexTable = new FlexTable();
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync callService = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
userFlexTable.setText(0, 0, "User ID");
userFlexTable.setText(0, 1, "First Name");
userFlexTable.setText(0, 2, "Second Name");
userFlexTable.setText(0, 3, "Remove");
//add input boxes to panel
addpanel1.add(firstName);
addpanel1.add(lastName);
firstName.setFocus(true);
//add input/result panels
mainpanel.add(userFlexTable);
mainpanel.add(addpanel1);
addpanel1.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
addStock();
}
});
lastName.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
addStock();
}
}
});
RootPanel.get().add(mainpanel);
getUser();
}
private void addStock(){
String name1 = firstName.getValue();
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
/*if (!name1.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
firstName.selectAll();
return;
}*/
firstName.setValue("");
String name2 = lastName.getValue();
/*if (!name2.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
lastName.selectAll();
return;
}*/
lastName.setValue("");
firstName.setFocus(true);
callService.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
// Add the user to the table.
// int row = userFlexTable.getRowCount();
// userFlexTable.setText(row, 1, result);
getUser();
}
});
}
private void getUser(){
callService.getUser(new AsyncCallback<User[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("Problem in database connection");
}
#Override
public void onSuccess(User[] result) {
// TODO Auto-generated method stub
for(int i = 0; i < result.length; i ++)
{
//String s = result[i].getFirstName();
int row = userFlexTable.getRowCount();
userFlexTable.setText(row, 0, result[i].getId().toString());
userFlexTable.setText(row, 1, result[i].getFirstName());
userFlexTable.setText(row, 2, result[i].getLastName());
}
}
});
}
}
Man did you notice that you are calling getUser twice if the entered Name is valid and the call to the service is successfull??
You have to remove one of them!
getUser is called on every new entry & all data is entered again into table.

composite within a composite

Does anybody know how or if you can place a smaller composite inside a larger composite.
For example I want the smaller composite to be in the centre of the large composite and visible and when a button is pressed in the larger composite a picture appears in the smaller composite?
Would be extremely glad of your help.
Ann.
I'm not sure if I understand your question, you meant something like this..?
import java.net.URL;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class CompositeInComposite {
private Display display = null;
private Shell shell = null;
private Composite composite = null;
private Image img = null;
private URL dog = null;
private URL cat = null;
public CompositeInComposite() {
display = new Display();
shell = new Shell(display);
shell.setLayout(new FillLayout(SWT.VERTICAL));
shell.setSize(300, 300);
Button btn = new Button(shell, SWT.PUSH);
btn.setText("show cat");
btn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
try {
img = new Image(display, cat.openStream());
composite.redraw();
} catch(Exception ex) {
ex.printStackTrace();
}
}
});
try {
cat = new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/6/64/Collage_of_Six_Cats-02.jpg/250px-Collage_of_Six_Cats-02.jpg");
dog = new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg");
img = new Image(display, dog.openStream());
} catch (Exception e) {
e.printStackTrace();
}
composite = new Composite(shell, SWT.BORDER);
composite.addPaintListener(new PaintListener() {
#Override
public void paintControl(PaintEvent e) {
e.gc.drawImage(img, 0, 0);
}
});
// shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static void main(String[] args) {
new CompositeInComposite();
}
}
The alignment of the button, it's size, etc. is just a proper configuration of layout manager, I would recommend MigLayout as IMO best layout manager that exists.

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();
}
}
});