Java tutorial
/* * Copyright 2016 Maugre Lucas * * 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. */ package maps; import java.io.*; import org.apache.commons.cli.*; public class OptionsHandler { static private Options options = new Options(); static private int tileWidth = 16; static private int tileHeight = 16; static private File file = null; static int getTileWidth() { return tileWidth; } static int getTileHeight() { return tileHeight; } static File getFile() { return file; } static { options.addOption("w", "width", true, "set tile width (default: 16)"); options.addOption("h", "height", true, "set tile height (default: 16)"); options.addOption("f", "file", true, "select the file, will disable GUI"); options.addOption("H", "help", false, "print this help"); } static private void checkOptions(CommandLine cmd) { if (cmd.hasOption("w")) setWidthOption(cmd.getOptionValue("w")); if (cmd.hasOption("h")) setHeightOption(cmd.getOptionValue("h")); if (cmd.hasOption("f")) setFileOption(cmd.getOptionValue("f")); if (cmd.hasOption("H")) printHelpOption(); } static void applyOptions(String[] args) { try { CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); checkOptions(cmd); } catch (ParseException e) { System.err.println("Error in options: " + e.toString()); printHelpOption(); } } static private void printHelpOption() { System.out.println("Usage:"); for (Option o : options.getOptions()) System.out.println(String.format("\t-%s --%s\t%s", o.getOpt(), o.getLongOpt(), o.getDescription())); System.exit(0); } static private void setWidthOption(String arg) { tileWidth = Integer.parseInt(arg); } static private void setHeightOption(String arg) { tileHeight = Integer.parseInt(arg); } static private void setFileOption(String arg) { file = new File(arg); if (!file.exists()) { System.err.println("File '" + arg + "' does not exists."); System.exit(1); } } }