Open file from table JavaFX [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have problem with opening file from table in my JavaFX app. When user click on the row, new window should open because in the table I have path to specialty file for example:
1 document C:/Users/document.docx
After user click on this row new office window will open. Below I add my code:
private void configureTableClick() {
TableView<String[]> contentTable = contentPaneController.getContentTable();
contentTable.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseEvent -> {
if (mouseEvent.getClickCount() == 1) {
int selectedIndex = contentTable.getSelectionModel().getSelectedIndex();
String fileToOpen;
if (selectedIndex > 0) {
try {
Desktop.getDesktop().open(new File(fileToOpen));
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
});
}

Note that class Desktop belongs to AWT and according to this other stackoverflow question – Is it OK to use AWT with JavaFx? – it is not recommended to mix the two. There is also an open bug: JDK-8240572
I propose two alternatives.
If you want to use JavaFX then launch the file using class ProcessBuilder rather than class Desktop. Here is sample code. (Note that I am on Windows 10.)
import java.io.IOException;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.SelectionModel;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableTst extends Application {
private TableView<FileObj> table;
#Override
public void start(Stage primaryStage) throws Exception {
FileObj row = new FileObj(1, "document", "C:/Users/document.docx");
ObservableList<FileObj> items = FXCollections.observableArrayList(row);
table = new TableView<>(items);
TableColumn<FileObj, Number> indexColumn = new TableColumn<>("Index");
indexColumn.setCellValueFactory(param -> param.getValue().indexProperty());
table.getColumns().add(indexColumn);
TableColumn<FileObj, String> typeColumn = new TableColumn<>("Type");
typeColumn.setCellValueFactory(param -> param.getValue().fileTypeProperty());
table.getColumns().add(typeColumn);
TableColumn<FileObj, String> pathColumn = new TableColumn<>("Path");
pathColumn.setCellValueFactory(param -> param.getValue().filePathProperty());
table.getColumns().add(pathColumn);
SelectionModel<FileObj> tableSelectionModel = table.getSelectionModel();
tableSelectionModel.selectedItemProperty().addListener(this::handleTableSelection);
BorderPane root = new BorderPane(table);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
private void handleTableSelection(ObservableValue<? extends FileObj> property,
FileObj oldValue,
FileObj newValue) {
if (newValue != null) {
String path = newValue.getFilePath();
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", path);
try {
Process p = pb.start();
p.waitFor();
}
catch (InterruptedException | IOException x) {
x.printStackTrace();
}
}
}
public static void main(String[] args) {
launch(args);
}
}
class FileObj {
private SimpleIntegerProperty index;
private SimpleStringProperty fileType;
private SimpleStringProperty filePath;
public FileObj(int ndx, String type, String path) {
index = new SimpleIntegerProperty(this, "index", ndx);
fileType = new SimpleStringProperty(this, "fileType", type);
filePath = new SimpleStringProperty(this, "filePath", path);
}
public int getIndex() {
return index.get();
}
public SimpleIntegerProperty indexProperty() {
return index;
}
public String getFileType() {
return fileType.get();
}
public SimpleStringProperty fileTypeProperty() {
return fileType;
}
public String getFilePath() {
return filePath.get();
}
public SimpleStringProperty filePathProperty() {
return filePath;
}
}
AWT can be used with Swing so you can use class Desktop if you are willing to use Swing rather than JavaFX. Here is sample code.
import java.awt.Desktop;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
public class TesTable {
private JFrame frame;
private JTable table;
private JScrollPane createTable() {
String[] columns = new String[]{"Index", "Type", "Path"};
String[][] data = new String[][]{{"1", "document", "C:/Users/document.docx"}};
table = new JTable(data, columns);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getSelectionModel().addListSelectionListener(this::handleTableSelection);
JScrollPane scrollPane = new JScrollPane(table);
return scrollPane;
}
private void showGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTable());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void handleTableSelection(ListSelectionEvent event) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
int ndx = event.getFirstIndex();
if (ndx >= 0) {
String path = (String) table.getValueAt(ndx, 2);
File f = new File(path);
try {
desktop.open(f);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
}
public static void main(String[] args) {
final TesTable instance = new TesTable();
EventQueue.invokeLater(() -> instance.showGui());
}
}
Note that both the above code samples use method references.

Related

JavaFX ContextMenu items not displaying changes during runtime

So I am writing an AutosuggestMenu that adds a listener to a TextField and recommends suggestions in a popup ContextMenu, based on comparing the keystrokes entered with the Collection of words provided.
Unfortunately, changes to the ContextMenu elements are not displayed, and I suspect this is because I am modifying the elements of the ObservableList associated with the ContextMenu and not the list itself.
Browsing stack has led to believe I should implement an extractor, but based on the examples provided I have no idea how to do this for my specific problem. Any solution would be very much appreciated!
Source:
package com.sknb.gui;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javafx.geometry.Side;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
public class AutosuggestMenu {
public final static int DEFAULT_MENU_SIZE = 10;
//Data members
private int menuSize;
private Collection<String> wordList;
//GUI members
private ContextMenu menu;
private final Text textBefore, textMatching, textAfter;
public AutosuggestMenu(Collection<String> keyList) {
this(keyList, DEFAULT_MENU_SIZE);
}
public AutosuggestMenu(Collection<String> keyList, int numEntries) {
if (keyList == null) {
throw new NullPointerException();
}
this.wordList = keyList;
this.menuSize = numEntries;
this.menu = new ContextMenu();
for (int i = 0; i < this.menuSize; i++) {
CustomMenuItem item = new CustomMenuItem(new Label(), true);
this.menu.getItems().add(item);
}
this.textBefore = new Text();
this.textMatching = new Text();
this.textAfter = new Text();
}
public void addListener(TextField field) {
field.textProperty().addListener((observable, oldValue, newValue) -> {
String enteredText = field.getText();
if (enteredText == null || enteredText.isEmpty()) {
this.menu.hide();
} else {
List<String> filteredEntries = this.wordList.stream()
.filter(e -> e.contains(enteredText))
.collect(Collectors.toList());
if (!filteredEntries.isEmpty()) {
populatePopup(field, filteredEntries, enteredText);
if (!(this.menu.isShowing())) {
this.menu.show(field, Side.BOTTOM, 0, 0);
}
} else {
this.menu.hide();
}
}
});
field.focusedProperty().addListener((observableValue, oldValue, newValue) -> {
this.menu.hide();
});
}
private void populatePopup(TextField field, List<String> matches, String query) {
int i = 0,
max = (matches.size() > this.menuSize) ? this.menuSize :
matches.size();
for (MenuItem item : this.menu.getItems()) {
if (i < max) {
String result = matches.get(i);
item.setGraphic(generateTextFlow(result, query));
item.setVisible(true);
item.setOnAction(actionEvent -> {
field.setText(result);
field.positionCaret(result.length());
this.menu.hide();
});
} else {
item.setVisible(false);
}
i++;
}
}
private TextFlow generateTextFlow(String text, String filter) {
int filterIndex = text.indexOf(filter);
this.textBefore.setText(text.substring(0, filterIndex));
this.textAfter.setText(text.substring(filterIndex + filter.length()));
this.textMatching.setText(text.substring(filterIndex, filterIndex + filter.length()));
textMatching.setFill(Color.BLUE);
textMatching.setFont(Font.font("Helvetica", FontWeight.BOLD, 12));
return new TextFlow(textBefore, textMatching, textAfter);
}
public int getMenuSize() {
return this.menuSize;
}
public void setMenuSize(int size) {
this.menuSize = size;
}
public Collection<String> getKeyList() {
return this.wordList;
}
public void setKeyList(Collection<String> keyList) {
this.wordList = keyList;
}
//To do: add ways to change style of ContextMenu/menu items/text elements
}
Test class using a text file of English words as a dictionary:
package autosuggestfieldtest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import com.sknb.gui.AutosuggestMenu;
public class AutosuggestFieldTest extends Application {
private TextField textfield;
private Collection<String> words;
private AutosuggestMenu popup;
#Override
public void start(Stage primaryStage) {
String filename = Paths.get("").toAbsolutePath().toString() + "\\words.txt";
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
words = stream
.collect(Collectors.toSet());
} catch (IOException e) {
System.out.println("DERP");
}
popup = new AutosuggestMenu(words);
textfield = new TextField();
popup.addListener(textfield);
StackPane root = new StackPane();
root.getChildren().add(textfield);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("AutocompleteField Test");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Note: this is a modification of a similar solution by Ruslan, but I was wondering if there is a solution that does not involve clearing/repopulating the menu with every keystroke? I.e. just using the setGraphic and refreshing the ContextMenu?

How do I clone a JavaFX TableView?

I have a JavaFX application whose main job is to display different tables containing data loaded from CSV files. I can read CSV files into TableViews with no problems, and export them to CSVs as well. My problem is displaying the different TableViews.
When I load from a CSV into a TableView, I want to save that TableView for future processing. I also want to display a table showing the newly loaded data. My strategy is to have a global TableView, call it table, that is added to the main VBox, and update its contents to contain (and hence display) the elements of whichever TableView I just created by reading a file.
Is this a bad idea? It seems like a simple concept to me, but I can't find a way to easily "clone" the chosen TableView - i.e. transfer its contents to my displayed TableView called table.
My simple attempt at cloning TableViews is shown here. I also tried writing an extensive equateTable() method, which went nowhere.
//WHY DOESN'T THIS WORK?
table.setItems(reqTable.getItems());
Here's the rest of the code. Thanks to anyone who answers!
package FLOOR;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Callback;
// --- Main Class
public class Main extends Application {
// --- All Tables
TableView<ObservableList<StringProperty>> reqTable = new TableView<>();
TableView<ObservableList<StringProperty>> tempTable = new TableView<>();
TableView<ObservableList<StringProperty>> ontTable = new TableView<>();
// --- Display Table
TableView<ObservableList<StringProperty>> table = new TableView<>();
// --- Main
public static void main(String[] args) {
launch(args);
}
// --- Start
#Override
public void start(Stage stage) {
// --- Stage & Scene
stage.setTitle("FLOOR");
Scene scene = new Scene(new VBox(), 900, 500);
MenuBar menuBar = new MenuBar();
// --- VBox
final VBox vbox = new VBox();
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.setPadding(new Insets(0, 10, 0, 10));
vbox.getChildren().addAll(table);
table.setVisible(false);
// --- Menus
// --- File Menu
// --- Import Submenu
Menu menuFile = new Menu("File");
Menu importMenu = new Menu("Import");
MenuItem reqOption = new MenuItem("Requirements");
MenuItem tempOption = new MenuItem("Templates");
MenuItem ontOption = new MenuItem("Ontologies");
importMenu.getItems().addAll(reqOption, tempOption, ontOption);
//Import Requirements
reqOption.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Requirements CSV");
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
populateTable(reqTable, file.getAbsolutePath());
}
getRequirementsPage();
}
});
//Import Templates
tempOption.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Templates CSV");
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
populateTable(tempTable, file.getAbsolutePath());
}
getTemplatesPage();
}
});
//Import Ontologies
ontOption.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Ontology CSV");
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
populateTable(ontTable, file.getAbsolutePath());
}
getOntologiesPage();
}
});
//Export
MenuItem export = new MenuItem("Export");
export.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Requirements CSV");
File file = fileChooser.showSaveDialog(stage);
if (file != null) {
exportTable(reqTable, file.getAbsolutePath());
}
}
});
//Exit
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
System.exit(0);
}
});
menuFile.getItems().addAll(importMenu, export, new SeparatorMenuItem(), exit);
// --- Menu Bar
menuBar.getMenus().addAll(menuFile);
// --- Show FLOOR
((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);
stage.setScene(scene);
stage.show();
}
// --- Methods
// Table Getters
private void getRequirementsPage() {
table.getItems().clear();
//WHY DOESN'T THIS WORK?
table.setItems(reqTable.getItems());
table.setVisible(true);
}
private void getTemplatesPage() {
table.getItems().clear();
table.setItems(tempTable.getItems());
table.setVisible(true);
}
private void getOntologiesPage() {
table.getItems().clear();
table.setItems(ontTable.getItems());
table.setVisible(true);
}
//populateTable
private void populateTable(
final TableView<ObservableList<StringProperty>> table,
final String filename) {
table.getItems().clear();
table.getColumns().clear();
table.setPlaceholder(new Label("Loading..."));
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
CSVReader reader = new CSVReader(new FileReader(filename));
String [] nextLine;
int count = 1;
while ((nextLine = reader.readNext()) != null) {
if (count == 1) {
final String[] headers = nextLine;
Platform.runLater(new Runnable() {
#Override
public void run() {
for (int column = 0; column < headers.length; column++) {
table.getColumns().add(
createColumn(column, headers[column]));
}
}
});
} else {
final String[] dataValues = nextLine;
Platform.runLater(new Runnable() {
#Override
public void run() {
// Add additional columns if necessary:
for (int columnIndex = table.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
table.getColumns().add(createColumn(columnIndex, ""));
}
// Add data to table:
ObservableList<StringProperty> data = FXCollections
.observableArrayList();
for (String value : dataValues) {
data.add(new SimpleStringProperty(value));
}
table.getItems().add(data);
}
});
}
count++;
}
reader.close();
return null;
}
};
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
//exportTable
private void exportTable(
final TableView<ObservableList<StringProperty>> table,
final String filename) {
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(filename), ',');
} catch (IOException e) {
e.printStackTrace();
}
int numRows = table.getItems().size();
int numCols = table.getColumns().size();
String[] dataWrite = new String[numCols];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
dataWrite[j] = table.getItems().get(i).get(j).getValue();
}
writer.writeNext(dataWrite);
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
//createColumn
private TableColumn<ObservableList<StringProperty>, String> createColumn(
final int columnIndex, String columnTitle) {
TableColumn<ObservableList<StringProperty>, String> column = new TableColumn<>();
String title;
if (columnTitle == null || columnTitle.trim().length() == 0) {
title = "Column " + (columnIndex + 1);
} else {
title = columnTitle;
}
column.setText(title);
column
.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<StringProperty>, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(
CellDataFeatures<ObservableList<StringProperty>, String> cellDataFeatures) {
ObservableList<StringProperty> values = cellDataFeatures.getValue();
if (columnIndex >= values.size()) {
return new SimpleStringProperty("");
} else {
return cellDataFeatures.getValue().get(columnIndex);
}
}
});
return column;
}
}

Applet is invisible in JavaFX application

I am in the process of converting my GUI from Swing to JavaFX (so I can add custom styling things more easily).
I had my application working in Swing but I cannot get it to work in JavaFX.
What I want is to load an external applet into a SwingNode. The applet has music that automatically plays and I can hear it but I cannot see anything.
I'm struggling to find any relevant documentation or help on this.
My Code:
ClientNew.java
package rsclient.coregui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.concurrent.ExecutionException;
import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.stage.Stage;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import rsloader.Loader;
public class ClientNew extends Application {
#Override
public void start(Stage stage) throws InterruptedException, ExecutionException {
SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final Loader loader = new Loader(Loader.Game.OSRS);
loader.applet.setLayout(null);
loader.applet.resize(800, 550);
JPanel gamepanel = new JPanel(new BorderLayout());
gamepanel.add(loader.applet, BorderLayout.CENTER);
swingNode.setContent(gamepanel);
gamepanel.setVisible(true);
}
});
Tab tab = new Tab();
tab.setText("My Tab");
tab.setClosable(false);
tab.setContent(swingNode);
TabP ane tabPane = new TabPane();
tabPane.getStyleClass().add("tabbedPane");
tabPane.getTabs().add(tab);
stage.setScene(
new Scene(
tabPane,
1000, 650
)
);
stage.setTitle("My APplication");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Loader.java (not my code but it seems to work. Will of course refactor later)
package rsloader;
import java.applet.Applet;
import java.applet.AppletContext;
import java.applet.AppletStub;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rsreflection.Reflector;
/***
*#author Xel
*#version 1.0
*#project RSLoader
*#file Loader.java
*#date 18.10.2013
*#time 10.43.48
*/
public class Loader implements AppletStub{
//insane declarations
public enum Game{OSRS, RS3, CLASSIC};
public static final HashMap<String, String> Parameters = new HashMap<String, String>();
public Game game;
public URL GamePack;
public Applet applet;
public String gameUrl;
public String MClass;
public Reflector loader;
public Loader(Game g)
{
game = g;
if(game == Game.OSRS)
gameUrl = "http://oldschool69.runescape.com/";
else if(game == Game.RS3)
gameUrl = "http://world1.runescape.com/";
else
gameUrl = "http://classic2.runescape.com/plugin.js?param=o0,a0,s0";
try {
GetParams(new URL(gameUrl));
loader = new Reflector(new URL[]{GamePack});
applet = (Applet)loader.loadClass(MClass).newInstance();
applet.setStub(this);
applet.init();
applet.start();
} catch (IOException | InstantiationException | IllegalAccessException | ClassNotFoundException e1) {
e1.printStackTrace();
}
}
public void GetParams(URL url) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
List<String> params = new ArrayList<String>();
while((line = reader.readLine()) != null)
{
if(line.contains("param name"))
params.add(line);
if(GamePack == null) //retarted block
if(line.contains("archive"))
if(game != Game.CLASSIC)
GamePack = new URL(gameUrl + line.substring(line.indexOf("archive=") + 8, line.indexOf(" ');")));
else
GamePack = new URL("http://classic2.runescape.com/" + line.substring(line.indexOf("archive=") + 8, line.indexOf(" code")));
if(MClass == null)
if(line.contains("code="))
MClass = line.substring(line.indexOf("code=") + 5, line.indexOf(".class"));
}
reader.close();
for(String s : params)
{
Parameters.put(GetParamName(s), GetParamValue(s));
}
}
public String GetParamName(String param)
{
try{
int StartIndex = param.indexOf("<param name=\"") + 13;
int EndIndex = param.indexOf("\" value");
return param.substring(StartIndex, EndIndex);
}catch(StringIndexOutOfBoundsException e)//classic handles some differently so why not just catch it =P
{
int StartIndex = param.indexOf("<param name=") + 12;
int EndIndex = param.indexOf(" value");
return param.substring(StartIndex, EndIndex);
}
}
public String GetParamValue(String param)
{
try{
int StartIndex = param.indexOf("value=\"") + 7;
int EndIndex = param.indexOf("\">');");
return param.substring(StartIndex, EndIndex);
}catch(StringIndexOutOfBoundsException e)//and again :D
{
int StartIndex = param.indexOf("value=") + 6;
int EndIndex = param.indexOf(">');");
return param.substring(StartIndex, EndIndex);
}
}
#Override
public void appletResize(int arg0, int arg1) {
}
#Override
public AppletContext getAppletContext() {
return null;
}
#Override
public URL getCodeBase() {
try
{
if(game == Game.OSRS)
return new URL("http://oldschool1.runescape.com/");
else if(game == Game.RS3)
return new URL("http://world1.runescape.com/");
else
return new URL("http://classic2.runescape.com/");
}catch(MalformedURLException e)
{
e.printStackTrace();
}
return null;
}
#Override
public URL getDocumentBase() {
try
{
if(game == Game.OSRS)
return new URL("http://oldschool1.runescape.com/");
else if(game == Game.RS3)
return new URL("http://world1.runescape.com/");
else
return new URL("http://classic2.runescape.com/");
}catch(MalformedURLException e)
{
e.printStackTrace();
}
return null;
}
#Override
public String getParameter(String arg0) {
return Parameters.get(arg0);
}
#Override
public boolean isActive() {
return false;
}
}
To ANYONE who is coming upon this question for rendering applets with JavaFX
Swing DOES NOT support the rendering of Heavyweight components.
There is still, and has not been any support for heavyweight components, which obviously sucks for people looking to render heavyweight games or applications with javafx.
I also was trying to implement a swing applet into JavaFX. I could not see the app. After getting the size of the root pane I saw that it's Dimension was 0,0. The applet doesn't autosize with JavaFX. I added the following line to my init method in the JApplet.
this.getRootPane().setMinimumSize(new Dimension(900,600));
This allowed me to set the size of the applet. I am working on implementing a listener so that it will size with the window.

run as .jar results in a different view

I write a programm which shows a waveform by using an Areachart.When i compile it and run it it looks just fine like below.When i execute the .jar file i get a complete different view of my waveform.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.AnimationTimer;
import javafx.animation.Timeline;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.stage.Stage;
public class AreaChartSample extends Application {
private static final int MAX_DATA_POINTS = 500;
private Series series;
private int xSeriesData = 0;
private ConcurrentLinkedQueue<Number> dataQ = new ConcurrentLinkedQueue<>();
private ExecutorService executor;
private AddToQueue addToQueue;
private Timeline timeline2;
private NumberAxis xAxis;
private int time_counter=0;
private int [] data_array=null;
private void init(Stage primaryStage) {
String line,full_text="";
try {
BufferedReader in = new BufferedReader(new FileReader("C:/testvideo/test.txt"));
while((line=in.readLine())!= null)
{
full_text+=line;
}
data_array=new int[full_text.length()];
for(int i=0;i<full_text.length();i++)
{
data_array[i]=((int)(full_text.charAt(i)))-127;
// data_array[i]=((int)(full_text.charAt(i)))-300;
}
} catch (Exception e) {
}
xAxis = new NumberAxis(0,MAX_DATA_POINTS,MAX_DATA_POINTS/10);
xAxis.setForceZeroInRange(false);
xAxis.setAutoRanging(false);
NumberAxis yAxis = new NumberAxis(-127,127,1);
yAxis.setAutoRanging(false);
//-- Chart
final AreaChart<Number, Number> sc = new AreaChart<Number, Number>(xAxis, yAxis) {
// Override to remove symbols on each data point
#Override protected void dataItemAdded(Series<Number, Number> series, int itemIndex, Data<Number, Number> item) {}
};
sc.setAnimated(false);
sc.setId("liveAreaChart");
sc.setTitle("Animated Area Chart");
//-- Chart Series
series = new AreaChart.Series<Number, Number>();
series.setName("Area Chart Series");
sc.getData().add(series);
primaryStage.setScene(new Scene(sc));
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
//-- Prepare Executor Services
executor = Executors.newCachedThreadPool();
addToQueue = new AddToQueue();
executor.execute(addToQueue);
//-- Prepare Timeline
prepareTimeline();
primaryStage.setOnCloseRequest(e -> {
executor.shutdown();
});
}
public static void main(String[] args) {
launch(args);
}
private class AddToQueue implements Runnable {
public void run() {
try {
// add a item of random data to queue
dataQ.add(data_array[time_counter]);
time_counter+=100;
Thread.sleep(10);
executor.execute(this);
} catch (InterruptedException ex) {
Logger.getLogger(AreaChartSample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//-- Timeline gets called in the JavaFX Main thread
private void prepareTimeline() {
// Every frame to take any data from queue and add to chart
new AnimationTimer() {
#Override public void handle(long now) {
addDataToSeries();
}
}.start();
}
private void addDataToSeries() {
for (int i = 0; i < 20; i++) { //-- add 20 numbers to the plot+
if (dataQ.isEmpty()) break;
Number y=dataQ.remove();
series.getData().add(new AreaChart.Data(xSeriesData++, y));
// System.out.println(y);
}
// remove points to keep us at no more than MAX_DATA_POINTS
if (series.getData().size() > MAX_DATA_POINTS) {
series.getData().remove(0, series.getData().size() - MAX_DATA_POINTS);
}
// update
xAxis.setLowerBound(xSeriesData-MAX_DATA_POINTS);
xAxis.setUpperBound(xSeriesData-1);
}
}
when i just run it =>
when i execute the build .jar file (windows 7 64 bit -> java8)
I have absolute no idea why this can happen.
Update: here is test.txt: http://expirebox.com/download/bf9be466e23c4c3d8f73f094f261dfbe.html
UPDATE2
Okay it must have to do with the reading of the file.when i change
data_array[i]=((int)(full_text.charAt(i)))-127;
to
data_array[i]=data_array[i]=((int)('f'))-127;
it is the same in both "versions".
Is there are another method which could read correct in both ways.Maybe it has to do with UTF8 or so?
This did the trick. Thank you!
String fileName = "C:/testvideo/test.txt";
FileInputStream is = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader in = new BufferedReader(isr);

SwingWorker ProgressBar

I am trying to get a progress bar to accurately reflect my SwingWorker. But I really can't figure out how to do it. I got the bar to just do a static animation until the operation has completed but I want a real active bar.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package frglauncher;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
/**
*
* #author KYLE-LAPTOP
*/
class DownloadWorker extends SwingWorker<String, Object> {
private String game;
private JProgressBar bar;
private JLabel label;
public DownloadWorker(JProgressBar bar, String game, JLabel label) {
this.game = game;
this.bar = bar;
this.label = label;
}
#Override
public String doInBackground() {
// Download here
label.setText("test");
try {
// ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.jar";
String LOCAL_FILE = ("\\" + game + "\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists()) {
System.out.println("Directory created!");
}
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE + "\\ProfessorPhys.jar\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
File file = new File(LOCAL_FILE + "ProfessorPhys.jar\\");
JarFile jar = new JarFile(file);
Enumeration enum1 = jar.entries();
while (enum1.hasMoreElements()) {
JarEntry file1 = (JarEntry) enum1.nextElement();
System.out.println("Directory to extract: " + LOCAL_FILE);
System.out.println("\n" + file1.getName() + "\n");
File f = new File(file1.getName());
if (file1.isDirectory()) { // If it's a directory, create it
f.mkdir();
continue;
}
try (InputStream is1 = jar.getInputStream(file1)) {
FileOutputStream fos1 = new FileOutputStream(f);
while (is1.available() > 0) { // Write contents of 'is' to 'fos'
fos1.write(is1.read());
}
fos1.close();
}
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(DownloadWorker.class.getName()).log(Level.SEVERE, null, ex);
}
catch (MalformedURLException ex) {
Logger.getLogger(DownloadWorker.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(DownloadWorker.class.getName()).log(Level.SEVERE, null, ex);
}
return "done";
}
#Override
protected void done() {
// Done
label.setText("Download of " + game + "is done.");
System.exit(0);
}
}
Several things:
There are four rules to follow with SwingWorker. You can refer to this diagram: .
So, this code:
#Override
public String doInBackground() {
//download here
label.setText("test");
violates that rule. Your label.setText() should be moved to the constructor.
To send "updates" to Swing components (like your progress bar) you want to use the process() method, which you invoke using publish() from inside your doInBackground(). Your second SwingWorker parameter reflects the type of value you want to pass. I've attached two SSCCEs. One passes an Integer to the process() method, the other passes a String. Should give you an idea of what's going on.
SSCCE using Integer:
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/**
*
* #author Ryan
*/
public class Test {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
go();
}
});
}
public static void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("Loading...");
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(false);
int max = 1000;
jpb.setMaximum(max);
panel.add(label);
panel.add(jpb);
frame.add(panel);
frame.pack();
frame.setSize(200,90);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Task_IntegerUpdate(jpb, max, label).execute();
}
static class Task_IntegerUpdate extends SwingWorker<Void, Integer> {
JProgressBar jpb;
int max;
JLabel label;
public Task_IntegerUpdate(JProgressBar jpb, int max, JLabel label) {
this.jpb = jpb;
this.max = max;
this.label = label;
}
#Override
protected void process(List<Integer> chunks) {
int i = chunks.get(chunks.size()-1);
jpb.setValue(i); // The last value in this array is all we care about.
System.out.println(i);
label.setText("Loading " + i + " of " + max);
}
#Override
protected Void doInBackground() throws Exception {
for(int i = 0; i < max; i++) {
Thread.sleep(10); // Illustrating long-running code.
publish(i);
}
return null;
}
#Override
protected void done() {
try {
get();
JOptionPane.showMessageDialog(jpb.getParent(), "Success", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
SSCCE using String:
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/**
*
* #author Ryan
*/
public class Test2 {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
go();
}
});
}
public static void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("Loading...");
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(true);
panel.add(label);
panel.add(jpb);
frame.add(panel);
frame.pack();
frame.setSize(200,90);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Task_StringUpdate(label).execute();
}
static class Task_StringUpdate extends SwingWorker<Void, String> {
JLabel jlabel;
public Task_StringUpdate(JLabel jlabel) {
this.jlabel = jlabel;
}
#Override
protected void process(List<String> chunks) {
jlabel.setText(chunks.get(chunks.size()-1)); // The last value in this array is all we care about.
System.out.println(chunks.get(chunks.size()-1));
}
#Override
protected Void doInBackground() throws Exception {
publish("Loading Step 1...");
Thread.sleep(1000);
publish("Loading Step 2...");
Thread.sleep(1000);
publish("Loading Step 3...");
Thread.sleep(1000);
publish("Loading Step 4...");
Thread.sleep(1000);
return null;
}
#Override
protected void done() {
try {
get();
JOptionPane.showMessageDialog(jlabel.getParent(), "Success", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
}
}

Categories