Commit d2491f18 authored by Radek Ošlejšek's avatar Radek Ošlejšek
Browse files

Merge branch '34-add-preferences-to-the-application' into 'master'

Resolve "Add "Preferences" to the application."

Closes #34

See merge request grp-fidentis/analyst2!42
parents 52d3fba3 d8beefd7
Loading
Loading
Loading
Loading
+42 −4
Original line number Diff line number Diff line
@@ -12,6 +12,10 @@ import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.ImageIcon;
@@ -151,7 +155,7 @@ public class Canvas extends javax.swing.JPanel {
        
        //enables to shows just .obj files in file chooser
        ModelFileFilter filter = new ModelFileFilter(extensions, "*.obj");
        JFileChooser jFileChooser1 = new JFileChooser();
        JFileChooser jFileChooser1 = new JFileChooser(getPrefferedModelPath());
        jFileChooser1.setPreferredSize(new Dimension (800,500));
       
        jFileChooser1.addChoosableFileFilter(filter);        
@@ -160,10 +164,16 @@ public class Canvas extends javax.swing.JPanel {
        jFileChooser1.showOpenDialog(this);
        jFileChooser1.setDialogTitle("Import obj file");
        
        setPrefferedModelPath(jFileChooser1.getCurrentDirectory().toString());
        
        File[] fileArray = new File[1];
        //saves selected file by user as first element in array
        fileArray[0] = jFileChooser1.getSelectedFile();

        //testing getting path TODO
        //JOptionPane.showConfirmDialog(null,
        //        fileArray[0].getAbsoluteFile(), "", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

        if (fileArray.length <= 0) {
            System.out.print("No file chosen.");
        } else {
@@ -172,6 +182,34 @@ public class Canvas extends javax.swing.JPanel {
        glCanvas.setVisible(true);
    }
    
    private void setPrefferedModelPath(String s) {
        //TODO remove duplicate with PreferenceTopComponent
        try {
            FileWriter rewriter = new FileWriter("preferences.fip", false);
            rewriter.write(s);
            rewriter.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }   
    }
    
    private String getPrefferedModelPath() {
        //TODO remove duplicate with PreferenceTopComponent
        String data = "";
        try {
            File myObj = new File(/*propPath + */"preferences.fip");
            if (myObj.length() == 0)
                return data;
            try (Scanner myReader = new Scanner(myObj)) {
                data = myReader.nextLine();
            }            
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        return data;
    }

    /**
     * Loads the model in .obj format from file and adds this model to listener for displaying.
     * If file does not contain 3D model or model is not correct, shows dialog with message
+1 −0
Original line number Diff line number Diff line
@@ -31,6 +31,7 @@ public class Installer extends ModuleInstall {
            java.util.logging.Logger.getLogger(UserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(() -> {
            //old JFrame, disabled
            /*frameMain = new UserInterface();
            frameMain.setBackground(new Color(49,165,154));
            frameMain.pack();
+102 −0
Original line number Diff line number Diff line
<?xml version="1.0" encoding="UTF-8" ?>

<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->

<Form version="1.5" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
  <AuxValues>
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
  </AuxValues>

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" attributes="0">
              <EmptySpace max="-2" attributes="0"/>
              <Group type="103" groupAlignment="0" attributes="0">
                  <Component id="jFormattedTextField1" max="32767" attributes="0"/>
                  <Group type="102" alignment="0" attributes="0">
                      <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
                      <EmptySpace min="0" pref="183" max="32767" attributes="0"/>
                  </Group>
              </Group>
              <EmptySpace max="-2" attributes="0"/>
              <Component id="jButton1" min="-2" max="-2" attributes="0"/>
              <EmptySpace min="-2" pref="18" max="-2" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
    <DimensionLayout dim="1">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" attributes="0">
              <EmptySpace max="-2" attributes="0"/>
              <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
              <EmptySpace max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jFormattedTextField1" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="jButton1" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace pref="246" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Component class="javax.swing.JButton" name="jButton1">
      <Properties>
        <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
          <ResourceString bundle="cz/fidentis/analyst/gui/Bundle.properties" key="PreferencesTopComponent.jButton1.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
        </Property>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JFormattedTextField" name="jFormattedTextField1">
      <Properties>
        <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
          <ResourceString bundle="cz/fidentis/analyst/gui/Bundle.properties" key="PreferencesTopComponent.jFormattedTextField1.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
        </Property>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jFormattedTextField1ActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel1">
      <Properties>
        <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
          <ComponentRef name="jFormattedTextField1"/>
        </Property>
        <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
          <ResourceString bundle="cz/fidentis/analyst/gui/Bundle.properties" key="PreferencesTopComponent.jLabel1.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
        </Property>
      </Properties>
    </Component>
  </SubComponents>
</Form>
+210 −0
Original line number Diff line number Diff line
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.fidentis.analyst.gui;

import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Richard Pajerský
 * 
 * Window with basic Preferences
 */
@ConvertAsProperties(
        dtd = "-//cz.fidentis.analyst.gui//Preferences//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "PreferencesTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "properties", openAtStartup = false)
@ActionID(category = "Window", id = "cz.fidentis.analyst.gui.PreferencesTopComponent")
@ActionReference(path = "Menu/Tools", position = 2600, separatorBefore = 2550 /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_PreferencesAction",
        preferredID = "PreferencesTopComponent"
)
@Messages({
    "CTL_PreferencesAction=Preferences",
    "CTL_PreferencesTopComponent=Preferences Window",
    "HINT_PreferencesTopComponent=This is a Preferences window"
})
public final class PreferencesTopComponent extends TopComponent {

    public PreferencesTopComponent() {
        initComponents();
        setName(Bundle.CTL_PreferencesTopComponent());
        setToolTipText(Bundle.HINT_PreferencesTopComponent());
        putClientProperty(TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.TRUE);
        
        createPreferencesFile();
    }
    
    private void createPreferencesFile() {
        //testing preferences fodler        
        //String propPath = System.getProperty("user.home") + "/preferences";
        try {
            File myObj = new File(/*propPath + */"preferences.fip");
        if (myObj.createNewFile()) {
            //JOptionPane.showConfirmDialog(null, "File created: " + myObj.getName());
        } else {
            //JOptionPane.showConfirmDialog(null, "File already exists." + myObj.getName());
        }
        } catch (IOException e) {
        JOptionPane.showConfirmDialog(null, "An error occurred.");
        e.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(PreferencesTopComponent.class, "PreferencesTopComponent.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jFormattedTextField1.setText(org.openide.util.NbBundle.getMessage(PreferencesTopComponent.class, "PreferencesTopComponent.jFormattedTextField1.text")); // NOI18N
        jFormattedTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField1ActionPerformed(evt);
            }
        });

        jLabel1.setLabelFor(jFormattedTextField1);
        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PreferencesTopComponent.class, "PreferencesTopComponent.jLabel1.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jFormattedTextField1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 183, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(246, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        JFileChooser chooser = new JFileChooser(getPrefferedModelPath());
        chooser.setDialogTitle("Model directory");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            //JOptionPane.showConfirmDialog(null,
            //    chooser.getCurrentDirectory(), "", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            //JOptionPane.showConfirmDialog(null,
            //    chooser.getSelectedFile(), "", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            setPrefferedModelPath(chooser.getSelectedFile().toString());
        }
        else {
            System.out.println("No Selection ");
        }
        
        componentOpened();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jFormattedTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFormattedTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jFormattedTextField1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
    
    private void setPrefferedModelPath(String s) {
        try {
            FileWriter rewriter = new FileWriter("preferences.fip", false);
            rewriter.write(s);
            rewriter.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }   
    }
    
    private String getPrefferedModelPath() {
        String data = "";
        try {
            File myObj = new File(/*propPath + */"preferences.fip");
            if (myObj.length() == 0)
                return data;
            try (Scanner myReader = new Scanner(myObj)) {
                data = myReader.nextLine();
            }            
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        return data;
    }
    
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        jFormattedTextField1.setText(getPrefferedModelPath());
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
}
+3 −6
Original line number Diff line number Diff line
#Localized module labels. Defaults taken from POM (<name>, <description>, <groupId>) if unset.
#OpenIDE-Module-Name=
#OpenIDE-Module-Short-Description=
#OpenIDE-Module-Long-Description=
#OpenIDE-Module-Display-Category=
#Thu Oct 03 09:09:53 CEST 2019
PreferencesTopComponent.jButton1.text=Change
PreferencesTopComponent.jFormattedTextField1.text=
PreferencesTopComponent.jLabel1.text=Path to model directory