I have created an application that runs fine but when made into a jar file the image doesn't show. I'm using JAVAFX for the GUI.
Part of the code
#FXML
private ImageView weatherIconId;
public void setLocation(){
WeatherToday wT = new WeatherToday();
File file = new File("src\\weatherIcons\\"+ wT.getIcon() + ".png");
Image image = new Image(file.toURI().toString());
try {
weatherIconId.setImage(image);
loc.setText(wT.getDescription().substring(0, 1).toUpperCase() + wT.getDescription().substring(1) + " " + wT.getCels());
}catch(Exception e){
loc.setText("Error News");
}
}
Image show in executable
Image not showing in JAR File
Full code for class
public class LabelController {
#FXML
private TextArea lblN;
#FXML
private Label lblTime;
#FXML
private Label loc;
#FXML
private Label trainUpdate;
#FXML
private Label monthDay;
#FXML
private Label TFLline;
#FXML
private Label BBCL;
#FXML
private ImageView weatherIconId;
static String i;
static int num;
public void getAndSetData(){
setTime();
setNews();
setLocation();
setTrainStatus();
}
public void setTime(){
try {
LocalTime watch = LocalTime.now();
DateTimeFormatter shortTime = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
i = shortTime.format(watch);
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM, dd");
String formatDate = now.format(formatter);
System.out.println("After : " + formatDate);
lblTime.setText(i);
monthDay.setText(formatDate);
}catch(Exception e){
lblTime.setText("Error T");
}
}
public void setNews(){
BBCL.setTextFill(Color.web("#ff270f"));
try {
String news = "";
for(String n: new News().getHeadLine()){
news += "- " + n + "\n";
}
//Scroll bar in the textArea
ScrollBar scrollBarv = (ScrollBar)lblN.lookup(".scroll-bar:vertical");
//Hide scrollbar
scrollBarv.setDisable(true);
lblN.setWrapText(true);
//New information.
lblN.setText(news);
lblN.appendText("\n"+ "\n"+ "\n"+ "\n");
//Automatic scrolling function
slowScrollToBottom(scrollBarv);
}catch(Exception e){
lblN.setText("Error News");
}
}
static void slowScrollToBottom(ScrollBar scrollPane) {
scrollPane.setValue(1.5);
Animation animation = new Timeline(
new KeyFrame(Duration.seconds(7),
new KeyValue(scrollPane.valueProperty(), 0)));
animation.play();
}
public void setLocation(){
WeatherToday wT = new WeatherToday();
File file = new File("src\\weatherIcons\\"+ wT.getIcon() + ".png");
Image image = new Image(file.toURI().toString());
try {
weatherIconId.setImage(image);
loc.setText(wT.getDescription().substring(0, 1).toUpperCase() + wT.getDescription().substring(1) + " " + wT.getCels());
}catch(Exception e){
loc.setText("Error News");
}
}
public void setTrainStatus(){
TFLStatus tS = new TFLStatus();
LocateMyCity lo = new LocateMyCity();
int sizeOfService = tS.getTFL().size();
int countGS = 0;
if(lo.getmyCityLocation().equalsIgnoreCase("London")) {
try {
for (Map.Entry<String, String> entry : tS.getTFL().entrySet()) {
//Line NOT equal to Good Service - Delay lines
if (!entry.getValue().equalsIgnoreCase("Good Service")) {
TFLline.setFont(new Font("Arial", 30));
TFLline.setStyle("-fx-font-weight: bold");
TFLline.setTextFill(Color.web("#ff270f"));
TFLline.setText("Services delays:");
trainUpdate.setFont(new Font("Arial", 32));
trainUpdate.setStyle("-fx-font-weight: bold");
trainUpdate.setTextFill(Color.web("#ffffff"));
trainUpdate.setText(entry.getKey() + ": " + entry.getValue() + "\n");
System.out.println("Name of Service: " + entry.getKey() + " " + entry.getValue() + "\n");
++countGS;
}
}
if (countGS == 0) {
TFLline.setFont(new Font("Arial", 35));
TFLline.setStyle("-fx-font-weight: bold");
TFLline.setTextFill(Color.web("#25d039"));
TFLline.setText("Good Services: Underground & DLR");
}
System.out.println(countGS);
//tS.getTFL().forEach((k,v)-> System.out.println(v));
} catch (Exception e) {
loc.setText("Error News");
}
}else{
TFLline.setText(lo.getmyCityLocation());
}
}
#FXML
public void initialize() {
Timeline timeline = new Timeline(new KeyFrame(
Duration.millis(8000),
ae -> getAndSetData()));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
// getAndSetTheCurrentTime();
// lblN.textProperty().bind(i);
}
}
You can try this to laod the image
private Image image1 =
new Image(this.getClass().getResourceAsStream("/src/weatherIcons/image1.png"));
First of all, change image patches from "src/image.jpg" to "/image.jpg" and load image with help of classloader getClass().gerResource("/image.jpg") because after building jar and move it to somewhere it does not able to see src folder and your images does not shown. If it does not work check presence of images in your jar (open it with winRar or 7z file managers) and see in classpath (folder with class files) they must be there.
I also faced this issue once, and I solved like this way:
I made a img folder that consists of images. I gave the path of image to button or label etc like this way.
Now I follow this directory structure to attach images.
buttonORLabel.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/image.jpg"))));
Related
I am trying to write this
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
onto my scores.txt file.
This is what I want the output in the scores.txt file to look like:
Write save here and then skip line
Write save here and then skip line (repeat again and again)
My Problem
Every time I press the save score button, it runs this code
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
which is good. But whenever I press the save score button again, the original line gets overwritten which I don't want to happen.
What I've Tried
I have tried \r\n and BufferedWriter and it doesn't match what I want the outcome to be.
My Code
HackerGUI.java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class HackerGUI extends JFrame
{
//jframe components
private JPanel rootPanel;
private JButton hack;
private JLabel time;
private JButton reset;
private JLabel description;
private JLabel title;
private JLabel gif;
private JTextField textField1;
private JButton saveScoresButton;
private JButton settingsButton;
private JButton placeholder;
//timer stuff
private final Timer timer; //create timer
private final long duration = 10000; //duration of time
private long startTime = -1; //start of the time
private int delay = 300; //delay of when the time starts
//hacker levels
private int count = 0;
public HackerGUI()
{
add(rootPanel); //add intellij windows builder form
setTitle("Hacker UI v8.4"); //set the title of the frame
try {
File myObj = new File("scores.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("Scores file already exists.");
}
} catch (IOException a) {
System.out.println("An error occurred.");
a.printStackTrace();
}
try {
File myObj = new File("settings.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("Settings file already exists.");
}
} catch (IOException a) {
System.out.println("An error occurred.");
a.printStackTrace();
}
timer = new Timer(20, new ActionListener() { //timer module
#Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) { //if time reaches 0, stop time so it doesn't go to negative int
startTime = System.currentTimeMillis(); //use system time
}
long now = System.currentTimeMillis(); //use system time
long clockTime = now - startTime;
if (clockTime >= duration) { //whenever clock reaches 0, run command under:
clockTime = duration;
timer.stop(); //stop the timer from going to the negatives
hack.setEnabled(false); //disables hack button as timer went to 0
reset.setEnabled(true); //enable reset button to play again
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss.SSS"); //format of time shown
time.setText(df.format(duration - clockTime)); //set time component to destination
}
});
timer.setInitialDelay(delay); //set the delay
hack.addActionListener(new ActionListener() { //play action listener, triggers when button is pressed
#Override
public void actionPerformed(ActionEvent e) {
count++; //count in positives and add
hack.setText("Hacker Level: " + count); //change int and label
if (!timer.isRunning()) { //when button pressed, start timer
startTime = -1; //int to when start
timer.start(); //start
}
}
});
reset.addActionListener(new ActionListener() { //reset action listener, triggers when button is pressed
#Override
public void actionPerformed(ActionEvent e) {
hack.setEnabled(true); //enable hack button to start a new game
reset.setEnabled(false); //disable reset button as it has been used
//old command line save score
String name = textField1.getText(); //get name string
System.out.println(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds."); //print other info
System.out.println(""); //print spacer
//old command line save score
count = count + -count; //count in positive integers
hack.setText("Hacker Level: " + -count); //reset level score
time.setText("00:10.000"); //reset time label
}
});
saveScoresButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
FileWriter myWriter = new FileWriter("scores.txt");
String name = textField1.getText(); //get name string
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.");
myWriter.close();
System.out.println("Successfully wrote to the score file.");
} catch (IOException b) {
System.out.println("An error occurred.");
b.printStackTrace();
}
}
});
settingsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO: put stuff here
}
});
//please don't delete! as this shows credits and help info
JOptionPane.showMessageDialog(rootPanel,
"Hacker UI v8.4 is created by _._#3324, thank you for downloading! What is Hacker UI v8.4? It is a clicker game! To know more, read the documentation! https://github.com/udu3324/Hacker-UI-v8.4");
System.out.println("Hacker UI v8.4: has successfully loaded.");
System.out.println("=====================================================");
System.out.println("");
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
public void setData(HackerGUI data) {
}
public void getData(HackerGUI data) {
}
public boolean isModified(HackerGUI data) {
return false;
}
}
Main.java
import javax.swing.*;
import java.net.URL;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, javax.swing.UnsupportedLookAndFeelException
{
System.out.println("Hello, World!"); //Hello, World!
}
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("Hacker UI v8.4: is loading..."); //print status of loading
URL iconURL = getClass().getResource("/images/Hacker UI.png"); //load icon resource
ImageIcon icon = new ImageIcon(iconURL); //set icon to icon
HackerGUI hackergui = new HackerGUI(); //make a hacker gui
hackergui.setIconImage(icon.getImage()); //get icon resource and set as
hackergui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminate when asked on close
hackergui.setResizable(false); //no resizing
hackergui.pack(); //wrap it into a pack and set jframe size depending on jframe component size
hackergui.setLocationRelativeTo(null); //set location to middle of screen
hackergui.setVisible(true); //set the frame visible
}
});
}
}
If you do not want to overwrite the text each time you need to append. You can do this by initializing your FileEriter as follows:
FileWriter myWriter = new FileWriter("scores.txt", true);
This constructor takes 2 parameters, one is the file you are writing to and the second is a boolean expression that determines will you append to the file or overwrite it.
If you want to know more about it you can check it out here:
https://www.geeksforgeeks.org/java-program-to-append-a-string-in-an-existing-file/
I need hlep with figuring out how to wrap the text in the JavaFX TextField object.
So my code gets a file name from the user, opens the file by pasting the contents of the text file into the text field. Then the user can edit the text and save it into the same file.
My code does all of the above so that's not what I need help with. The JavaFX TextField object does not seem to have a way to wrap the text in the text box. It ends up looking like this:
Alt Image Link: https://drive.google.com/open?id=1q2yU5ox6WA5EwS3YSxaKoqUDpCxpbPmu
I want to wrap the text for obvious reasons. Below is my code (minus the import statements)
public class TextEditor extends Application
{
private Button button = new Button();
private TextField text = new TextField();
private Label label = new Label("Enter filename:");
private String filename = "";
String filetext = "";
Scanner file = new Scanner("");
PrintWriter pw = null;
FileOutputStream fos = null;
#Override
public void start(Stage primaryStage) throws Exception
{
GridPane myPane = new GridPane();
myPane.setHgap(10);
myPane.setVgap(10);
Scene myScene = new Scene(myPane, 500, 500);
primaryStage.setScene(myScene);
primaryStage.show();
primaryStage.setTitle("Find File");
myPane.setAlignment(Pos.BASELINE_CENTER);
label.setAlignment(Pos.BASELINE_CENTER);
myPane.add(label, 0, 0, 3, 1);
text.setAlignment(Pos.TOP_LEFT);
text.setPrefWidth(480);
text.setPrefHeight(400);
myPane.add(text, 0, 1);
button = new Button("Submit Filename");
button.setPrefSize(180, 50);
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
if(button.getText().equals("Save Changes"))
{
try
{
fos = new FileOutputStream(filename);
pw = new PrintWriter(fos);
System.out.println("Saving changes in " + filename);
pw.println(text.getText());
pw.close();
primaryStage.close();
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(button.getText().equals("Submit Filename"))
{
filename = text.getText();
try
{
file = new Scanner(new FileInputStream(new File(filename)));
while(file.hasNextLine())
{
String line = file.nextLine();
System.out.println(line);
filetext += line + "\n";
}
System.out.println("File text: " + filetext);
text.setText(filetext);
button.setText("Save Changes");
}
catch(FileNotFoundException exc)
{
System.out.println("Cannot find file. Program aborted.");
primaryStage.close();
}
}
}
});
myPane.add(button, 0, 2);
}
public static void main(String[] args)
{
Application.launch(args);
}
}
Would love some assistance getting the text to wrap. Do I need to not use a JavaFX TextField? Should I use something else?
Thanks in advance!
EDIT
SOLUTION FOUND
I changed the TextField text to a TextArea, removed the text.setAlignment(Pos.TOP_LEFT) line and added a text.setWrapText(true) (as suggested below) and now the program works great. Thanks Fabian and Zephyr!
How to display a text in a JTextField ot jLabel with 2 colors.
for example:
1 0 0 0 1 1 1 0 1
textField.setForeground(Color.RED ,BLUE);
Positioning individual RED for example
Different font color in a JTextField
You can't achieve it with JTextField instead use JEditorPane or JTextPane.
Read more about How to Use Editor Panes and Text Panes
Sample code using JTextPane directly from HERE
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class StylesExample12 {
public static void main(String[] args) {
JFrame f = new JFrame("Styles Example 1");
// Create the StyleContext, the document and the pane
StyleContext sc = new StyleContext();
final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
JTextPane pane = new JTextPane(doc);
// Create and add the style
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
try {
// Add the text to the document
doc.insertString(0, text, null);
// Finally, apply the style to the heading
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (BadLocationException e) {
}
}
});
} catch (Exception e) {
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
f.getContentPane().add(new JScrollPane(pane));
f.setSize(400, 300);
f.setVisible(true);
}
public static final String text = "Attributes, Styles and Style Contexts\n"
+ "The simple PlainDocument class that you saw in the previous "
+ "chapter is only capable of holding text. The more complex text "
+ "components use a more sophisticated model that implements the "
+ "StyledDocument interface. StyledDocument is a sub-interface of "
+ "Document that contains methods for manipulating attributes that "
+ "control the way in which the text in the document is displayed. "
+ "The Swing text package contains a concrete implementation of "
+ "StyledDocument called DefaultStyledDocument that is used as the "
+ "default model for JTextPane and is also the base class from which "
+ "more specific models, such as the HTMLDocument class that handles "
+ "input in HTML format, can be created. In order to make use of "
+ "DefaultStyledDocument and JTextPane, you need to understand how "
+ "Swing represents and uses attributes.\n";
}
snapshot:
EDIT
As per your question try this sample code: (change it as per your requirement)
// Create and add the style
final Style redStyle = sc.addStyle("RED", null);
redStyle.addAttribute(StyleConstants.Foreground, Color.red);
redStyle.addAttribute(StyleConstants.FontSize, new Integer(16));
final Style blueStyle = sc.addStyle("BLUE", null);
blueStyle.addAttribute(StyleConstants.Foreground, Color.blue);
blueStyle.addAttribute(StyleConstants.FontSize, new Integer(14));
blueStyle.addAttribute(StyleConstants.Bold, new Boolean(true));
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
try {
String[] text = { "1a", "0b", "0c", "0d", "1e", "1f", "1g", "0h", "1i" };
for (int i = 0; i < text.length; i++) {
String s = text[i];
// Finally, apply the style to the heading
int start = pane.getText().length();
Style style = null;
if (i % 2 == 0) {
style = redStyle;
} else {
style = blueStyle;
}
// Add the text to the document
doc.insertString(start, s + " ", style);
}
} catch (BadLocationException e) {
}
}
});
} catch (Exception e) {
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
snapshot:
I am trying to add a slider on my page like progress bar. But my code is not working well.
My task is when I am going to copy something from one location to another I want to display a progress bar on my page.
So in javaFx I wrote following task but it is not working well. That code runs but I want show the work in percentage like 30%, 50% and "finish". But my code fails to gives me like requirement so please help me.
My code is:
1.Declaration of progress bar and progress indicator
#FXML
final ProgressBar progressBar = new ProgressBar();
#FXML
final ProgressIndicator progressIndicator = new ProgressIndicator();
2.Assign values when I click on copy button.
#FXML
private void handleOnClickButtonAction(MouseEvent event) {
if (fromLabel.getText().isEmpty()
|| toLabel.getText().isEmpty()
|| fromLabel.getText().equalsIgnoreCase("No Directory Selected")
|| toLabel.getText().equalsIgnoreCase("No Directory Selected")) {
// Nothing
} else {
progressBar.setProgress(0.1f);
progressIndicator.setProgress(progressBar.getProgress());
this.directoryCount.setText("Please Wait !!!");
}
}
This code shows me only 10% completion an then directly shows "done", but I want whole process in percentage like 10,20,30,.. etc and then "done".
My copy code:
double i = 1;
while (rst.next()) {
File srcDirFile = new File(fromLabel.getText() + "/" + rst.getString("nugget_media_files"));
File dstDirFile = new File(toLabel.getText() + "/" + rst.getString("nugget_media_files"));
File dstDir = new File(toLabel.getText() + "/" + rst.getString("nugget_directory"));
if (srcDirFile.lastModified() > dstDirFile.lastModified()
|| srcDirFile.length() != dstDirFile.length()) {
copyDirectory(srcDirFile, dstDirFile, dstDir);
}
this.currentNuggetCount = i / this.nuggetFolderSize;
System.out.println("Nugget Count : " + this.currentNuggetCount);
Platform.runLater(new Runnable() {
#Override
public void run() {
progressBar.setProgress(1.0f);
progressIndicator.setProgress(progressBar.getProgress());
}
});
++i;
}
This is the copyDirectory method:
private static void copyDirectory(File srcDir, File dstDir,File destNugget) {
System.out.println(srcDir+" >> "+dstDir);
if(!destNugget.exists()) {
destNugget.mkdirs();
}
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdirs();
}
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(srcDir, children[i]),
new File(dstDir, children[i]),
destNugget);
}
} else {
InputStream in = null;
try {
in = new FileInputStream(srcDir);
OutputStream out = new FileOutputStream(dstDir);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException ex) {
System.out.println("Exceptio "+ex);
} finally {
try {
in.close();
} catch (IOException ex) {
System.out.println("Exceptio "+ex);
}
}
}
}
Try this code. It will give you Progress bar with progress indicator which depends on the slider control.
public class Main extends Application {
#Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Progress Controls");
final Slider slider = new Slider();
slider.setMin(0);
slider.setMax(50);
final ProgressBar pb = new ProgressBar(0);
final ProgressIndicator pi = new ProgressIndicator(0);
slider.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov,
Number old_val, Number new_val) {
pb.setProgress(new_val.doubleValue()/50);
pi.setProgress(new_val.doubleValue()/50);
}
});
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(slider, pb, pi);
scene.setRoot(hb);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
You must enter your code inside a Task and set within UpdateProgress method. Before you run the Task you have to set progressBar.progressProperty (). Bind (task.progressProperty ());
This is an example:
TaskTest
I have an assignment from my university to continue a JAVA card project from the students from last semester, which happens to be sucked. Because we have to carry on with someones work instead ours..
So my first step is to make an window image icon and tray icon for the application`s window.
The thing is, this code below is based on extended FrameView instead of JWindow.
My idea is to wrap the extended FrameView up into a Window.
Can someone help me with that?
Thanks much I would appreciate that.
CODE:
public class DesktopApplication1View extends FrameView implements IProgressDialogObserver
{
//============================================================
// Fields
// ===========================================================
private Connection connection = new Connection();
private ProgressDialogUpdater pbu = ProgressDialogUpdater.getInstance();
private Vector<CourseFromCard> courseListFromCard = new Vector<CourseFromCard>();
private Vector<School> schoolList = new Vector<School>();
private Vector<CourseFromFile> courseList = new Vector<CourseFromFile>();
private int cardReaderRefreshHelper = 0;
private Student student = null;
JLabel jLabelBilkaImage = null;
final String ICON = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_32.png";
final String PIC = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_128.png";
private JLabel getJLabelBilkaImage() {
if (jLabelBilkaImage == null) {
Icon image = new ImageIcon(PIC);
jLabelBilkaImage = new JLabel(image);
jLabelBilkaImage.setName("jLabelBilkaImage");
}
return jLabelBilkaImage;
}
//============================================================
// Constructors
// ===========================================================
public DesktopApplication1View(SingleFrameApplication app)
{
super(app);
pbu.registriere(this);
app.getMainFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
initComponents();
refreshConnectionState();
readFilesFromLocalHDD();
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++)
{
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
{
public void propertyChange(java.beans.PropertyChangeEvent evt)
{
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName))
{
if (!busyIconTimer.isRunning())
{
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
}
else if ("done".equals(propertyName))
{
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
}
else if ("message".equals(propertyName))
{
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
}
else if ("progress".equals(propertyName))
{
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}
.........
SingleFrameApplication provides the method getMainFrame(), which returns the JFrame used to display a particular view. The code you listed in your question is one such view. If you need to operate on the frame, it's probably better to do it in code subclassing SingleFrameApplication than the code you posted.
There's a tutorial on using the Swing Application Framework, which might provide more help.