diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a6f89c2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target/ \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..376dc4f --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,13 @@ +Copyright 2013 BrosMakingSoftware + +Licensed 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8f96939 --- /dev/null +++ b/README.md @@ -0,0 +1,298 @@ +## SwingHelper +This is the **official** GitHub repository of the SwingHelper project (known as sidereal-libraries), created on September 2013 and originally hosted at Google Code, now archived. For reference go to https://code.google.com/archive/p/sidereal-libraries/. SwingHelper packages were rebranded to *BrosMakingSoftware* in order to match the format of its new home. + +The following documentation is based on the *Swing's Little Helper* article published at https://www.codeproject.com/Articles/662256/Swings-Little-Helper. It was updated to fix some grammar issues, to make it simpler to read and it has been reformatted to match Markdown syntax. + +## Introduction +Swing is the primary Java GUI widget toolkit. It is easy to use but there are things that can be improved, like assumptions of defaults values (for example all the parameters to display a simple Information Message Dialog), and the usage of flexible collections when binding properties to Swing components. + +**SwingHelper** improves these areas by implementing some default parameters encapsulated in convenient methods to make easier invocations of some components like messages and dialogs, as well as implementing collections on some models. + +## Background +Swing is the primary Java GUI, but it is not the only one available for Java to create desktop applications, we can find AWT, SWT, SwingX, JavaFX, Apache Pivot, and many others. + +AWT was the first Java GUI, and Swing is its successor. Swing was created to provide rich components completely written on Java, which means that they are not implemented by platform-specific code, it is also known as “lightweight” elements, the ability of Swing to render their own components by painting them using Java2D APIs and not depending of native user interface toolkits. + +One of the reasons why we choose Swing to work on our projects is because it is completely written on Java and it is included on the JVM, so no extra libraries are needed, also we can create OS-independent applications using the Look and Feel we want, they can be one of the Java's defaults look and feels that looks the same on all platforms, or our favorite, the current OS look and feel, all in one pure jar that is executable in any platform, literally “write once, run anywhere”. + +SwingHelper was made to help you create beautiful UI experiences. We want to disprove the myth that Java only delivers ugly look and feels, and the myth that you need OS-specific libraries to make it work. + +## Using the code +What is SwingHelper? +It is an open-source library written on Java, it is a set of common invocations to components that reduces complexity assuming default values. Also it implements some AbstractModels to bind data with components, just in seconds! + +### Downloading the library +Download the latest version available at https://github.com/BrosMakingSoftware/SwingHelper/releases + +### Running examples +SwingHelper is a Maven project, you should be able to build it and run a test to see a demo of all the features. Follow the instructions displayed on each Dialog to complete the test. All the code displayed on this documentation can be found on the test packages of this project. + +### The `SwingHelper` class +This class contains the following features: + +* Sets the Look and Feel of the whole application: +Note: The `System` Look and Feel is **always** set as default when using SwingHelper, instead +of the `Metal` one (Java's default) + ```java + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.NIMBUS); + //or + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.MOTIF); + //or + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.METAL); + //or + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.SYSTEM); + ``` + +* When using `Metal` Look and Feel, you can change its themes by using: + ```java + SwingHelper.setMetalTheme(SwingHelper.MetalTheme.DEFAULT_METAL); + //or + SwingHelper.setMetalTheme(SwingHelper.MetalTheme.OCEAN); + ``` + +* Centers the windows: + ```java + SwingHelper.centerWindow(customerJDialog); + ``` + +* Displays error messages: + ```java + SwingHelper.showErrorMessage("Error title", "This is an error message."); + ``` + +* Displays warning messages: + ```java + SwingHelper.showWarningMessage("Warning title", "This is a warning message."); + ``` + +* Displays information messages: + ```java + SwingHelper.showInformationMessage("Information title", "This is an information message."); + ``` + +* Displays Input Dialogs asking for required values: + ```java + String result = + SwingHelper.askForRequiredTextUsingInputDialog("Text request", "Write your name:"); + ``` + +* Displays Confirmation Dialogs with `Yes/No`, `Yes/No/Cancel` or `OK/Cancel` buttons: + ```java + String title = "Click on a button to confirm"; + String message = "Click on YES button"; + + String result = SwingHelper.showConfirmationDialogWithYesNoButtons(title, message); + + if(result.equals("yes")){ + // Write your logic here... + } + ``` + +* Displays File Choosers asking for folders: + ```java + String title = "Choose a folder" + String startDirectory = "target/test-classes/com/diegohp/swing/"; + + File result = SwingHelper.chooseDirectory(title, startDirectory); + // Use 'result' as your folder + ``` + +* Displays File Choosers asking for files: + ```java + String title = "Choose any file"; + + File result = SwingHelper.chooseFile(title); + // Use 'result' as your file + ``` + +* Displays File Choosers asking for files with an specific extension: + ```java + String title = "Choose a text file"; + String fileExtension = ".txt"; + + File result = SwingHelper.chooseFile(title, fileExtension); + // Use 'result' as your file + ``` + +All of these features have more specific parameters (some of them omitted in the above examples), you should be able to define different parameters to change the behavior as needed. + +The most common parameters are: `title` (of the window), `startDirectory` (the folder that a file chooser opens as default), `fileExtension` (the extension of the file to be selected), `startFile` (the file that a file chooser selects as default), `lookAndFeel` (one of the options of an enum of the same name), `metalTheme` (one of the options of another enum of the same name), `message` (the message displayed on message window). + +### The `ListComboBoxModel` class +This class contains the following features: + +* Extends `AbstractListModel` and implements `MutableComboBoxModel`. All methods are implemented. + +* `AbstractListModel` gives the ability to use a List as the data container (in this case, an ArrayList with parameterized type) + +* `MutableComboBoxModel` gives the ability to change its data even after the UI component was displayed + +Example: +We are going to create a window that asks the user to select a language from a combo box. +Let's declare a JDialog with a Combo Box and a button: +```java +public class LanguageSelectorJDialog extends javax.swing.JDialog { + private javax.swing.JComboBox jComboBoxLanguages; + private javax.swing.JButton jButtonSelect; +} +``` + +Now use `ListComboBoxModel` to create the model of the Combo Box: +```java +private ListComboBoxModel languagesListComboBoxModel; +``` + +Note: in this case the parameterized type of the container was set to ``, this is a trivial example just to demonstrate that any class can fit this place, even your custom classes like pojos, the only requirements is that they must override the `toString()` method (component uses this value as the display text), to return something understandable by the user, but if it is not your case, you will need to create a wrapper class to provide a different `toString()` implementation. + +Next, on the constructor of the JDialog we are going to populate the model with data: +```java +this.languagesListComboBoxModel.addElement("English"); +this.languagesListComboBoxModel.addElement("Español"); +``` + +Now we are going to implement the logic of the click event of the select button: +```java +private void jButtonSelectActionPerformed(java.awt.event.ActionEvent evt) { + + // See how easy is to get the selected object of the combo + String selected = (String) this.languagesListComboBoxModel.getSelectedItem(); + + // Then implement your logic + if (selected.equals("English")) { + Locale.setDefault(Locale.ENGLISH); + System.out.println("Language set to English"); + } + else { + Locale.setDefault(new Locale("es")); + System.out.println("Language set to Spanish"); + } +} +``` + +This is how the final result looks like, this is an actual screenshot of one of our applications which uses this logic: +![ListComboBoxModel.jpg](screenshots/2013-10-02_11_10_46-ListComboBoxModel.jpg) + +This is a pretty easy example of a usage of the `ListComboBoxModel` class, but remember the ability of the parameterized type. Let's think in a more complex scenario, were instead of `String` we have a custom class called `Language`, that has a name (English, Spanish) and a number of language (345, 874) and the list of languages are not limited to only 2, they can be more based on the records of a data base. Fist you need to override the `toString()` method of the Language class to return just the name (since the user is not going to understand the number of language), then you just need to add all the list of languages to the model and when the user selects a language and clicks on select button, the model returns the whole selected object, in this case a Language object directly. With this feature you avoid the creation of auxiliary lists to represent indexes of the real objects. + +### The `ListTableModel` class +This class contains the following features: + +* Extends from `AbstractTableModel`, it implements all the methods as much as it can, leaving just one method to be implemented, `getValueAt(int row, int col)`, which is very easy, you just need to return the value of the corresponding column. When trying to implement an `AbstractTableModel` you get around a 40% of the class, using `ListTableModel` you get a 99% of the implementation with a flexible and mutable logic. + +* It has a List of Strings where you can set the columns names, you can change them even after the component was displayed + +* Implements the usage of a List as a data container (in this case, an `ArrayList` with parameterized type), very useful when displaying and editing information on a table + +Example: +For this scenario we are going to create a window with a table of customers, when a customer is clicked, a message is displayed with their information and a count of views, which is incremented each time you click them. + +First, let's create an entity class of Customer: +```java +public class Customer { + private Long id; + private String name; + private Integer views; + + // All setters an getters +} +``` + +Now, let's create a `JDialog` with a table, a model and a Customer object to keep the selected customer: +```java +public class CustomerTableModelJDialog extends javax.swing.JDialog { + + private javax.swing.JTable jTableCustomers; + private ListTableModel customersListTableModel; + private Customer customerSelected; +} +``` + +Once the model is declared, we need to create its instance by implementing the remaining method to get the display values of each column. In this case our first column will display the Id of the customers, the second column displays the name and the third column displays the numbers of views: +```java +this.customersListTableModel = new ListTableModel() { + @Override + public Object getValueAt(int row, int col) { + Customer customer = this.objects.get(row); + if (col == 0) { + return customer.getId(); + } + if (col == 1) { + return customer.getName(); + } + if (col == 2) { + return customer.getViews(); + } + return customer.getId() + " -> " + customer.getName(); + } +}; +``` + +Now we need to declare the names of the headers of the table: +```java +List columnsNames = new ArrayList(); +columnsNames.add("Id"); +columnsNames.add("Name"); +columnsNames.add("Views"); + +this.customersListTableModel.setColumnNames(columnsNames); +``` + +The next step is to create a listener to capture the value changed event and implement some specific logic when a customer is selected: +```java +this.jTableCustomers.getSelectionModel().addListSelectionListener(new ListSelectionListener() { + +@Override +public void valueChanged(ListSelectionEvent lse) { + + if (!lse.getValueIsAdjusting()) { + + ListSelectionModel model = jTableCustomers.getSelectionModel(); + + if (model.getLeadSelectionIndex() >= 0) { + customerSelected = ((ListTableModel)jTableCustomers.getModel()).getObjectAt(model.getLeadSelectionIndex()); + + // Now we got the customer, let's implement our logic + customerSelected.setViews(customerSelected.getViews() + 1); + + // Now call fireTableDataChanged so the table updates the data displayed + customersListTableModel.fireTableDataChanged(); + + // Now display some information of the customer + SwingHelper.showInformationMessage( + "Clicked on a Customer", + "Customer's Id is " + customerSelected.getId() + + " and name is " + customerSelected.getName()); + } + } + } +}); +``` + +Once the model is ready, let's set it to the table: +```java +this.jTableCustomers.setModel(this.customersListTableModel); +``` + +In order to populate the table, we need to create some customers, add them to the table and update the changes: +```java +List customers = new ArrayList(); + +Customer c1 = new Customer(); +c1.setId(123456789L); +c1.setName("Harry Mason"); +c1.setViews(0); + +Customer c2 = new Customer(); +c2.setId(987654321L); +c2.setName("James Sunderland"); +c2.setViews(0); + +customers.add(c1); +customers.add(c2); + +this.customersListTableModel.addObjectList(customers); +this.customersListTableModel.fireTableDataChanged(); +``` + +And that's it! You will see something like this: +![ListTableModel.jpg](screenshots/2013-10-02_11_12_36-ListTableModel.jpg)s diff --git a/pom.xml b/pom.xml new file mode 100755 index 0000000..0ac74e2 --- /dev/null +++ b/pom.xml @@ -0,0 +1,114 @@ + + 4.0.0 + + com.brosmakingsoftware.swing + SwingHelper + 1.2 + jar + + SwingHelper + https://github.com/BrosMakingSoftware/SwingHelper + Build Desktop User Interface using Java Swing fast and easy with SwingHelper! + + + UTF-8 + 1.8 + 1.8 + + + + + + project.local + project + file:${project.basedir}/repo + + + + + + + + maven-resources-plugin + 2.5 + + + copy-resources + validate + + copy-resources + + + ${basedir}/target/classes + + + src/main/conf + true + + + + + + + + + maven-jar-plugin + 2.3.2 + + + + + true + lib + + + conf/ + + + + + + + maven-assembly-plugin + + + make-assembly + package + + attached + + + + + + + src/main/assembly/stand-alone-app.xml + + + + + + + + + + junit + junit + 4.10 + test + + + org.swinglabs + swing-layout + 1.0.3 + test + + + org.bolet + jgz + 0.2 + test + + + diff --git a/repo/org/bolet/jgz/0.2/jgz-0.2.jar b/repo/org/bolet/jgz/0.2/jgz-0.2.jar new file mode 100755 index 0000000..3125a4a Binary files /dev/null and b/repo/org/bolet/jgz/0.2/jgz-0.2.jar differ diff --git a/repo/org/bolet/jgz/0.2/jgz-0.2.jar.sha1 b/repo/org/bolet/jgz/0.2/jgz-0.2.jar.sha1 new file mode 100755 index 0000000..b5c61a2 --- /dev/null +++ b/repo/org/bolet/jgz/0.2/jgz-0.2.jar.sha1 @@ -0,0 +1 @@ +90ac31dbef0cdfcfea7a0acab0c5567d7cfe3075 diff --git a/repo/org/bolet/jgz/0.2/jgz-0.2.pom b/repo/org/bolet/jgz/0.2/jgz-0.2.pom new file mode 100755 index 0000000..805223a --- /dev/null +++ b/repo/org/bolet/jgz/0.2/jgz-0.2.pom @@ -0,0 +1,9 @@ + + + 4.0.0 + org.bolet + jgz + 0.2 + POM was created from install:install-file + diff --git a/repo/org/bolet/jgz/0.2/jgz-0.2.pom.sha1 b/repo/org/bolet/jgz/0.2/jgz-0.2.pom.sha1 new file mode 100755 index 0000000..162af86 --- /dev/null +++ b/repo/org/bolet/jgz/0.2/jgz-0.2.pom.sha1 @@ -0,0 +1 @@ +53cc6f2e0eff8a7483947d4986d0d564bc8c4036 diff --git a/screenshots/2013-10-02_11_10_46-ListComboBoxModel.jpg b/screenshots/2013-10-02_11_10_46-ListComboBoxModel.jpg new file mode 100755 index 0000000..ea42903 Binary files /dev/null and b/screenshots/2013-10-02_11_10_46-ListComboBoxModel.jpg differ diff --git a/screenshots/2013-10-02_11_12_36-ListTableModel.jpg b/screenshots/2013-10-02_11_12_36-ListTableModel.jpg new file mode 100755 index 0000000..21aacb3 Binary files /dev/null and b/screenshots/2013-10-02_11_12_36-ListTableModel.jpg differ diff --git a/src/main/assembly/stand-alone-app.xml b/src/main/assembly/stand-alone-app.xml new file mode 100755 index 0000000..d639b0c --- /dev/null +++ b/src/main/assembly/stand-alone-app.xml @@ -0,0 +1,44 @@ + + + jar-with-dependencies + + zip + + + + conf + /conf + + + + src/main/java + /conf + + *.xml + *.properties + + + *.jar + + + + + target + / + + *.jar + + + + true + + + /lib + false + false + runtime + + + \ No newline at end of file diff --git a/src/main/java/com/brosmakingsoftware/swing/ListComboBoxModel.java b/src/main/java/com/brosmakingsoftware/swing/ListComboBoxModel.java new file mode 100644 index 0000000..e5493f6 --- /dev/null +++ b/src/main/java/com/brosmakingsoftware/swing/ListComboBoxModel.java @@ -0,0 +1,156 @@ + +package com.brosmakingsoftware.swing; + + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import javax.swing.AbstractListModel; +import javax.swing.ComboBoxModel; +import javax.swing.MutableComboBoxModel; + +/** + * This class implements a {@link ComboBoxModel} based on a {@link List} as container. + * + * @param Class that defines the type of the container list. + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + * @version 1.0 + */ +public final class ListComboBoxModel extends AbstractListModel implements MutableComboBoxModel, Serializable { + + private List objects; + private O selectedObject; + + /** + * Constructs an empty DefaultComboBoxModel object. + */ + public ListComboBoxModel() { + this.objects = new ArrayList(); + } + + + /** + * Constructs a DefaultComboBoxModel object initialized with + * a List. + * + */ + public ListComboBoxModel(java.util.List list) { + this.objects.addAll(list); + + if ( getSize() > 0 ) { + selectedObject = getElementAt( 0 ); + } + } + + // implements javax.swing.ComboBoxModel + /** + * Set the value of the selected item. The selected item may be null. + *

+ * @param anObject The combo box value or null for no selection. + */ + @Override + public void setSelectedItem(Object anObject) { + if ((selectedObject != null && !selectedObject.equals( anObject )) || + selectedObject == null && anObject != null) { + selectedObject = (O)anObject; + fireContentsChanged(this, -1, -1); + } + } + + // implements javax.swing.ComboBoxModel + @Override + public Object getSelectedItem() { + return selectedObject; + } + + // implements javax.swing.ListModel + @Override + public int getSize() { + return objects.size(); + } + + // implements javax.swing.ListModel + @Override + public O getElementAt(int index) { + if ( index >= 0 && index < objects.size() ) + return objects.get(index); + else + return null; + } + + /** + * Returns the index-position of the specified object in the list. + * + * @param anObject + * @return an integer representing the index position, where 0 is + * the first position + */ + public int getIndexOf(Object anObject) { + return objects.indexOf(anObject); + } + + // implements javax.swing.MutableComboBoxModel + @Override + @SuppressWarnings("unchecked") + public void addElement(Object anObject) { + objects.add((O)anObject); + fireIntervalAdded(this,objects.size()-1, objects.size()-1); + if ( objects.size() == 1 && selectedObject == null && anObject != null ) { + setSelectedItem( anObject ); + } + } + + // implements javax.swing.MutableComboBoxModel + @Override + @SuppressWarnings("unchecked") + public void insertElementAt(Object anObject,int index) { + objects.add(index, (O)anObject); + fireIntervalAdded(this, index, index); + } + + // implements javax.swing.MutableComboBoxModel + @Override + public void removeElementAt(int index) { + if ( getElementAt( index ) == selectedObject ) { + if ( index == 0 ) { + setSelectedItem( getSize() == 1 ? null : getElementAt( index + 1 ) ); + } + else { + setSelectedItem( getElementAt( index - 1 ) ); + } + } + + objects.remove(index); + + fireIntervalRemoved(this, index, index); + } + + // implements javax.swing.MutableComboBoxModel + @Override + public void removeElement(Object anObject) { + int index = objects.indexOf(anObject); + if ( index != -1 ) { + removeElementAt(index); + } + } + + /** + * Empties the list. + */ + public void removeAllElements() { + if ( objects.size() > 0 ) { + int firstIndex = 0; + int lastIndex = objects.size() - 1; + objects.clear(); + selectedObject = null; + fireIntervalRemoved(this, firstIndex, lastIndex); + } else { + selectedObject = null; + } + } + + public List returnObjects(){ + return this.objects; + } +} diff --git a/src/main/java/com/brosmakingsoftware/swing/ListTableModel.java b/src/main/java/com/brosmakingsoftware/swing/ListTableModel.java new file mode 100644 index 0000000..e9a7250 --- /dev/null +++ b/src/main/java/com/brosmakingsoftware/swing/ListTableModel.java @@ -0,0 +1,83 @@ + +package com.brosmakingsoftware.swing; + +import java.util.ArrayList; +import java.util.List; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableModel; + +/** + * This class defines a {@link TableModel} based on a {@link List} as container. + * + * @param Class that defines the type of the container list. + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + * @version 1.0 + */ +public abstract class ListTableModel extends AbstractTableModel { + + protected List columnNames; + protected List objects; + + public ListTableModel() { + this.columnNames = new ArrayList(); + this.objects = new ArrayList(); + } + + public ListTableModel(List objects) { + this.objects.addAll(objects); + } + + public void addObject(O object) { + this.objects.add(object); + this.fireTableDataChanged(); + } + + public void addObjectList(List objects) { + this.objects.addAll(objects); + this.fireTableDataChanged(); + } + + public O getObjectAt(int row) { + return this.objects.get(row); + } + + public O removeObjectAt(int row) { + O object = this.objects.remove(row); + this.fireTableDataChanged(); + return object; + } + + public void removeAllObjects() { + this.objects.clear(); + this.fireTableDataChanged(); + } + + @Override + public int getRowCount() { + //throw new UnsupportedOperationException("Not supported yet."); + return this.objects.size(); + } + + @Override + public int getColumnCount() { + //throw new UnsupportedOperationException("Not supported yet."); + return this.columnNames.size(); + } + + @Override + public String getColumnName(int col) { + return columnNames.get(col); + } + + public void setColumnNames(List columnNames){ + this.columnNames.addAll(columnNames); + } + + public List getObjects(){ + return this.objects; + } + + @Override + public abstract Object getValueAt(int row, int col); +} diff --git a/src/main/java/com/brosmakingsoftware/swing/SwingHelper.java b/src/main/java/com/brosmakingsoftware/swing/SwingHelper.java new file mode 100644 index 0000000..1f4b6ff --- /dev/null +++ b/src/main/java/com/brosmakingsoftware/swing/SwingHelper.java @@ -0,0 +1,365 @@ + +package com.brosmakingsoftware.swing; + +import java.awt.Toolkit; +import java.awt.Window; +import java.io.File; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.UIManager; +import javax.swing.filechooser.FileFilter; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.plaf.metal.OceanTheme; + +/** + * This class brings some shortcuts of Swing User-Interface components. + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + * @version 1.1 + */ +public final class SwingHelper { + + /** + * Setting the look and feel to be the System one as default. + */ + static{ + SwingHelper.setLookAndFeel(LookAndFeel.SYSTEM); + } + + /** + * Enum listing the look and feel types. + * @since 1.1 + */ + public enum LookAndFeel{ + /** + * The main default Java look and feel. Present on all OS. + */ + METAL("javax.swing.plaf.metal.MetalLookAndFeel"), + /** + * One of the default Java look and feels. Present on all OS. + */ + NIMBUS("javax.swing.plaf.nimbus.NimbusLookAndFeel"), + /** + * One of the default Java look and feels. Present on all OS. + */ + MOTIF("com.sun.java.swing.plaf.motif.MotifLookAndFeel"), + /** + * Windows look and feel, the theme depends on the version (XP, Vista, 7, 8). + * Only present on Windows OS. + */ + WINDOWS("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"), + /** + * A classic windows look ad feel. Only present on Windows OS. + */ + WINDOWS_CLASSIC("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"), + /** + * Mac OSX look and feel. Only present on MAC OS. + */ + MAC("com.apple.laf.AquaLookAndFeel"), + /** + * GTK+ look and feel. Present on all OS except Windows. + */ + GTK("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"), + /** + * Uses the native look and feel of the host OS. + */ + SYSTEM(UIManager.getSystemLookAndFeelClassName()); + + private String lookAndFeelClass; + + private LookAndFeel(String lookAndFeelClass){ + this.lookAndFeelClass = lookAndFeelClass; + } + + /** + * @return the lookAndFeel + */ + public String getLookAndFeelClass() { + return lookAndFeelClass; + } + } + + /** + * Enum listing the Metal themes.. + * @since 1.1 + */ + public enum MetalTheme{ + DEFAULT_METAL, + OCEAN; + + private MetalTheme(){} + } + + /** + * Set the look and feel of the current app. + *

+ * If you want to change the look and feel once the UI was displayed, invoke the following methods for each top-level container: + *
+ * + * SwingUtilities.updateComponentTreeUI(yourFrame);
+ * yourFrame.pack(); + *
+ * + * @param lookAndFeel One of the options listed on {@link LookAndFeel}. + */ + public static void setLookAndFeel(LookAndFeel lookAndFeel){ + try { + javax.swing.UIManager.setLookAndFeel(lookAndFeel.getLookAndFeelClass()); + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(SwingHelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(SwingHelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(SwingHelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(SwingHelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + } + + /** + * Set the theme for the Metal look and feel.
+ * This method calls {@link #setLookAndFeel(com.brosmakingsoftware.swing.SwingHelper.LookAndFeel)} with {@link LookAndFeel#METAL} to set the Metal look and feel.
+ * The Metal look and feel is required to use these themes. + * + * @param metalTheme One of the options listed on {@link MetalTheme}. + */ + public static void setMetalTheme(MetalTheme metalTheme){ + SwingHelper.setLookAndFeel(LookAndFeel.METAL); + if(metalTheme == MetalTheme.DEFAULT_METAL) MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); + if(metalTheme == MetalTheme.OCEAN) MetalLookAndFeel.setCurrentTheme(new OceanTheme()); + } + + /** + * Centers a {@link Window} at the center of the screen.
+ * Windows like {@link JDialog} and {@link JFrame} (and others) that extend from {@link Window} applies for this method. + * + * @param window + */ + public static void centerWindow(Window window){ + window.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/2 - window.getWidth()/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2 - window.getHeight()/2); + } + + /** + * Displays a {@link JOptionPane} as an error message. + * + * @param title The title of the dialog. + * @param message The message inside the dialog. + */ + public static void showErrorMessage(String title, String message) { + JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE); + } + + /** + * Displays a {@link JOptionPane} as a warning message. + * + * @param title The title of the dialog. + * @param message The message inside the dialog. + */ + public static void showWarningMessage(String title, String message) { + JOptionPane.showMessageDialog(null, message, title, JOptionPane.WARNING_MESSAGE); + } + + /** + * Displays a {@link JOptionPane} as an information message. + * + * @param title The title of the dialog. + * @param message The message inside the dialog. + */ + public static void showInformationMessage(String title, String message) { + JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE); + } + + /** + * Displays a {@link JOptionPane} as an Input Dialog asking for a required text. + * + * @param title The title of the dialog. + * @return The text written by the user. + */ + public static String askForRequiredTextUsingInputDialog(String title, String message) { + String text = null; + while (text == null || text.trim().equals("")) { + text = JOptionPane.showInputDialog(null, message, title, JOptionPane.QUESTION_MESSAGE); + } + return text; + } + + /** + * Displays a {@link JOptionPane} as a Confirm Dialog with YES and NO buttons. + * + * @param title The title of the Dialog. + * @param message The message of the Dialog. + * @return "yes" or "no" if clicked on the respective buttons. + */ + public static String showConfirmationDialogWithYesNoButtons(String title, String message){ + int result = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if(result == JOptionPane.YES_OPTION) return "yes"; + if(result == JOptionPane.NO_OPTION) return "no"; + return null; + } + + /** + * Displays a {@link JOptionPane} as a Confirm Dialog with YES, NO and CANCEL buttons. + * + * @param title The title of the Dialog. + * @param message The message of the Dialog. + * @return "yes" or "no" or "cancel" if clicked on the respective buttons. + */ + public static String showConfirmationDialogWithYesNoCancelButtons(String title, String message){ + int result = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); + if(result == JOptionPane.YES_OPTION) return "yes"; + if(result == JOptionPane.NO_OPTION) return "no"; + if(result == JOptionPane.CANCEL_OPTION) return "cancel"; + return null; + } + + /** + * Displays a {@link JOptionPane} as a Confirm Dialog with OK and CANCEL buttons. + * + * @param title The title of the Dialog. + * @param message The message of the Dialog. + * @return "ok" or "cancel" if clicked on the respective buttons. + */ + public static String showConfirmationDialogWithOkCancelButtons(String title, String message){ + int result = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); + if(result == JOptionPane.OK_OPTION) return "ok"; + if(result == JOptionPane.CANCEL_OPTION) return "cancel"; + return null; + } + + /** + * Displays a {@link JFileChooser} to select a directory. + * + * @param title The title of the dialog. + * @param startDirectory The directory where the dialog is initialed opened. + * @return The {@link File} selected, returns null if no directory was selected. + */ + public static File chooseDirectory(String title, String startDirectory) { + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setDialogTitle(title); + + if (startDirectory != null && !startDirectory.trim().equals("")) { + chooser.setCurrentDirectory(new File(startDirectory)); + } + + int status = chooser.showOpenDialog(null); + + if (status == JFileChooser.APPROVE_OPTION) { + return chooser.getSelectedFile(); + } + + return null; + } + + /** + * Displays a {@link JFileChooser} to select a directory. + * + * @param title The title of the dialog. + * @param startDirectory The directory where the dialog is initialed opened. + * @return The {@link File} selected, returns null if no directory was selected. + */ + public static File chooseDirectory(String title, File startDirectory) { + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setDialogTitle(title); + + if (startDirectory != null) { + chooser.setCurrentDirectory(startDirectory); + } + + int status = chooser.showOpenDialog(null); + + if (status == JFileChooser.APPROVE_OPTION) { + return chooser.getSelectedFile(); + } + + return null; + } + + /** + * Displays a {@link JFileChooser} to select a directory. + * + * @param title The title of the dialog. + * @return The {@link File} selected, returns null if no directory was selected. + */ + public static File chooseDirectory(String title) { + return chooseDirectory(title, ""); + } + + /** + * Displays a {@link JFileChooser} to select a file. + * + * @param title The title of the dialog. + * @param startDirectory The directory where the dialog is initialed opened. + * @param fileExtension File extension to filter each content of the opened + * directories. Example ".xml". + * @param startFile The preselected file where the dialog is initialed opened. + * @return The {@link File} object selected, returns null if no file was selected. + */ + public static File chooseFile(String title, String startDirectory, final String fileExtension, String startFile) { + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + chooser.setDialogTitle(title); + + if (fileExtension != null && !fileExtension.trim().equals("")) { + FileFilter filter = new FileFilter() { + + @Override + public boolean accept(File pathname) { + return pathname.isDirectory() || pathname.getName().endsWith(fileExtension); + } + + @Override + public String getDescription() { + return "(" + fileExtension + ")"; + } + }; + + chooser.setFileFilter(filter); + } + + if (startDirectory != null && !startDirectory.trim().equals("")) { + chooser.setCurrentDirectory(new File(startDirectory)); + } + + if (startFile != null && !startFile.trim().equals("")) { + chooser.setSelectedFile(new File(startFile)); + } + + int status = chooser.showOpenDialog(null); + + if (status == JFileChooser.APPROVE_OPTION) { + return chooser.getSelectedFile(); + } + + return null; + } + + /** + * Displays a {@link JFileChooser} to select a file. + * + * @param title The title of the dialog. + * @param startDirectory The directory where the dialog is initialed opened. + * @param fileExtension File extension to filter each content of the opened + * directories. Example ".xml". + * @return The {@link File} object selected, returns null if no file was + * selected. + */ + public static File chooseFile(String title) { + return chooseFile(title, null, null, null); + } + + /** + * Displays a {@link JFileChooser} to select a file. + * + * @param title The title of the dialog. + * @param fileExtension File extension to filter each content of the opened directories. Example ".xml". + * @return The {@link File} object selected, returns null if no file was selected. + */ + public static File chooseFile(String title, String fileExtension) { + return chooseFile(title, null, fileExtension, null); + } +} diff --git a/src/test/java/com/brosmakingsoftware/swing/Customer.java b/src/test/java/com/brosmakingsoftware/swing/Customer.java new file mode 100644 index 0000000..1b04c20 --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/Customer.java @@ -0,0 +1,63 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package com.brosmakingsoftware.swing; + +/** + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + */ +public class Customer { + + private Long id; + private String name; + private Integer views; + + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the views + */ + public int getViews() { + return views; + } + + /** + * @param views the views to set + */ + public void setViews(Integer views) { + this.views = views; + } + + + +} diff --git a/src/test/java/com/brosmakingsoftware/swing/CustomerTableModelJDialog.form b/src/test/java/com/brosmakingsoftware/swing/CustomerTableModelJDialog.form new file mode 100644 index 0000000..1276b1f --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/CustomerTableModelJDialog.form @@ -0,0 +1,87 @@ + + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + +
+
+
+
+ + + + + +
+
diff --git a/src/test/java/com/brosmakingsoftware/swing/CustomerTableModelJDialog.java b/src/test/java/com/brosmakingsoftware/swing/CustomerTableModelJDialog.java new file mode 100644 index 0000000..b2e80cb --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/CustomerTableModelJDialog.java @@ -0,0 +1,198 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.brosmakingsoftware.swing; + +import com.brosmakingsoftware.swing.ListTableModel; +import com.brosmakingsoftware.swing.SwingHelper; +import java.util.ArrayList; +import java.util.List; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +/** + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + */ +public class CustomerTableModelJDialog extends javax.swing.JDialog { + + /** + * Creates new form CustomerTableModelJDialog + */ + public CustomerTableModelJDialog(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + SwingHelper.centerWindow(this); + + this.customersListTableModel = new ListTableModel() { + + @Override + public Object getValueAt(int row, int col) { + Customer customer = this.objects.get(row); + if (col == 0) { + return customer.getId(); + } + if (col == 1) { + return customer.getName(); + } + if (col == 2) { + return customer.getViews(); + } + return customer.getId() + " -> " + customer.getName(); + } + }; + + List columnsNames = new ArrayList(); + columnsNames.add("Id"); + columnsNames.add("Name"); + columnsNames.add("Views"); + this.customersListTableModel.setColumnNames(columnsNames); + + + this.jTableCustomers.getSelectionModel().addListSelectionListener(new ListSelectionListener() { + + @Override + public void valueChanged(ListSelectionEvent lse) { + if(!lse.getValueIsAdjusting()){ + ListSelectionModel model = jTableCustomers.getSelectionModel(); + if(model.getLeadSelectionIndex() >= 0){ + customerSelected = ((ListTableModel)jTableCustomers.getModel()).getObjectAt(model.getLeadSelectionIndex()); + customerSelected.setViews(customerSelected.getViews() + 1); + customersListTableModel.fireTableDataChanged(); + SwingHelper.showInformationMessage("Clicked on a Customer", "Customer's Id is " + customerSelected.getId() + " and name is " + customerSelected.getName()); + } + } + } + }); + + jTableCustomers.setModel(this.customersListTableModel); + + List customers = new ArrayList(); + + Customer c1 = new Customer(); + c1.setId(123456789L); + c1.setName("Harry Mason"); + c1.setViews(0); + + Customer c2 = new Customer(); + c2.setId(987654321L); + c2.setName("James Sunderland"); + c2.setViews(0); + + customers.add(c1); + customers.add(c2); + + this.customersListTableModel.addObjectList(customers); + this.customersListTableModel.fireTableDataChanged(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jScrollPane1 = new javax.swing.JScrollPane(); + jTableCustomers = new javax.swing.JTable(); + jLabel1 = new javax.swing.JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + + jTableCustomers.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); + jTableCustomers.setModel(new javax.swing.table.DefaultTableModel( + new Object [][] { + {null, null, null, null}, + {null, null, null, null}, + {null, null, null, null}, + {null, null, null, null} + }, + new String [] { + "Title 1", "Title 2", "Title 3", "Title 4" + } + )); + jTableCustomers.setIntercellSpacing(new java.awt.Dimension(4, 4)); + jScrollPane1.setViewportView(jTableCustomers); + + jLabel1.setText("Click on any of the names: (close this window when finished)"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(layout.createSequentialGroup() + .addComponent(jLabel1) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the dialog */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + CustomerTableModelJDialog dialog = new CustomerTableModelJDialog(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + dialog.setVisible(true); + } + }); + } + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JLabel jLabel1; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JTable jTableCustomers; + // End of variables declaration//GEN-END:variables + + private ListTableModel customersListTableModel; + private Customer customerSelected; +} diff --git a/src/test/java/com/brosmakingsoftware/swing/LanguageSelectorJDialog.form b/src/test/java/com/brosmakingsoftware/swing/LanguageSelectorJDialog.form new file mode 100644 index 0000000..e8291b0 --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/LanguageSelectorJDialog.form @@ -0,0 +1,89 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/src/test/java/com/brosmakingsoftware/swing/LanguageSelectorJDialog.java b/src/test/java/com/brosmakingsoftware/swing/LanguageSelectorJDialog.java new file mode 100644 index 0000000..120c5b6 --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/LanguageSelectorJDialog.java @@ -0,0 +1,161 @@ +package com.brosmakingsoftware.swing; + +import com.brosmakingsoftware.swing.SwingHelper; +import com.brosmakingsoftware.swing.ListComboBoxModel; +import java.awt.Toolkit; +import java.util.Locale; +import javax.swing.UIManager; + +/** + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftwares + */ +public class LanguageSelectorJDialog extends javax.swing.JDialog { + + /** + * Creates new form LanguageSelectorJDialog + */ + public LanguageSelectorJDialog(java.awt.Frame parent, boolean modal) { + super(parent, modal); + this.languagesListComboBoxModel = new ListComboBoxModel(); + + if (Locale.getDefault().getLanguage().equals("en")) { + System.out.println("Language detected: English"); + this.languagesListComboBoxModel.addElement("English"); + this.languagesListComboBoxModel.addElement("Español"); + } + else { + if (Locale.getDefault().getLanguage().equals("es")) { + System.out.println("Language detected: Spanish"); + this.languagesListComboBoxModel.addElement("Español"); + this.languagesListComboBoxModel.addElement("English"); + } + else{ + System.out.println("Language detected: " + Locale.getDefault().getLanguage()); + System.out.println("No resources available for this language. Loading default one (English)"); + this.languagesListComboBoxModel.addElement("English"); + this.languagesListComboBoxModel.addElement("Español"); + } + } + + initComponents(); + SwingHelper.centerWindow(this); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jLabel1 = new javax.swing.JLabel(); + jComboBox1 = new javax.swing.JComboBox(); + jButtonSelect = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("com/brosmakingsoftware/umd/renamer/ui/resources"); // NOI18N + setTitle(bundle.getString("language_selector_title")); // NOI18N + setAlwaysOnTop(true); + setResizable(false); + + jLabel1.setText(bundle.getString("language_selector")); // NOI18N + + jComboBox1.setModel(this.languagesListComboBoxModel); + + jButtonSelect.setText(bundle.getString("select")); // NOI18N + jButtonSelect.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButtonSelectActionPerformed(evt); + } + }); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(15, 15, 15) + .add(jLabel1)) + .add(layout.createSequentialGroup() + .add(53, 53, 53) + .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 203, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(jButtonSelect))) + .addContainerGap(17, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(17, 17, 17) + .add(jLabel1) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .add(jButtonSelect)) + .addContainerGap(26, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void jButtonSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelectActionPerformed + + String selected = (String) this.languagesListComboBoxModel.getSelectedItem(); + if (selected.equals("English")) { + Locale.setDefault(Locale.ENGLISH); + System.out.println("Language set to English"); + } else { + Locale.setDefault(new Locale("es")); + System.out.println("Language set to Spanish"); + } + + this.dispose(); + + }//GEN-LAST:event_jButtonSelectActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* + * Set the Nimbus look and feel + */ + // + try { + javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(LanguageSelectorJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(LanguageSelectorJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(LanguageSelectorJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(LanguageSelectorJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* + * Create and display the form + */ + LanguageSelectorJDialog dialog = new LanguageSelectorJDialog(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + dialog.setVisible(true); + } + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButtonSelect; + private javax.swing.JComboBox jComboBox1; + private javax.swing.JLabel jLabel1; + // End of variables declaration//GEN-END:variables + private ListComboBoxModel languagesListComboBoxModel; +} diff --git a/src/test/java/com/brosmakingsoftware/swing/ListComboBoxModelTest.java b/src/test/java/com/brosmakingsoftware/swing/ListComboBoxModelTest.java new file mode 100644 index 0000000..b1ddb20 --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/ListComboBoxModelTest.java @@ -0,0 +1,44 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.brosmakingsoftware.swing; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + */ +public class ListComboBoxModelTest { + + public ListComboBoxModelTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test + public void testListComboBoxModel(){ + LanguageSelectorJDialog dialog = new LanguageSelectorJDialog(new javax.swing.JFrame(), true); + dialog.setVisible(true); + } +} \ No newline at end of file diff --git a/src/test/java/com/brosmakingsoftware/swing/ListTableModelTest.java b/src/test/java/com/brosmakingsoftware/swing/ListTableModelTest.java new file mode 100644 index 0000000..0c53464 --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/ListTableModelTest.java @@ -0,0 +1,43 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.brosmakingsoftware.swing; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + */ +public class ListTableModelTest { + + public ListTableModelTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test + public void testListTableModel(){ + CustomerTableModelJDialog dialog = new CustomerTableModelJDialog(new javax.swing.JFrame(), true); + dialog.setVisible(true); + } +} \ No newline at end of file diff --git a/src/test/java/com/brosmakingsoftware/swing/SwingHelperTest.java b/src/test/java/com/brosmakingsoftware/swing/SwingHelperTest.java new file mode 100644 index 0000000..7ba30e9 --- /dev/null +++ b/src/test/java/com/brosmakingsoftware/swing/SwingHelperTest.java @@ -0,0 +1,194 @@ + +package com.brosmakingsoftware.swing; + +import com.brosmakingsoftware.swing.SwingHelper; +import java.io.File; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import static org.junit.Assert.*; + +/** + * @author Diego Hernandez Perez (iampeluca on Github) - BrosMakingSoftware + */ +public class SwingHelperTest { + + public SwingHelperTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @org.junit.Test + public void allTest(){ + testShowConfirmationDialogWithYesNoButtonsYES(); + testShowConfirmationDialogWithYesNoButtonsNO(); + testShowConfirmationDialogWithYesNoCancelButtonsYES(); + testShowConfirmationDialogWithYesNoCancelButtonsNO(); + testShowConfirmationDialogWithYesNoCancelButtonsCANCEL(); + testShowConfirmationDialogWithOkCancelButtonsOK(); + testShowConfirmationDialogWithOkCancelButtonsCANCEL(); + testAskForRequiredTextUsingInputDialog(); + + testChooseDirectory_String_String(); + //testChooseDirectory_String_File(); + testChooseDirectory_String(); + testChooseFile_4args(); + testChooseFile_String(); + //testChooseFile_String_String(); + testSetLookAndFeel(); + } + + public void testShowConfirmationDialogWithYesNoButtonsYES(){ + System.out.println("showConfirmationDialogWithYesNoButtons"); + String title = "Click on a button to confirm"; + String message = "Click on YES button"; + String result = SwingHelper.showConfirmationDialogWithYesNoButtons(title, message); + assertTrue("YES button was not clicked.", result.equals("yes")); + } + + public void testShowConfirmationDialogWithYesNoButtonsNO(){ + System.out.println("showConfirmationDialogWithYesNoButtons"); + String title = "Click on a button to confirm"; + String message = "Click on NO button"; + String result = SwingHelper.showConfirmationDialogWithYesNoButtons(title, message); + assertTrue("NO button was not clicked.", result.equals("no")); + } + + public void testShowConfirmationDialogWithYesNoCancelButtonsYES(){ + System.out.println("showConfirmationDialogWithYesNoCancelButtons"); + String title = "Click on a button to confirm"; + String message = "Click on YES button"; + String result = SwingHelper.showConfirmationDialogWithYesNoCancelButtons(title, message); + assertTrue("YES button was not clicked.", result.equals("yes")); + } + + public void testShowConfirmationDialogWithYesNoCancelButtonsNO(){ + System.out.println("showConfirmationDialogWithYesNoCancelButtons"); + String title = "Click on a button to confirm"; + String message = "Click on NO button"; + String result = SwingHelper.showConfirmationDialogWithYesNoCancelButtons(title, message); + assertTrue("NO button was not clicked.", result.equals("no")); + } + + public void testShowConfirmationDialogWithYesNoCancelButtonsCANCEL(){ + System.out.println("showConfirmationDialogWithYesNoCancelButtons"); + String title = "Click on a button to confirm"; + String message = "Click on CANCEL button"; + String result = SwingHelper.showConfirmationDialogWithYesNoCancelButtons(title, message); + assertTrue("CANCEL button was not clicked.", result.equals("cancel")); + } + + public void testShowConfirmationDialogWithOkCancelButtonsOK(){ + System.out.println("showConfirmationDialogWithYesNoCancelButtons"); + String title = "Click on a button to confirm"; + String message = "Click on OK button"; + String result = SwingHelper.showConfirmationDialogWithOkCancelButtons(title, message); + assertTrue("OK button was not clicked.", result.equals("ok")); + } + + public void testShowConfirmationDialogWithOkCancelButtonsCANCEL(){ + System.out.println("showConfirmationDialogWithYesNoCancelButtons"); + String title = "Click on a button to confirm"; + String message = "Click on CANCEL button"; + String result = SwingHelper.showConfirmationDialogWithOkCancelButtons(title, message); + assertTrue("CANCEL button was not clicked.", result.equals("cancel")); + } + + public void testAskForRequiredTextUsingInputDialog() { + System.out.println("askForRequiredTextUsingInputDialog"); + String result = SwingHelper.askForRequiredTextUsingInputDialog("Required text request", "Write something (not empty):"); + assertNotNull("Text was null", result); + assertFalse("Text was empty", result.trim().equals("")); + } + + public void testChooseDirectory_String_String() { + System.out.println("chooseDirectory"); + String startDirectory = "target/test-classes/com/brosmakingsoftware/swing/"; + File result = SwingHelper.chooseDirectory("Choose a folder", startDirectory); + assertNotNull("Folder selected was null", result); + } + + public void testChooseDirectory_String_File() { + System.out.println("chooseDirectory"); + File startDirectory = new File("target/test-classes/com/brosmakingsoftware/swing/"); + File result = SwingHelper.chooseDirectory("Choose a folder", startDirectory); + assertNotNull("Folder selected was null", result); + } + + public void testChooseDirectory_String() { + System.out.println("chooseDirectory"); + File result = SwingHelper.chooseDirectory("Choose a folder"); + assertNotNull("Folder selected was null", result); + } + + public void testChooseFile_4args() { + System.out.println("chooseFile"); + String title = "Choose a file"; + String startDirectory = "target/test-classes/com/brosmakingsoftware/swing/"; + String fileExtension = ".xml"; + String startFile = "AnXML.xml"; + File result = SwingHelper.chooseFile(title, startDirectory, fileExtension, startFile); + assertNotNull("The file selected was null", result); + } + + public void testChooseFile_String() { + System.out.println("chooseFile"); + File result = SwingHelper.chooseFile("Choose any file"); + assertNotNull("The file selected was null", result); + } + + public void testChooseFile_String_String() { + System.out.println("chooseFile"); + String title = "Choose file"; + String fileExtension = ".txt"; + File result = SwingHelper.chooseFile(title, fileExtension); + assertNotNull("The file selected was null", result); + } + + public void testSetLookAndFeel() { + System.out.println("Testing setLookAndFeel(SwingHelper.LookAndFeel)"); + + SwingHelper.showErrorMessage("Error", "This is an error message using System Look and Feel."); + SwingHelper.showWarningMessage("Warning", "This is a warning message using System Look and Feel"); + SwingHelper.showInformationMessage("Information", "This is an information message using System Look and Feel."); + + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.MOTIF); + SwingHelper.showErrorMessage("Error", "This is an error message using Motif Look and Feel."); + SwingHelper.showWarningMessage("Warning", "This is a warning message using Motif Look and Feel"); + SwingHelper.showInformationMessage("Information", "This is an information message using Motif Look and Feel."); + + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.NIMBUS); + SwingHelper.showErrorMessage("Error", "This is an error message using Nimbus Look and Feel."); + SwingHelper.showWarningMessage("Warning", "This is a warning messag eusing Nimbus Look and Feel"); + SwingHelper.showInformationMessage("Information", "This is an information message using Nimbus Look and Feel."); + + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.METAL); + SwingHelper.setMetalTheme(SwingHelper.MetalTheme.DEFAULT_METAL); + SwingHelper.showErrorMessage("Error", "This is an error message using Metal Look and Feel with Default theme."); + SwingHelper.showWarningMessage("Warning", "This is a warning message using Metal Look and Feel with Default theme."); + SwingHelper.showInformationMessage("Information", "This is an information message using Metal Look and Feel with Default theme."); + + SwingHelper.setMetalTheme(SwingHelper.MetalTheme.OCEAN); + SwingHelper.showErrorMessage("Error", "This is an error message using Metal Look and Feel with Ocean theme."); + SwingHelper.showWarningMessage("Warning", "This is a warning message using Metal Look and Feel with Ocean theme."); + SwingHelper.showInformationMessage("Information", "This is an information message using Metal Look and Feel with Ocean theme."); + + SwingHelper.setLookAndFeel(SwingHelper.LookAndFeel.SYSTEM); + } + +} \ No newline at end of file diff --git a/src/test/log4j.properties b/src/test/log4j.properties new file mode 100755 index 0000000..f02eff9 --- /dev/null +++ b/src/test/log4j.properties @@ -0,0 +1,13 @@ +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +#log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy MM dd, HH:MM:ss}] %5p %c{1}.%M:%L - %m%n +log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy-MM-dd, HH:MM:ss}] %5p - %m%n +log4j.rootLogger=debug,stdout + +#log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender +#log4j.appender.rollingFile.File=D:/gpg-helper.log +#log4j.appender.rollingFile.MaxFileSize=2MB +#log4j.appender.rollingFile.MaxBackupIndex=2 +#log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout +#log4j.appender.rollingFile.layout.ConversionPattern=%p %t %c - %m%n \ No newline at end of file diff --git a/src/test/resources/com/brosmakingsoftware/swing/AnXML.xml b/src/test/resources/com/brosmakingsoftware/swing/AnXML.xml new file mode 100755 index 0000000..e69de29 diff --git a/src/test/resources/com/brosmakingsoftware/swing/MyLittleFile.txt b/src/test/resources/com/brosmakingsoftware/swing/MyLittleFile.txt new file mode 100755 index 0000000..0338cd6 --- /dev/null +++ b/src/test/resources/com/brosmakingsoftware/swing/MyLittleFile.txt @@ -0,0 +1,8 @@ +Hi! + + + + + + +Bye! \ No newline at end of file diff --git a/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources.properties b/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources.properties new file mode 100755 index 0000000..53f9e16 --- /dev/null +++ b/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources.properties @@ -0,0 +1,34 @@ +id=Id +title=Title +version=Version +firmware=Firmware +psp_game_information=PSP Game Information +psp_game_icon=PSP Game Icon +list_of_psp_games=List of PSP Games +actual_folder=Actual folder +no_folder_selected= +change_folder=Change folder +use_title_changes=Use "Title" changes +old_filename=Old filename +new_filename=New filename +language_selector_title=UMD FileRenamer - Language Selector +language_selector=Please select the language you want to use for this application +select=Select +select_folder_containing_images=Select the folder that contains the images files +error_opening_file=Error opening file +warning=Warning +folder_does_not_contain_psp_images=This folder does not contain PSP image files +rename_all=Rename all the files +chars_replaced_title=Characters replaced +chars_replaced=Some characters where replaced to avoid file system problems. +files_rename_sucess_title=All files renamed! +files_rename_sucess=All the files were renamed successfully! +error_renaming_files=Error renaming files +app_do_not_change_game_properties=Note: This application does not change the properties inside the PSP Game. Any change in this table is only reflected on the file names. +author=Author +description=Description +description_about=This application reads ISO or CSO files and extract their information to generate a recognized and standard file name, but not changing the properties inside the PSP games.\nSome classes of jpcsp project are used, jpcsp is an open source Java emulator of Playstation Portable console system. See http://jpcsp.org/ for more information, code can be downloaded from http://code.google.com/p/jpcsp/\nThis application is partially based and inspired on UmdBrowser (http://code.google.com/p/jumdbrowser/), an application to list and navigate into UMD images. +file=File +exit=Exit +help=Help +about=About diff --git a/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources_en.properties b/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources_en.properties new file mode 100755 index 0000000..53f9e16 --- /dev/null +++ b/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources_en.properties @@ -0,0 +1,34 @@ +id=Id +title=Title +version=Version +firmware=Firmware +psp_game_information=PSP Game Information +psp_game_icon=PSP Game Icon +list_of_psp_games=List of PSP Games +actual_folder=Actual folder +no_folder_selected= +change_folder=Change folder +use_title_changes=Use "Title" changes +old_filename=Old filename +new_filename=New filename +language_selector_title=UMD FileRenamer - Language Selector +language_selector=Please select the language you want to use for this application +select=Select +select_folder_containing_images=Select the folder that contains the images files +error_opening_file=Error opening file +warning=Warning +folder_does_not_contain_psp_images=This folder does not contain PSP image files +rename_all=Rename all the files +chars_replaced_title=Characters replaced +chars_replaced=Some characters where replaced to avoid file system problems. +files_rename_sucess_title=All files renamed! +files_rename_sucess=All the files were renamed successfully! +error_renaming_files=Error renaming files +app_do_not_change_game_properties=Note: This application does not change the properties inside the PSP Game. Any change in this table is only reflected on the file names. +author=Author +description=Description +description_about=This application reads ISO or CSO files and extract their information to generate a recognized and standard file name, but not changing the properties inside the PSP games.\nSome classes of jpcsp project are used, jpcsp is an open source Java emulator of Playstation Portable console system. See http://jpcsp.org/ for more information, code can be downloaded from http://code.google.com/p/jpcsp/\nThis application is partially based and inspired on UmdBrowser (http://code.google.com/p/jumdbrowser/), an application to list and navigate into UMD images. +file=File +exit=Exit +help=Help +about=About diff --git a/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources_es.properties b/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources_es.properties new file mode 100755 index 0000000..61c3988 --- /dev/null +++ b/src/test/resources/com/brosmakingsoftware/umd/renamer/ui/resources_es.properties @@ -0,0 +1,34 @@ +id=Id +title=T\u00edtulo +version=Versi\u00f3n +firmware=Firmware +psp_game_information=Informaci\u00f3n del juego PSP +psp_game_icon=Icono del juego PSP +list_of_psp_games=Lista de juegos PSP +actual_folder=Folder actual +no_folder_selected= +change_folder=Cambiar folder +use_title_changes=Usar el "T\u00edtulo" cambiado +old_filename=Nombre de archivo viejo +new_filename=Nombre de archivo nuevo +language_selector_title=UMD FileRenamer - Selector de idioma +language_selector=Por favor seleccione el idioma que desea utilizar +select=Seleccionar +select_folder_containing_images=Seleccionie el folder que contiene los archivos de im\u00e1genes +error_opening_file=Error abriendo archivo +warning=Advertencia +folder_does_not_contain_psp_images=Este folder no contiene archivos de im\u00e1genes de PSP +rename_all=Renombrar todos los archivos +chars_replaced_title=Caracteres reemplazados +chars_replaced=Algunos caracteres fueron reemplazados para evitar problemas con el sistema de archivos. +files_rename_sucess_title=\u00a1Todos los archivos fueron renombrados! +files_rename_sucess=\u00a1Todos los archivos fueron renombrados exit\u00f3samente! +error_renaming_files=Error renombrando los archivos +app_do_not_change_game_properties=Nota: Esta aplicaci\u00f3n no cambia las propiedades de los juegos PSP. Cualquier cambio hecho en la tabla s\u00f3lamente se ve reflejado en los nombres de los archivos. +author=Autor +description=Descripci\u00f3n +description_about=Esta aplicaci\u00f3n lee archivos ISO y CSO y extrae su informaci\u00f3n para generar un nombre de archivo reconocido y estandarizado sin cambiar las propiedades del juego de PSP.\nAlgunas clases del projecto jpcsp son usas, este es un emulador de c\u00f3digo libre escrito en Java de consola Playstation Portable. Para m\u00e1s informaci\u00f3n, la p\u00e1gina oficial es http://jpcsp.org/ y el c\u00f3digo se puede descargar de http://code.google.com/p/jpcsp/\nEsta aplicaci\u00f3n es parcialmente basada e inspirada en el projecto UmdBrowser (http://code.google.com/p/jumdbrowser/), una aplicaci\u00f3n para listar y navegar dento de im\u00e1genes UMD. +file=Archivo +exit=Salir +help=Ayuda +about=Sobre la aplicaci\u00f3n