diff --git a/resources/plugins/05/B-Human/src/bhuman/gui/BHumanDetailFrame.java b/resources/plugins/05/B-Human/src/bhuman/gui/BHumanDetailFrame.java index 43841ff6..7a520b1b 100644 --- a/resources/plugins/05/B-Human/src/bhuman/gui/BHumanDetailFrame.java +++ b/resources/plugins/05/B-Human/src/bhuman/gui/BHumanDetailFrame.java @@ -8,10 +8,8 @@ import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.util.Enumeration; import java.util.List; import java.util.Map; -import java.util.Set; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; @@ -102,12 +100,9 @@ protected void init(final RobotState robot) { @Override public void robotStateChanged(final RobotStateEvent e) { if (isVisible()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - update((RobotState) e.getSource()); - repaint(); - } + SwingUtilities.invokeLater(() -> { + update((RobotState) e.getSource()); + repaint(); }); } } @@ -117,7 +112,7 @@ public void run() { */ private void update(final RobotState robot) { final SPLTeamMessage msg = robot.getLastTeamMessage(); - if (msg == null || !BHumanMessage.class.isInstance(msg)) { + if (!BHumanMessage.class.isInstance(msg)) { return; } final BHumanMessage bmsg = (BHumanMessage) msg; diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/ArrayReader.java b/resources/plugins/05/B-Human/src/bhuman/message/data/ArrayReader.java index 72ac5298..178e1b73 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/ArrayReader.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/ArrayReader.java @@ -1,6 +1,8 @@ package bhuman.message.data; import common.Log; + +import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; /** @@ -45,8 +47,12 @@ public T[] read(final ByteBuffer stream) { array[i] = reader.read(stream); } else { try { - array[i] = readerClass.newInstance().read(stream); - } catch (InstantiationException | IllegalAccessException ex) { + array[i] = readerClass.getConstructor().newInstance().read(stream); + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { Log.error("Failed to instantiate reader class " + readerClass.getName()); } } @@ -57,13 +63,13 @@ public T[] read(final ByteBuffer stream) { @Override public int getStreamedSize(final ByteBuffer stream) { try { - if (reader != null && SimpleStreamReader.class.isInstance(reader)) { + if (SimpleStreamReader.class.isInstance(reader)) { return array.length * ((SimpleStreamReader) reader).getStreamedSize(); } else if (readerClass != null && SimpleStreamReader.class.isAssignableFrom(readerClass)) { - return array.length * ((SimpleStreamReader) readerClass.newInstance()).getStreamedSize(); + return array.length * ((SimpleStreamReader) readerClass.getConstructor().newInstance()).getStreamedSize(); } - final ComplexStreamReader reader = (ComplexStreamReader) (this.reader != null ? this.reader : readerClass.newInstance()); + final ComplexStreamReader reader = (ComplexStreamReader) (this.reader != null ? this.reader : readerClass.getConstructor().newInstance()); if (ProbablySimpleStreamReader.class.isInstance(reader) && ProbablySimpleStreamReader.class.cast(reader).isSimpleStreamReader()) { return array.length * reader.getStreamedSize(stream); } @@ -83,7 +89,11 @@ public int getStreamedSize(final ByteBuffer stream) { } stream.position(position); return size; - } catch (InstantiationException | IllegalAccessException ex) { + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { Log.error("Failed to instantiate reader class " + readerClass.getName()); return 0; } @@ -93,8 +103,12 @@ public int getStreamedSize(final ByteBuffer stream) { public boolean isSimpleStreamReader() { final StreamReader reader; try { - reader = this.reader != null ? this.reader : readerClass.newInstance(); - } catch (InstantiationException | IllegalAccessException ex) { + reader = this.reader != null ? this.reader : readerClass.getConstructor().newInstance(); + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { Log.error("Cannot instantiate reader class " + readerClass.getName()); return false; } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/BitStream.java b/resources/plugins/05/B-Human/src/bhuman/message/data/BitStream.java index bdb2bc6a..d48d6903 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/BitStream.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/BitStream.java @@ -10,7 +10,7 @@ */ public class BitStream { - private ByteBuffer source; + private final ByteBuffer source; private short currentByte; private long offset = 0; @@ -25,7 +25,7 @@ public long readBits(long bits) { currentByte = Unsigned.toUnsigned(source.get()); } if((currentByte & (1 << (offset % 8))) != 0) { - result |= (1 << i); + result |= (1L << i); } } return result; diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/ComplexStreamReader.java b/resources/plugins/05/B-Human/src/bhuman/message/data/ComplexStreamReader.java index 5a089b7a..0ee50b86 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/ComplexStreamReader.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/ComplexStreamReader.java @@ -17,5 +17,5 @@ public interface ComplexStreamReader extends StreamReader { * @param stream stream to read from * @return size in bytes */ - public int getStreamedSize(final ByteBuffer stream); + int getStreamedSize(final ByteBuffer stream); } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/EnumMapReader.java b/resources/plugins/05/B-Human/src/bhuman/message/data/EnumMapReader.java index 1f7d444a..6a8ed06a 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/EnumMapReader.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/EnumMapReader.java @@ -1,6 +1,8 @@ package bhuman.message.data; import common.Log; + +import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.util.EnumMap; @@ -30,8 +32,12 @@ public EnumMapReader(final Class enumclass, final StreamReader reader) { public boolean isSimpleStreamReader() { final StreamReader reader; try { - reader = this.reader != null ? this.reader : readerclass.newInstance(); - } catch (InstantiationException | IllegalAccessException ex) { + reader = this.reader != null ? this.reader : readerclass.getConstructor().newInstance(); + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { Log.error("Cannot instantiate reader class " + readerclass.getName()); return false; } @@ -46,8 +52,12 @@ public int getStreamedSize(final ByteBuffer stream) { final StreamReader reader; try { - reader = this.reader != null ? this.reader : readerclass.newInstance(); - } catch (InstantiationException | IllegalAccessException ex) { + reader = this.reader != null ? this.reader : readerclass.getConstructor().newInstance(); + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { Log.error("Cannot instantiate reader class " + readerclass.getName()); return count; } @@ -83,8 +93,12 @@ public EnumMap read(final ByteBuffer stream) { map.put(key, reader.read(stream)); } else { try { - map.put(key, readerclass.newInstance().read(stream)); - } catch (InstantiationException | IllegalAccessException ex) { + map.put(key, readerclass.getConstructor().newInstance().read(stream)); + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { Log.error("Failed to instantiate reader class " + readerclass.getName()); } } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/ListReader.java b/resources/plugins/05/B-Human/src/bhuman/message/data/ListReader.java index ceee4430..5b8e66c7 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/ListReader.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/ListReader.java @@ -1,6 +1,8 @@ package bhuman.message.data; import common.Log; + +import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -71,8 +73,12 @@ public List read(final ByteBuffer stream) { elems.add(reader.read(stream)); } else { try { - elems.add(readerClass.newInstance().read(stream)); - } catch (InstantiationException | IllegalAccessException ex) { + elems.add(readerClass.getConstructor().newInstance().read(stream)); + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { } } } @@ -83,13 +89,13 @@ public List read(final ByteBuffer stream) { public int getStreamedSize(final ByteBuffer stream) { final int count = getElementCount(stream); try { - if (reader != null && SimpleStreamReader.class.isInstance(reader)) { + if (SimpleStreamReader.class.isInstance(reader)) { return listCountSize + count * ((SimpleStreamReader) reader).getStreamedSize(); } else if (readerClass != null && SimpleStreamReader.class.isAssignableFrom(readerClass)) { - return listCountSize + count * ((SimpleStreamReader) readerClass.newInstance()).getStreamedSize(); + return listCountSize + count * ((SimpleStreamReader) readerClass.getConstructor().newInstance()).getStreamedSize(); } - final ComplexStreamReader reader = (ComplexStreamReader) (this.reader != null ? this.reader : readerClass.newInstance()); + final ComplexStreamReader reader = (ComplexStreamReader) (this.reader != null ? this.reader : readerClass.getConstructor().newInstance()); if (ProbablySimpleStreamReader.class.isInstance(reader) && ProbablySimpleStreamReader.class.cast(reader).isSimpleStreamReader()) { return listCountSize + count * reader.getStreamedSize(stream); } @@ -110,7 +116,11 @@ public int getStreamedSize(final ByteBuffer stream) { } stream.position(position); return size; - } catch (InstantiationException | IllegalAccessException ex) { + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException + | NullPointerException ex) { Log.error("Failed to instantiate reader class " + readerClass.getName()); return 0; } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/NativeReaders.java b/resources/plugins/05/B-Human/src/bhuman/message/data/NativeReaders.java index c0e11ff4..c86f33e8 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/NativeReaders.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/NativeReaders.java @@ -1,8 +1,8 @@ package bhuman.message.data; -import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import util.Unsigned; @@ -286,15 +286,7 @@ public String read(final ByteBuffer stream) { final int size = stream.getInt(); final byte[] bytes = new byte[size]; stream.get(bytes); - try { - return new String(bytes, "ISO-8859-1"); - } catch (UnsupportedEncodingException ex) { - try { - return new String(bytes, "US-ASCII"); - } catch (UnsupportedEncodingException e) { - return new String(bytes); - } - } + return new String(bytes, StandardCharsets.ISO_8859_1); } } @@ -319,15 +311,7 @@ public int getStreamedSize() { public String read(final ByteBuffer stream) { final byte[] bytes = new byte[count]; stream.get(bytes); - try { - return new String(bytes, "ISO-8859-1"); - } catch (UnsupportedEncodingException ex) { - try { - return new String(bytes, "US-ASCII"); - } catch (UnsupportedEncodingException e) { - return new String(bytes); - } - } + return new String(bytes, StandardCharsets.ISO_8859_1); } } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/ProbablySimpleStreamReader.java b/resources/plugins/05/B-Human/src/bhuman/message/data/ProbablySimpleStreamReader.java index f5c07100..6d4bd62d 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/ProbablySimpleStreamReader.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/ProbablySimpleStreamReader.java @@ -14,5 +14,5 @@ public interface ProbablySimpleStreamReader extends ComplexStreamReader { * * @return bool */ - public boolean isSimpleStreamReader(); + boolean isSimpleStreamReader(); } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/SimpleStreamReader.java b/resources/plugins/05/B-Human/src/bhuman/message/data/SimpleStreamReader.java index dcedbfe9..04c10d7d 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/SimpleStreamReader.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/SimpleStreamReader.java @@ -14,5 +14,5 @@ public interface SimpleStreamReader extends StreamReader { * * @return size in bytes */ - public int getStreamedSize(); + int getStreamedSize(); } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/StreamReader.java b/resources/plugins/05/B-Human/src/bhuman/message/data/StreamReader.java index d4bab202..ad983a92 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/StreamReader.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/StreamReader.java @@ -16,5 +16,5 @@ public interface StreamReader { * @param stream stream to read from * @return object */ - public T read(final ByteBuffer stream); + T read(final ByteBuffer stream); } diff --git a/resources/plugins/05/B-Human/src/bhuman/message/data/StreamedObject.java b/resources/plugins/05/B-Human/src/bhuman/message/data/StreamedObject.java index 09c2b54a..a5949076 100644 --- a/resources/plugins/05/B-Human/src/bhuman/message/data/StreamedObject.java +++ b/resources/plugins/05/B-Human/src/bhuman/message/data/StreamedObject.java @@ -1,11 +1,8 @@ package bhuman.message.data; import common.Log; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; + +import java.lang.reflect.*; import java.nio.ByteBuffer; import java.util.EnumMap; import java.util.HashMap; @@ -83,7 +80,7 @@ protected StreamReader getFieldReader(final Field field) { final Reader reader = field.getAnnotation(Reader.class); final Primitive primitive = field.getAnnotation(Primitive.class); if (reader != null) { - return reader.value().newInstance(); + return reader.value().getConstructor().newInstance(); } else if (primitive != null) { try { final Field readerField = NativeReaders.class.getField(primitive.value().toLowerCase() + "Reader"); @@ -99,7 +96,7 @@ protected StreamReader getFieldReader(final Field field) { if (nativeReader != null) { return nativeReader; } else if (StreamReader.class.isAssignableFrom(type)) { - return (StreamReader) type.newInstance(); + return (StreamReader) type.getConstructor().newInstance(); } else if (Enum.class.isAssignableFrom(type)) { return new EnumReader(type); } else if (EnumMap.class.isAssignableFrom(type)) { @@ -134,7 +131,7 @@ protected StreamReader getFieldReader(final Field field) { Log.error("field " + field.getName() + " in class " + getClass().getName() + " could not be read automatically"); } } - return new ListReader(componentReader, listCountSize); + return new ListReader<>(componentReader, listCountSize); } catch (ClassNotFoundException ex) { Log.error("field " + field.getName() + " in class " + getClass().getName() + " could not be read automatically because the type was not found"); } @@ -156,7 +153,10 @@ protected StreamReader getFieldReader(final Field field) { } } } - } catch (IllegalAccessException | InstantiationException ex) { + } catch (IllegalAccessException + | InstantiationException + | InvocationTargetException + | NoSuchMethodException ex) { Log.error("Could not get reader for field " + field.getName() + " of class " + getClass().getName()); } return null; diff --git a/resources/plugins/05/B-Human/src/util/Unsigned.java b/resources/plugins/05/B-Human/src/util/Unsigned.java index 0f2c77e4..2ef96994 100644 --- a/resources/plugins/05/B-Human/src/util/Unsigned.java +++ b/resources/plugins/05/B-Human/src/util/Unsigned.java @@ -34,6 +34,6 @@ public static int toUnsigned(final short s) { * @return unsigned value */ public static long toUnsigned(final int i) { - return i < 0 ? i + (1l << (long) Integer.SIZE) : i; + return i < 0 ? i + (1L << (long) Integer.SIZE) : i; } } diff --git a/src/common/ApplicationLock.java b/src/common/ApplicationLock.java index aa857654..c4fe0488 100644 --- a/src/common/ApplicationLock.java +++ b/src/common/ApplicationLock.java @@ -13,16 +13,16 @@ */ public class ApplicationLock { /** The lockFile. */ - private File lockFile = null; + private final File lockFile; /** The acquire. */ - private FileLock lock = null; + private FileLock lock; /** The lockChannel. */ - private FileChannel lockChannel = null; + private FileChannel lockChannel; /** The lockStream. */ - private FileOutputStream lockStream = null; + private FileOutputStream lockStream; /** * Creates a new ApplicationLock instance. diff --git a/src/common/Log.java b/src/common/Log.java index 236333dc..f6c8c129 100644 --- a/src/common/Log.java +++ b/src/common/Log.java @@ -1,7 +1,7 @@ package common; import data.AdvancedData; -import java.io.File; + import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -23,16 +23,16 @@ public class Log { /** The instance of the singleton. */ - private static Log instance = new Log(); + private static final Log instance = new Log(); /** The file to write into. */ private FileWriter file; /** The error-file to write into. */ private FileWriter errorFile; /** The file to write into. */ - private String errorPath = "error.txt"; + private final String errorPath = "error.txt"; /** The timeline. */ - private LinkedList states = new LinkedList(); + private final LinkedList states = new LinkedList<>(); /** If != null, the next log entry will use this message. */ private String message = null; @@ -55,7 +55,7 @@ public synchronized static void init(String path) throw new IllegalStateException("logger already initialized"); } try{ - instance.file = new FileWriter(new File(path)); + instance.file = new FileWriter(path); } catch (IOException e) { error("cannot write to logfile "+path); } @@ -63,11 +63,11 @@ public synchronized static void init(String path) // Write version number if application is GameController try { toFile((String)Class.forName("controller.GameController").getField("version").get(null)); - } catch (ClassNotFoundException ex) { - } catch (NoSuchFieldException ex) { - } catch (SecurityException ex) { - } catch (IllegalArgumentException ex) { - } catch (IllegalAccessException ex) { + } catch (ClassNotFoundException + | NoSuchFieldException + | SecurityException + | IllegalArgumentException + | IllegalAccessException ex) { } } @@ -201,13 +201,13 @@ public static String goBack(AdvancedData data, int states) try { final Class eventHandlerClass = Class.forName("controller.EventHandler"); eventHandlerClass.getField("data").set(eventHandlerClass.getMethod("getInstance").invoke(null), state); - } catch (ClassNotFoundException ex) { - } catch (NoSuchFieldException ex) { - } catch (SecurityException ex) { - } catch (IllegalArgumentException ex) { - } catch (IllegalAccessException ex) { - } catch (NoSuchMethodException ex) { - } catch (InvocationTargetException ex) { + } catch (ClassNotFoundException + | NoSuchFieldException + | SecurityException + | IllegalArgumentException + | IllegalAccessException + | NoSuchMethodException + | InvocationTargetException ex) { } return state.message; } @@ -246,7 +246,7 @@ public static void error(String s) System.err.println(s); try{ if (instance.errorFile == null) { - instance.errorFile = new FileWriter(new File(instance.errorPath)); + instance.errorFile = new FileWriter(instance.errorPath); } instance.errorFile.write(timestampFormat.format(new Date(System.currentTimeMillis()))+": "+s+"\n"); instance.errorFile.flush(); diff --git a/src/common/net/GameControlReturnDataReceiver.java b/src/common/net/GameControlReturnDataReceiver.java index 78f95b47..18da4969 100644 --- a/src/common/net/GameControlReturnDataReceiver.java +++ b/src/common/net/GameControlReturnDataReceiver.java @@ -10,8 +10,6 @@ import java.net.InetSocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; @@ -44,11 +42,8 @@ private class ReceiverThread extends Thread { * @param address the InetAddress to listen on. If null, listens on any address. * @param forwarded whether this thread should received forwarded packets (from GC) instead of the original ones * @throws SocketException if an error occurs while creating the socket - * @throws UnknownHostException if (internally chosen) inet-address is not - * valid or no network device is bound to an address matching the regex - * (ignoring loopback interfaces) */ - public ReceiverThread(final InetAddress address, boolean forwarded) throws SocketException, UnknownHostException { + public ReceiverThread(final InetAddress address, boolean forwarded) throws SocketException { setName("GameControlReturnDataReceiver"); this.forwarded = forwarded; @@ -103,11 +98,8 @@ public void run() { * @param address the InetAddress to listen on. If null, listens on any address. * @param generateIP Generate a sender IP based on data in return packet. * @throws SocketException if an error occurs while creating the socket - * @throws UnknownHostException if (internally chosen) inet-address is not - * valid or no network device is bound to an address matching the regex - * (ignoring loopback interfaces) */ - public GameControlReturnDataReceiver(final InetAddress address, boolean generateIP) throws SocketException, UnknownHostException { + public GameControlReturnDataReceiver(final InetAddress address, boolean generateIP) throws SocketException { // Create receiver thread receiver = new ReceiverThread(address, false); this.generateIP = generateIP; @@ -117,11 +109,8 @@ public GameControlReturnDataReceiver(final InetAddress address, boolean generate * Creates a new Receiver for forwarded messages. * * @throws SocketException if an error occurs while creating the socket - * @throws UnknownHostException if (internally chosen) inet-address is not - * valid or no network device is bound to an address matching the regex - * (ignoring loopback interfaces) */ - public GameControlReturnDataReceiver() throws SocketException, UnknownHostException { + public GameControlReturnDataReceiver() throws SocketException { // Create receiver thread receiver = new ReceiverThread(null, true); generateIP = false; diff --git a/src/common/net/logging/Logger.java b/src/common/net/logging/Logger.java index e8b79393..316f0e0c 100644 --- a/src/common/net/logging/Logger.java +++ b/src/common/net/logging/Logger.java @@ -5,10 +5,10 @@ import common.net.GameControlReturnDataPackage; import data.GameControlData; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; +import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Date; @@ -161,7 +161,7 @@ public void log(final Class cls, final T p) { // Open stream if needed if (logger == null) { try { - logger = new ObjectOutputStream(new FileOutputStream(logFile)); + logger = new ObjectOutputStream(Files.newOutputStream(logFile.toPath())); } catch (IOException ex) { Log.error("error while opening logfile: " + ex.getMessage()); error = true; diff --git a/src/data/AdvancedData.java b/src/data/AdvancedData.java index aa0c5139..83189623 100644 --- a/src/data/AdvancedData.java +++ b/src/data/AdvancedData.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.util.Arrays; /** * This class extends the GameControlData that is send to the robots. It @@ -62,43 +63,43 @@ public class AdvancedData extends GameControlData implements Cloneable { /** * When was each player penalized last (ms, 0 = never)? */ - public long[][] whenPenalized = new long[2][Rules.league.teamSize]; + public final long[][] whenPenalized = new long[2][Rules.league.teamSize]; /** * How often was each team penalized? */ - public int[] penaltyCount = new int[2]; + public final int[] penaltyCount = new int[2]; /** * How often was each team penalized at before the robot got penalized? */ - public int[][] robotPenaltyCount = new int[2][Rules.league.teamSize]; + public final int[][] robotPenaltyCount = new int[2][Rules.league.teamSize]; /** * How many hardware penalties can each robot get until it is ejected? */ - public int[][] robotHardwarePenaltyBudget = new int[2][Rules.league.teamSize]; + public final int[][] robotHardwarePenaltyBudget = new int[2][Rules.league.teamSize]; /** * Which players are already ejected? */ - public boolean[][] ejected = new boolean[2][Rules.league.teamSize]; + public final boolean[][] ejected = new boolean[2][Rules.league.teamSize]; /** * Did the team send too many messages so that its score is set to 0 forever? */ - public boolean[] sentIllegalMessages = {false, false}; + public final boolean[] sentIllegalMessages = {false, false}; /** * If true, the referee set a timeout */ - public boolean refereeTimeout = false; + public final boolean refereeTimeout = false; /** * If true, this team is currently taking a timeOut, 0:left side, 1:right * side. */ - public boolean[] timeOutActive = {false, false}; + public final boolean[] timeOutActive = {false, false}; /** * TimeOut counters for each team, 0:left side, 1:right side. @@ -118,12 +119,12 @@ public class AdvancedData extends GameControlData implements Cloneable { /** * If true, the clock has manually been paused in the testmode. */ - public boolean manPause = false; + public final boolean manPause = false; /** * If true, the clock has manually been started in the testmode. */ - public boolean manPlay = false; + public final boolean manPlay = false; /** * When was the last manual intervention to the clock? @@ -141,14 +142,14 @@ public class AdvancedData extends GameControlData implements Cloneable { public long manRemainingGameTimeOffset; /** - * Used to backup the game phase during a timeout. + * Used to back up the game phase during a timeout. */ - public byte previousGamePhase = GAME_PHASE_NORMAL; + public final byte previousGamePhase = GAME_PHASE_NORMAL; /** * The kicking team before the last goal. */ - public byte kickingTeamBeforeGoal = 0; + public final byte kickingTeamBeforeGoal = 0; public static final byte KICKOFF_HALF = 0; public static final byte KICKOFF_TIMEOUT = 1; @@ -353,9 +354,7 @@ public Integer getRemainingPauseTime() { */ public void resetPenaltyTimes() { for (long[] players : whenPenalized) { - for (int i = 0; i < players.length; ++i) { - players[i] = 0; - } + Arrays.fill(players, 0); } } diff --git a/src/data/GameControlData.java b/src/data/GameControlData.java index b644d5ac..da9201b7 100644 --- a/src/data/GameControlData.java +++ b/src/data/GameControlData.java @@ -109,7 +109,7 @@ public class GameControlData implements Serializable { public byte kickingTeam; // the next team to kick off public short secsRemaining = (short) Rules.league.halfTime; // estimate of number of seconds remaining in the half public short secondaryTime = 0; // sub-time (remaining in ready state etc.) in seconds - public TeamInfo[] team = new TeamInfo[2]; + public final TeamInfo[] team = new TeamInfo[2]; /** * Creates a new GameControlData. diff --git a/src/data/GameControlReturnData.java b/src/data/GameControlReturnData.java index f0431cb6..b4bba48d 100644 --- a/src/data/GameControlReturnData.java +++ b/src/data/GameControlReturnData.java @@ -48,7 +48,7 @@ public class GameControlReturnData implements Serializable { // +ve x-axis points towards the goal we are attempting to score on // +ve y-axis is 90 degrees counter clockwise from the +ve x-axis // angle in radians, 0 along the +x axis, increasing counter clockwise - public float[] pose = new float[3]; // x,y,theta + public final float[] pose = new float[3]; // x,y,theta // ball information public float ballAge; // seconds since this robot last saw the ball. -1.f if we haven't seen it @@ -58,7 +58,7 @@ public class GameControlReturnData implements Serializable { // 0,0 is in centre of the robot // +ve x-axis points forward from the robot // +ve y-axis is 90 degrees counter clockwise from the +ve x-axis - public float[] ball = new float[2]; + public final float[] ball = new float[2]; public boolean valid = false; public boolean headerValid = false; diff --git a/src/data/SPL.java b/src/data/SPL.java index 8d005727..c033da9d 100644 --- a/src/data/SPL.java +++ b/src/data/SPL.java @@ -11,91 +11,91 @@ public class SPL extends Rules { SPL() { - /** The league's name this rules are for. */ + /* The league's name this rules are for. */ leagueName = "SPL"; - /** The league's directory name with its teams and icons. */ + /* The league's directory name with its teams and icons. */ leagueDirectory = "spl"; - /** How many robots are in a team. */ + /* How many robots are in a team. */ teamSize = 6; // 5 players + 1 sub - /** How many robots of each team may play at one time. */ + /* How many robots of each team may play at one time. */ robotsPlaying = 5; - /** The Java Colors the left and the right team starts with. */ + /* The Java Colors the left and the right team starts with. */ teamColor = new Color[] {Color.BLUE, Color.RED, new Color(224, 200, 0), Color.BLACK, Color.WHITE, new Color(0, 192, 0), new Color(255, 165, 0), new Color(128, 0, 128), new Color(165, 42, 42), new Color(128, 128, 128)}; - /** The name of the colors. */ + /* The name of the colors. */ teamColorName = new String[] {"Blue", "Red", "Yellow", "Black", "White", "Green", "Orange", "Purple", "Brown", "Gray"}; - /** If the clock may stop in certain states (Ready, Set) in a play-off game. */ + /* If the clock may stop in certain states (Ready, Set) in a play-off game. */ playOffTimeStop = true; - /** Time in seconds one half is long. */ + /* Time in seconds one half is long. */ halfTime = 10*60; - /** Time in seconds the ready state is long. */ + /* Time in seconds the ready state is long. */ readyTime = 45; - /** Time in seconds between first and second half. */ + /* Time in seconds between first and second half. */ pauseTime = 10*60; - /** If left and right side may both have the first kickoff. */ + /* If left and right side may both have the first kickoff. */ kickoffChoice = false; - /** Time in seconds the ball is blocked after kickoff. */ + /* Time in seconds the ball is blocked after kickoff. */ kickoffTime = 10; - /** Time in seconds the ball is blocked after a free kick. */ + /* Time in seconds the ball is blocked after a free kick. */ freeKickTime = 30; - /** Time in seconds the the ready state during a penalty kick is long. */ + /* Time in seconds the ready state during a penalty kick is long. */ penaltyKickReadyTime = 30; - /** Time in seconds before a global game stuck can be called. */ + /* Time in seconds before a global game stuck can be called. */ minDurationBeforeStuck = 30; - /** The number of seconds switching to Playing is delayed. */ + /* The number of seconds switching to Playing is delayed. */ delayedSwitchToPlaying = 15; - /** The number of seconds switching to Ready after a goal is delayed. */ + /* The number of seconds switching to Ready after a goal is delayed. */ delayedSwitchAfterGoal = 15; - /** If there is an overtime before penalty-shoot in a play-off game. */ + /* If there is an overtime before penalty-shoot in a play-off game. */ overtime = false; - /** Time in seconds one overtime half is long. */ + /* Time in seconds one overtime half is long. */ overtimeTime = 0; - /** If the game starts with penalty-shoots. */ + /* If the game starts with penalty-shoots. */ startWithPenalty = false; - /** Time in seconds between second half and penalty shoot. */ + /* Time in seconds between second half and penalty shoot. */ pausePenaltyShootOutTime = 0; - /** Time in seconds one penalty shoot is long. */ + /* Time in seconds one penalty shoot is long. */ penaltyShotTime = 30; - /** If there can be a penalty-shoot retry. */ + /* If there can be a penalty-shoot retry. */ penaltyShotRetries = false; - /** If there is a sudden-death. */ + /* If there is a sudden-death. */ suddenDeath = true; - /** Time in seconds one penalty shoot is long in sudden-death. */ + /* Time in seconds one penalty shoot is long in sudden-death. */ penaltyShotTimeSuddenDeath = 30; - /** Number of penalty-shots for each team. */ + /* Number of penalty-shots for each team. */ numberOfPenaltyShots = 3; - /** Time in seconds for each kind of penalty (-1 = should not be used). */ + /* Time in seconds for each kind of penalty (-1 = should not be used). */ penaltyTime = new int[] {-1, 45, 45, 15, 45, 45, 45, 45, 45, 15}; - /** Time in seconds to increment penalties. */ + /* Time in seconds to increment penalties. */ penaltyIncreaseTime = 10; - /** Whether the penalty count is reset on halftime */ + /* Whether the penalty count is reset on halftime */ resetPenaltyCountOnHalftime = false; - /** Whether penalties can be removed before the penalty time has passed. */ + /* Whether penalties can be removed before the penalty time has passed. */ allowEarlyPenaltyRemoval = false; - /** Penalty that players get when they substitute another player. */ + /* Penalty that players get when they substitute another player. */ substitutePenalty = PlayerInfo.PENALTY_SPL_REQUEST_FOR_PICKUP; - /** if robots should return from penalties when the game state changes. */ + /* if robots should return from penalties when the game state changes. */ returnRobotsInGameStoppages = true; - /** Time in seconds one team has as timeOut. */ + /* Time in seconds one team has as timeOut. */ timeOutTime = 5*60; - /** Time in seconds of a referee timeout */ + /* Time in seconds of a referee timeout */ refereeTimeout = 10*60; - /** Defines if the option for a referee timeout is available */ + /* Defines if the option for a referee timeout is available */ isRefereeTimeoutAvailable = true; - /** One time-out per half? */ + /* One time-out per half? */ timeOutPerHalf = false; - /** Allowed to compensate the lost time? */ + /* Allowed to compensate the lost time? */ lostTime = true; - /** If true, the game controller should drop broadcast-messages */ + /* If true, the game controller should drop broadcast-messages */ dropBroadcastMessages = true; - /** The type of the competition (COMPETITION_TYPE_NORMAL, COMPETITION_TYPE_CHALLENGE_SHIELD, etc) */ + /* The type of the competition (COMPETITION_TYPE_NORMAL, COMPETITION_TYPE_CHALLENGE_SHIELD, etc) */ competitionType = GameControlData.COMPETITION_TYPE_NORMAL; - /** Number of hardware penalties per half before the robot is ejected. */ + /* Number of hardware penalties per half before the robot is ejected. */ allowedHardwarePenaltiesPerHalf = Integer.MAX_VALUE; - /** Number of hardware penalties per game before the robot is ejected. */ + /* Number of hardware penalties per game before the robot is ejected. */ allowedHardwarePenaltiesPerGame = Integer.MAX_VALUE; - /** Number of team messages a team is allowed to send per game. */ + /* Number of team messages a team is allowed to send per game. */ overallMessageBudget = 1200; - /** Number of team messages that are added to the budget per minute of extra time. */ + /* Number of team messages that are added to the budget per minute of extra time. */ additionalMessageBudgetPerMinute = 60; } } diff --git a/src/data/SPL7v7.java b/src/data/SPL7v7.java index b13895d6..b1258cb4 100644 --- a/src/data/SPL7v7.java +++ b/src/data/SPL7v7.java @@ -9,13 +9,13 @@ public class SPL7v7 extends SPL { SPL7v7() { - /** The league's name this rules are for. */ + /* The league's name these rules are for. */ leagueName = "SPL 7v7"; - /** The league's directory name with its teams and icons. */ + /* The league's directory name with its teams and icons. */ leagueDirectory = "spl"; - /** How many robots are in a team. */ + /* How many robots are in a team. */ teamSize = 7; - /** How many robots of each team may play at one time. */ + /* How many robots of each team may play at one time. */ robotsPlaying = 7; } } diff --git a/src/data/SPLDynamicBallHandling.java b/src/data/SPLDynamicBallHandling.java index dc7bb309..c85f62cc 100644 --- a/src/data/SPLDynamicBallHandling.java +++ b/src/data/SPLDynamicBallHandling.java @@ -9,19 +9,19 @@ public class SPLDynamicBallHandling extends SPL { SPLDynamicBallHandling() { - /** The league's name this rules are for. */ + /* The league's name these rules are for. */ leagueName = "SPL Dynamic Ball Handling"; - /** The league's directory name with its teams and icons. */ + /* The league's directory name with its teams and icons. */ leagueDirectory = "spl"; - /** How many robots are in a team. */ + /* How many robots are in a team. */ teamSize = 3; - /** How many robots of each team may play at one time. */ + /* How many robots of each team may play at one time. */ robotsPlaying = 3; - /** Time in seconds one half is long. */ + /* Time in seconds one half is long. */ halfTime = 4*60; - /** Time in seconds the ball is blocked after kickoff. */ + /* Time in seconds the ball is blocked after kickoff. */ kickoffTime = -1; - /** The type of the competition (COMPETITION_TYPE_NORMAL, COMPETITION_TYPE_CHALLENGE_SHIELD, etc) */ + /* The type of the competition (COMPETITION_TYPE_NORMAL, COMPETITION_TYPE_CHALLENGE_SHIELD, etc) */ competitionType = GameControlData.COMPETITION_TYPE_DYNAMIC_BALL_HANDLING; } } diff --git a/src/data/SPLGORE.java b/src/data/SPLGORE.java index d57bf58a..c05a65ce 100644 --- a/src/data/SPLGORE.java +++ b/src/data/SPLGORE.java @@ -9,15 +9,15 @@ public class SPLGORE extends SPL { SPLGORE() { - /** The league's name this rules are for. */ + /* The league's name these rules are for. */ leagueName = "SPL GORE"; - /** The league's directory name with its teams and icons. */ + /* The league's directory name with its teams and icons. */ leagueDirectory = "spl"; - /** How many robots are in a team. */ + /* How many robots are in a team. */ teamSize = 5; // no substitute - /** Number of hardware penalties per half before the robot is ejected. */ + /* Number of hardware penalties per half before the robot is ejected. */ allowedHardwarePenaltiesPerHalf = 2; - /** Number of hardware penalties per game before the robot is ejected. */ + /* Number of hardware penalties per game before the robot is ejected. */ allowedHardwarePenaltiesPerGame = 3; } } diff --git a/src/data/SPLPenaltyShootout.java b/src/data/SPLPenaltyShootout.java index 254deadb..a9876ddc 100644 --- a/src/data/SPLPenaltyShootout.java +++ b/src/data/SPLPenaltyShootout.java @@ -9,9 +9,9 @@ public class SPLPenaltyShootout extends SPL { SPLPenaltyShootout() { - /** The league's name this rules are for. */ + /* The league's name these rules are for. */ leagueName = "SPL Penalty Shootout"; - /** If the game starts with penalty-shots. */ + /* If the game starts with penalty-shots. */ startWithPenalty = true; } } diff --git a/src/data/TeamInfo.java b/src/data/TeamInfo.java index 47aacd33..6f15c7d4 100644 --- a/src/data/TeamInfo.java +++ b/src/data/TeamInfo.java @@ -52,7 +52,7 @@ public class TeamInfo implements Serializable { public byte penaltyShot = 0; // penalty shot counter public short singleShots = 0; // bits represent penalty shot success public short messageBudget = 0; // number of team messages the team is allowed to send for the remainder of the game - public PlayerInfo[] player = new PlayerInfo[MAX_NUM_PLAYERS]; // the team's players + public final PlayerInfo[] player = new PlayerInfo[MAX_NUM_PLAYERS]; // the team's players /** * Creates a new TeamInfo. @@ -103,8 +103,8 @@ public void fromByteArray(ByteBuffer buffer) { penaltyShot = buffer.get(); singleShots = buffer.getShort(); messageBudget = buffer.getShort(); - for (int i = 0; i < player.length; i++) { - player[i].fromByteArray(buffer); + for (PlayerInfo info : player) { + info.fromByteArray(buffer); } } @@ -137,20 +137,20 @@ public static String getTeamColorName(byte teamColor) { @Override public String toString() { - String out = "--------------------------------------\n"; + StringBuilder out = new StringBuilder("--------------------------------------\n"); - out += " teamNumber: " + teamNumber + "\n"; - out += " fieldPlayerColor: " + getTeamColorName(fieldPlayerColor) + "\n"; - out += " goalkeeperColor: " + getTeamColorName(goalkeeperColor) + "\n"; - out += " goalkeeper: " + goalkeeper + "\n"; - out += " score: " + score + "\n"; - out += " penaltyShot: " + penaltyShot + "\n"; - out += " singleShots: " + Integer.toBinaryString(singleShots) + "\n"; - out += " messageBudget: " + messageBudget + "\n"; + out.append(" teamNumber: ").append(teamNumber).append("\n"); + out.append(" fieldPlayerColor: ").append(getTeamColorName(fieldPlayerColor)).append("\n"); + out.append(" goalkeeperColor: ").append(getTeamColorName(goalkeeperColor)).append("\n"); + out.append(" goalkeeper: ").append(goalkeeper).append("\n"); + out.append(" score: ").append(score).append("\n"); + out.append(" penaltyShot: ").append(penaltyShot).append("\n"); + out.append(" singleShots: ").append(Integer.toBinaryString(singleShots)).append("\n"); + out.append(" messageBudget: ").append(messageBudget).append("\n"); for (int i = 0; i < player.length; i++) { - out += "Player #" + (i + 1) + "\n" + player[i].toString(); + out.append("Player #").append(i + 1).append("\n").append(player[i].toString()); } - return out; + return out.toString(); } } diff --git a/src/data/Teams.java b/src/data/Teams.java index 173060f6..4a3567c5 100644 --- a/src/data/Teams.java +++ b/src/data/Teams.java @@ -6,10 +6,11 @@ import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Paths; import javax.imageio.ImageIO; /** @@ -30,7 +31,7 @@ private static class Info { /** * The name of the team. */ - public String name; + public final String name; /** * The icon of the team. */ @@ -38,7 +39,7 @@ private static class Info { /** * The first and secondary jersey colors of the team. */ - public String[] colors; + public final String[] colors; /** * Create a new team information. @@ -74,12 +75,12 @@ public Info(String name, String[] colors) { /** * The instance of the singleton. */ - private static Teams instance = new Teams(); + private static final Teams instance = new Teams(); /** * The information read from the config files. */ - private Info[][] teams; + private final Info[][] teams; /** * Creates a new Teams object. @@ -91,13 +92,13 @@ private Teams() { int maxValue = 0; BufferedReader br = null; try { - InputStream inStream = new FileInputStream(PATH + dir + "/" + CONFIG); + InputStream inStream = Files.newInputStream(Paths.get(PATH + dir + "/" + CONFIG)); br = new BufferedReader( new InputStreamReader(inStream, CHARSET)); String line; while ((line = br.readLine()) != null) { try { - final int value = Integer.valueOf(line.split("=", 2)[0]); + final int value = Integer.parseInt(line.split("=", 2)[0]); if (value > maxValue) { maxValue = value; } @@ -141,7 +142,7 @@ private static int getLeagueIndex() { public static void readTeams() { BufferedReader br = null; try { - InputStream inStream = new FileInputStream(PATH + Rules.league.leagueDirectory + "/" + CONFIG); + InputStream inStream = Files.newInputStream(Paths.get(PATH + Rules.league.leagueDirectory + "/" + CONFIG)); br = new BufferedReader( new InputStreamReader(inStream, CHARSET)); String line; @@ -150,7 +151,7 @@ public static void readTeams() { if (entry.length == 2) { int key = -1; try { - key = Integer.valueOf(entry[0]); + key = Integer.parseInt(entry[0]); } catch (NumberFormatException e) { } if (key >= 0) { diff --git a/src/eventrecorder/EventRecorder.java b/src/eventrecorder/EventRecorder.java index 79ac8d68..076bae30 100644 --- a/src/eventrecorder/EventRecorder.java +++ b/src/eventrecorder/EventRecorder.java @@ -44,14 +44,14 @@ public class EventRecorder { private static byte lastSetPlay = -1; private static byte lastKickingTeam = -1; - private static boolean[] logPenalty = new boolean[16]; + private static final boolean[] logPenalty = new boolean[16]; private static boolean logFreeKicks = true; public TeamInfo[] getLastTeamData() { return lastTeamData; } - public static void main(String args[]){ + public static void main(String[] args){ System.setProperty("apple.laf.useScreenMenuBar", "true"); model = new DataModel(); history = new ActionHistory(); @@ -88,8 +88,8 @@ public void gameControlDataTimeout(GameControlDataTimeoutEvent e) { } - public static void updateGameData(GameControlData data){ - if(data != lastData && data != null){ + public static void updateGameData(GameControlData data) { + if (data != lastData && data != null) { // Deactivate manually running: model.isManuallyRunning = false; @@ -97,20 +97,21 @@ public static void updateGameData(GameControlData data){ model.currentTime = data.secsRemaining; //Log goals - if(lastData != null && data.gameState != GameControlData.STATE_INITIAL && - (lastData.team[0].score != data.team[0].score || lastData.team[1].score != data.team[1].score)){ + if (lastData != null && data.gameState != GameControlData.STATE_INITIAL && + (lastData.team[0].score != data.team[0].score || lastData.team[1].score != data.team[1].score)) { // Insert before empty logEntries: int insertPlace = EventRecorder.model.logEntries.size(); - while (insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace - 1).text)) + while (insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace - 1).text)) { --insertPlace; + } history.execute(new EntryCreateAction(new LogEntry(capitalize(TeamInfo.getTeamColorName(data.team[0].fieldPlayerColor)) + " " + data.team[0].score + " : " + data.team[1].score + " " + capitalize(TeamInfo.getTeamColorName(data.team[1].fieldPlayerColor)), SECONDS_FORMAT.format(data.secsRemaining * 1000), LogType.Manually), insertPlace, false)); } // If Gamestate is changed, add a LogEntry: - if(lastGameState != data.gameState){ + if (lastGameState != data.gameState) { lastGameState = data.gameState; String gameStateString = GAME_STATE_NAMES[data.gameState]; @@ -121,16 +122,17 @@ public static void updateGameData(GameControlData data){ // Insert before empty logEntries: int insertPlace = EventRecorder.model.logEntries.size(); - while(insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace-1).text)) + while (insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace - 1).text)) { --insertPlace; + } - history.execute(new EntryCreateAction(new LogEntry(gameStateString,SECONDS_FORMAT.format(data.secsRemaining*1000),LogType.GameState), insertPlace, false)); + history.execute(new EntryCreateAction(new LogEntry(gameStateString, SECONDS_FORMAT.format(data.secsRemaining * 1000),LogType.GameState), insertPlace, false)); } //Log Free Kicks - if(logFreeKicks && (lastSetPlay != data.setPlay || lastKickingTeam != data.kickingTeam)) { - if(data.setPlay == GameControlData.SET_PLAY_NONE) { - String setPlayString = ""; + if (logFreeKicks && (lastSetPlay != data.setPlay || lastKickingTeam != data.kickingTeam)) { + if (data.setPlay == GameControlData.SET_PLAY_NONE) { + String setPlayString; switch (lastSetPlay) { case GameControlData.SET_PLAY_GOAL_KICK: setPlayString = "Goal Kick Complete"; @@ -155,14 +157,15 @@ public static void updateGameData(GameControlData data){ // Insert before empty logEntries: int insertPlace = EventRecorder.model.logEntries.size(); - while(insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace-1).text)) + while (insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace-1).text)) { --insertPlace; + } - if(setPlayString != "") - history.execute(new EntryCreateAction(new LogEntry(setPlayString, SECONDS_FORMAT.format(data.secsRemaining*1000),LogType.SetPlayState), insertPlace, false)); - } - else { - String setPlayString = ""; + if (!setPlayString.isEmpty()) { + history.execute(new EntryCreateAction(new LogEntry(setPlayString, SECONDS_FORMAT.format(data.secsRemaining * 1000), LogType.SetPlayState), insertPlace, false)); + } + } else { + String setPlayString; switch (data.setPlay) { case GameControlData.SET_PLAY_GOAL_KICK: setPlayString = "Goal Kick for team: "; @@ -188,36 +191,35 @@ public static void updateGameData(GameControlData data){ // Insert before empty logEntries: int insertPlace = EventRecorder.model.logEntries.size(); - while(insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace-1).text)) + while (insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace - 1).text)) { --insertPlace; + } - history.execute(new EntryCreateAction(new LogEntry(setPlayString, SECONDS_FORMAT.format(data.secsRemaining*1000),LogType.SetPlayState), insertPlace, false)); + history.execute(new EntryCreateAction(new LogEntry(setPlayString, SECONDS_FORMAT.format(data.secsRemaining * 1000), LogType.SetPlayState), insertPlace, false)); } lastSetPlay = data.setPlay; lastKickingTeam = data.kickingTeam; } // Check for changed penalties: - if(lastTeamData != null) { - for(int i=0; i 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace-1).text)) + while (insertPlace > 0 && "".equals(EventRecorder.model.logEntries.get(insertPlace - 1).text)) { --insertPlace; + } - history.execute(new EntryCreateAction(new LogEntry(totalString,SECONDS_FORMAT.format(data.secsRemaining*1000),LogType.PlayerState), insertPlace, false)); - + history.execute(new EntryCreateAction(new LogEntry(totalString, SECONDS_FORMAT.format(data.secsRemaining * 1000),LogType.PlayerState), insertPlace, false)); } } } @@ -233,7 +235,7 @@ public static void updateGameData(GameControlData data){ } public static String capitalize(String string) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String[] array = string.split(" "); for (String s : array) { @@ -246,7 +248,7 @@ public static String capitalize(String string) { return result.toString().trim(); } - public static void cleanExit(){ + public static void cleanExit() { gcDataReceiver.interrupt(); // Try to join receiver threads diff --git a/src/eventrecorder/action/Action.java b/src/eventrecorder/action/Action.java index 4cfbed1a..c4e4beb2 100644 --- a/src/eventrecorder/action/Action.java +++ b/src/eventrecorder/action/Action.java @@ -9,14 +9,14 @@ */ public abstract class Action { - protected LogEntry entry; - private boolean addToHistory; + protected final LogEntry entry; + private final boolean addToHistory; /** * Constructor. * * @param entry - * @param hidden Should undo/redo be possible? + * @param addToHistory */ public Action(LogEntry entry, boolean addToHistory){ diff --git a/src/eventrecorder/action/ActionHistory.java b/src/eventrecorder/action/ActionHistory.java index e2289098..3c709a8d 100644 --- a/src/eventrecorder/action/ActionHistory.java +++ b/src/eventrecorder/action/ActionHistory.java @@ -9,7 +9,7 @@ */ public class ActionHistory { - public CircularLiFoBuffer actions = new CircularLiFoBuffer(1000); + public final CircularLiFoBuffer actions = new CircularLiFoBuffer<>(1000); public boolean execute(Action action){ if(action.executeAction()){ @@ -71,7 +71,7 @@ public boolean redo(){ /** * Notify the GUI that a LogEntry is changed. * - * @param e + * @param a */ private void notifyGUI(Action a){ diff --git a/src/eventrecorder/action/CircularLiFoBuffer.java b/src/eventrecorder/action/CircularLiFoBuffer.java index 51b1e438..b39dc1eb 100644 --- a/src/eventrecorder/action/CircularLiFoBuffer.java +++ b/src/eventrecorder/action/CircularLiFoBuffer.java @@ -7,7 +7,7 @@ */ public class CircularLiFoBuffer { - T[] array; + final T[] array; int pos = -1; int elements = 0; int pops = 0; diff --git a/src/eventrecorder/action/EntryChangeTextAction.java b/src/eventrecorder/action/EntryChangeTextAction.java index 59009f94..1ca843fe 100644 --- a/src/eventrecorder/action/EntryChangeTextAction.java +++ b/src/eventrecorder/action/EntryChangeTextAction.java @@ -9,15 +9,15 @@ */ public class EntryChangeTextAction extends Action{ - private String newText; - private String savedText; + private final String newText; + private final String savedText; /** * Creates a new ChangeAction. * - * @param entry LogEntry in the DataModel. - * @param newLogEntry Copy of the LogEntry with new values. - * @param savedLogEntry Copy of the LogEntry with old values. + * @param entry LogEntry in the DataModel. + * @param newText entry's text. + * @param savedText entry's previous text. */ public EntryChangeTextAction(LogEntry entry, String newText, String savedText){ diff --git a/src/eventrecorder/action/EntryChangeTimeAction.java b/src/eventrecorder/action/EntryChangeTimeAction.java index a3199c99..cf0cb8e1 100644 --- a/src/eventrecorder/action/EntryChangeTimeAction.java +++ b/src/eventrecorder/action/EntryChangeTimeAction.java @@ -9,16 +9,16 @@ */ public class EntryChangeTimeAction extends Action{ - private String newTime; - private String savedTime; - private boolean wasFirstTimeSet; + private final String newTime; + private final String savedTime; + private final boolean wasFirstTimeSet; /** * Creates a new ChangeAction. * - * @param entry LogEntry in the DataModel. - * @param newLogEntry Copy of the LogEntry with new values. - * @param savedLogEntry Copy of the LogEntry with old values. + * @param entry LogEntry in the DataModel. + * @param newTime New time value. + * @param savedTime Previous time value to support undo. */ public EntryChangeTimeAction(LogEntry entry, String newTime, String savedTime){ diff --git a/src/eventrecorder/action/EntryTypeChangeAction.java b/src/eventrecorder/action/EntryTypeChangeAction.java index ef42439e..812dd8e5 100644 --- a/src/eventrecorder/action/EntryTypeChangeAction.java +++ b/src/eventrecorder/action/EntryTypeChangeAction.java @@ -4,8 +4,8 @@ import eventrecorder.data.LogType; public class EntryTypeChangeAction extends Action{ - private LogType savedLogType; - private LogType newLogType; + private final LogType savedLogType; + private final LogType newLogType; public EntryTypeChangeAction(LogEntry entry, LogType newLogType, LogType savedLogType){ this(entry, true, newLogType, savedLogType); diff --git a/src/eventrecorder/action/TitleChangeAction.java b/src/eventrecorder/action/TitleChangeAction.java index 4489615b..ae921736 100644 --- a/src/eventrecorder/action/TitleChangeAction.java +++ b/src/eventrecorder/action/TitleChangeAction.java @@ -10,10 +10,10 @@ */ public class TitleChangeAction extends Action{ - String savedTitle; - String savedAdditional; - String newTitle; - String newAdditional; + final String savedTitle; + final String savedAdditional; + final String newTitle; + final String newAdditional; public TitleChangeAction(LogEntry entry, String newTitle, String newAdditional, String savedTitle, String savedAdditional) { super(entry, true); diff --git a/src/eventrecorder/data/DataModel.java b/src/eventrecorder/data/DataModel.java index ff402471..9cbb3db3 100644 --- a/src/eventrecorder/data/DataModel.java +++ b/src/eventrecorder/data/DataModel.java @@ -11,7 +11,7 @@ public class DataModel { public String title = ""; public String additionalInfo = ""; - public ArrayList logEntries = new ArrayList(); + public final ArrayList logEntries = new ArrayList<>(); public int currentTime = 600; public boolean isManuallyRunning = false; diff --git a/src/eventrecorder/data/LogEntry.java b/src/eventrecorder/data/LogEntry.java index e4e29947..8f6eed97 100644 --- a/src/eventrecorder/data/LogEntry.java +++ b/src/eventrecorder/data/LogEntry.java @@ -27,16 +27,6 @@ public LogEntry(String text, String time, LogType type){ this.firstTimeSet = "".equals(time); } - /** - * Creates a new LogEntry with the values of the given LogEntry. - * - * @param e LogEntry - */ - - public LogEntry(LogEntry e){ - set(e); - } - /** * Sets the values of this LogEntry to the value of e. * diff --git a/src/eventrecorder/data/LogType.java b/src/eventrecorder/data/LogType.java index 71595a4a..3b50106a 100644 --- a/src/eventrecorder/data/LogType.java +++ b/src/eventrecorder/data/LogType.java @@ -7,5 +7,5 @@ */ public enum LogType { - GameState, SetPlayState, PlayerState, Manually; + GameState, SetPlayState, PlayerState, Manually } diff --git a/src/eventrecorder/export/MarkDownExporter.java b/src/eventrecorder/export/MarkDownExporter.java index 0a99c4ff..a645fb8f 100644 --- a/src/eventrecorder/export/MarkDownExporter.java +++ b/src/eventrecorder/export/MarkDownExporter.java @@ -12,23 +12,23 @@ public class MarkDownExporter { public static String toMarkDown(DataModel model){ - String result = "## " + model.title + " \n" + model.additionalInfo+" \n\n"; + StringBuilder result = new StringBuilder("## " + model.title + " \n" + model.additionalInfo + " \n\n"); for(LogEntry entry : model.logEntries){ if("".equals(entry.time) && "".equals(entry.text)) continue; if(entry.type == LogType.Manually){ - result += "- "+entry.time+": "+entry.text+" \n"; + result.append("- ").append(entry.time).append(": ").append(entry.text).append(" \n"); } else if(entry.type == LogType.PlayerState || entry.type == LogType.SetPlayState){ - result += "- *"+entry.time+": "+entry.text+"* \n"; + result.append("- *").append(entry.time).append(": ").append(entry.text).append("* \n"); } else if(entry.type == LogType.GameState){ - result += "\n**"+entry.text+" ("+entry.time+")** \n\n"; + result.append("\n**").append(entry.text).append(" (").append(entry.time).append(")** \n\n"); } } //result += "*Logfile End*"; - return result; + return result.toString(); } } diff --git a/src/eventrecorder/gui/EntryPanel.java b/src/eventrecorder/gui/EntryPanel.java index 15915fda..e390b3eb 100644 --- a/src/eventrecorder/gui/EntryPanel.java +++ b/src/eventrecorder/gui/EntryPanel.java @@ -1,8 +1,6 @@ package eventrecorder.gui; import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; @@ -24,8 +22,8 @@ public class EntryPanel extends JPanel{ private static final long serialVersionUID = -907777557585101050L; - private TimeField timeField; - private TextField textField; + private final TimeField timeField; + private final TextField textField; public EntryPanel(final LogEntry e){ timeField = new TimeField(e); @@ -41,24 +39,12 @@ public EntryPanel(final LogEntry e){ controlEntryPanel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); - final JComboBox logTypeChooser = new JComboBox(new LogType[]{LogType.Manually, LogType.GameState, LogType.PlayerState, LogType.SetPlayState}); + final JComboBox logTypeChooser = new JComboBox<>(new LogType[]{LogType.Manually, LogType.GameState, LogType.PlayerState, LogType.SetPlayState}); logTypeChooser.setSelectedItem(e.type); - logTypeChooser.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent aE) { - EventRecorder.history.execute(new EntryTypeChangeAction(e, (LogType)logTypeChooser.getSelectedItem(), e.type)); - } - - }); + logTypeChooser.addActionListener(aE -> EventRecorder.history.execute(new EntryTypeChangeAction(e, (LogType)logTypeChooser.getSelectedItem(), e.type))); JButton deleteButton = new JButton("Delete"); - deleteButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent aE) { - EventRecorder.history.execute(new EntryDeleteAction(e)); - } - }); + deleteButton.addActionListener(aE -> EventRecorder.history.execute(new EntryDeleteAction(e))); controlEntryPanel.add(logTypeChooser); controlEntryPanel.add(deleteButton); diff --git a/src/eventrecorder/gui/ImageButton.java b/src/eventrecorder/gui/ImageButton.java index 70e0a6dd..548133c4 100644 --- a/src/eventrecorder/gui/ImageButton.java +++ b/src/eventrecorder/gui/ImageButton.java @@ -11,7 +11,7 @@ */ public class ImageButton extends JButton{ private static final long serialVersionUID = -2848062138312840891L; - ImageIcon enabledIcon; + final ImageIcon enabledIcon; ImageIcon disabledIcon; public ImageButton(String tooltip, String path, int width, int height){ diff --git a/src/eventrecorder/gui/ImageToggleButton.java b/src/eventrecorder/gui/ImageToggleButton.java index c2fdd116..fe999053 100644 --- a/src/eventrecorder/gui/ImageToggleButton.java +++ b/src/eventrecorder/gui/ImageToggleButton.java @@ -1,8 +1,6 @@ package eventrecorder.gui; import java.awt.Image; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JToggleButton; @@ -15,7 +13,7 @@ public class ImageToggleButton extends JToggleButton{ private static final long serialVersionUID = 1L; - private ImageIcon enabledIcon; + private final ImageIcon enabledIcon; private ImageIcon disabledIcon; private boolean isActivated; @@ -38,14 +36,7 @@ public ImageToggleButton(String tooltip, String path, String disabledPath, boole setToolTipText(tooltip); - addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - setActivated(!isActivated); - } - - }); + addActionListener(e -> setActivated(!isActivated)); } public void setActivated(boolean b) { diff --git a/src/eventrecorder/gui/LogEntryTable.java b/src/eventrecorder/gui/LogEntryTable.java index e063eb67..2269a027 100644 --- a/src/eventrecorder/gui/LogEntryTable.java +++ b/src/eventrecorder/gui/LogEntryTable.java @@ -42,8 +42,8 @@ private void createLogEntryTable(){ ArrayList entries = EventRecorder.model.logEntries; for(LogEntry e : entries){ EntryPanel entryPanel = new EntryPanel(e); - entryPanel.getTimeField().addKeyListener(new TimeFieldKeyListener(this,e)); - entryPanel.getTextField().addKeyListener(new TextFieldKeyListener(this,e)); + entryPanel.getTimeField().addKeyListener(new TimeFieldKeyListener(this, e)); + entryPanel.getTextField().addKeyListener(new TextFieldKeyListener(this, e)); add(entryPanel); } @@ -66,9 +66,9 @@ public int getIdByLogEntry(LogEntry entry){ * @author Andre Muehlenbrock */ - class TimeFieldKeyListener extends KeyAdapter { - private LogEntryTable table; - private LogEntry entry; + static class TimeFieldKeyListener extends KeyAdapter { + private final LogEntryTable table; + private final LogEntry entry; public TimeFieldKeyListener(LogEntryTable table, LogEntry entry){ this.table = table; @@ -142,9 +142,9 @@ public void keyPressed(KeyEvent e) { * @author Andre Muehlenbrock */ - class TextFieldKeyListener extends KeyAdapter { - private LogEntryTable table; - private LogEntry entry; + static class TextFieldKeyListener extends KeyAdapter { + private final LogEntryTable table; + private final LogEntry entry; public TextFieldKeyListener(LogEntryTable table, LogEntry entry){ this.table = table; @@ -244,8 +244,8 @@ public void entryActionWasExecuted(Action action){ entryPanel.repaint(); } else if(action instanceof EntryCreateAction && !action.shouldBeAddedToHistory()){ EntryPanel entryPanel = new EntryPanel(action.getAffectedLogEntry()); - entryPanel.getTimeField().addKeyListener(new TimeFieldKeyListener(this,action.getAffectedLogEntry())); - entryPanel.getTextField().addKeyListener(new TextFieldKeyListener(this,action.getAffectedLogEntry())); + entryPanel.getTimeField().addKeyListener(new TimeFieldKeyListener(this, action.getAffectedLogEntry())); + entryPanel.getTextField().addKeyListener(new TextFieldKeyListener(this, action.getAffectedLogEntry())); int index = EventRecorder.model.logEntries.indexOf(action.getAffectedLogEntry()); @@ -255,7 +255,7 @@ public void entryActionWasExecuted(Action action){ createLogEntryTable(); int newId = getIdByLogEntry(action.getAffectedLogEntry()); - EntryPanel entryPanel = null; + EntryPanel entryPanel; // if the entry was added: if(newId != -1){ entryPanel = (EntryPanel)getComponent(newId); @@ -263,7 +263,7 @@ public void entryActionWasExecuted(Action action){ entryPanel.getTextField().requestFocus(); } else { // if the entry was removed: if(getComponents().length > 0){ - entryPanel = (EntryPanel)getComponent(id-1<0?0:id-1); + entryPanel = (EntryPanel)getComponent(Math.max(id - 1, 0)); if(entryPanel != null){ entryPanel.getTextField().setCaretPosition(entryPanel.getTextField().getText().length()); entryPanel.getTextField().requestFocus(); diff --git a/src/eventrecorder/gui/MainFrame.java b/src/eventrecorder/gui/MainFrame.java index fefaba66..eb607080 100644 --- a/src/eventrecorder/gui/MainFrame.java +++ b/src/eventrecorder/gui/MainFrame.java @@ -6,20 +6,18 @@ import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; -import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedWriter; -import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; @@ -44,6 +42,7 @@ import javax.swing.UIManager; import javax.swing.plaf.FontUIResource; +import common.Log; import eventrecorder.EventRecorder; import eventrecorder.action.Action; import eventrecorder.action.EntryCreateAction; @@ -82,32 +81,30 @@ public class MainFrame extends JFrame { public static final int CURRENT_TIME_SMALL_STEP = 5; public static final int CURRENT_TIME_BIG_STEP = 60; - private Preferences prefs; + private final Preferences prefs; - private LogEntryTable entryTable; + private final LogEntryTable entryTable; - private JPanel statusPanel = new JPanel(); + private final JPanel statusPanel = new JPanel(); - private ImageButton undoButton; - private ImageButton redoButton; - private JLabel currentTimeLabel; + private final ImageButton undoButton; + private final ImageButton redoButton; + private final JLabel currentTimeLabel; - private ImageToggleButton startButton; - private ImageButton resetButton; + private final ImageToggleButton startButton; + private final ImageButton resetButton; - private Timer timer = new Timer(); + private final JTextArea additionalField; - private JTextArea additionalField; - - private JTextField titleField; + private final JTextField titleField; private boolean activeGameController; - private JButton timePlusPlusButton; - private JButton timePlusButton; + private final JButton timePlusPlusButton; + private final JButton timePlusButton; - private JButton timeMinusMinusButton; - private JButton timeMinusButton; + private final JButton timeMinusMinusButton; + private final JButton timeMinusButton; /** * Creates the Main Window. @@ -117,7 +114,7 @@ public MainFrame(){ JComponent.setDefaultLocale(Locale.ENGLISH); // Enable fullscreen mode on macOS - getRootPane().putClientProperty("apple.awt.fullscreenable", Boolean.valueOf(true)); + getRootPane().putClientProperty("apple.awt.fullscreenable", true); // Load preferences: prefs = Preferences.userRoot().node(this.getClass().getName()); @@ -165,34 +162,24 @@ public void windowClosing(WindowEvent we) JPanel main = new JPanel(); main.setLayout(new BorderLayout()); - // Contains title, additional and other informations: + // Contains title, additional and other information: JPanel head = new JPanel(); head.setLayout(new BoxLayout(head,BoxLayout.Y_AXIS)); try { String current = new java.io.File( "." ).getCanonicalPath(); System.out.println(current); } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + Log.error(e.getMessage()); + System.exit(1); } // Undo and Redo Line: JPanel topLine = new JPanel(); topLine.setLayout(new BorderLayout()); undoButton = new ImageButton("Make Undo ( Strg+Z )",ICONS_PATH+"undo.png",ICONS_PATH+"undo_disabled.png", EventRecorder.history.undoPossible(),24,24); - undoButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.history.undo(); - } - }); + undoButton.addActionListener(e -> EventRecorder.history.undo()); redoButton = new ImageButton("Make Redo ( Strg+Y )",ICONS_PATH+"redo.png",ICONS_PATH+"redo_disabled.png", EventRecorder.history.redoPossible(),24,24); - redoButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.history.redo(); - } - }); + redoButton.addActionListener(e -> EventRecorder.history.redo()); // Current Time Label: currentTimeLabel = new JLabel(TIME_FORMAT.format(EventRecorder.model.currentTime*1000)); @@ -201,31 +188,18 @@ public void actionPerformed(ActionEvent e) { ImageButton createNewButton = new ImageButton("New ( Strg+New )", ICONS_PATH+"plus_icon.png", 24,24); - createNewButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.history.execute(new EntryCreateAction(new LogEntry("","",LogType.Manually))); - } - }); + createNewButton.addActionListener(e -> EventRecorder.history.execute(new EntryCreateAction(new LogEntry("","",LogType.Manually)))); // Start/Stop and Reset-Button: startButton = new ImageToggleButton("Play and Pause ( Strg+Space )", ICONS_PATH+"pause_icon.png", ICONS_PATH+"play_icon.png", false,24,24); - startButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.model.isManuallyRunning = !EventRecorder.model.isManuallyRunning; - } - }); + startButton.addActionListener(e -> EventRecorder.model.isManuallyRunning = !EventRecorder.model.isManuallyRunning); resetButton = new ImageButton("Reset", ICONS_PATH+"reset_icon.png", 24,24); - resetButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.model.currentTime = 600; - currentTimeLabel.setText((EventRecorder.model.currentTime < 0? "-":"")+TIME_FORMAT.format(Math.abs(EventRecorder.model.currentTime*1000))); - currentTimeLabel.revalidate(); - currentTimeLabel.repaint(); - } + resetButton.addActionListener(e -> { + EventRecorder.model.currentTime = 600; + currentTimeLabel.setText((EventRecorder.model.currentTime < 0? "-":"")+TIME_FORMAT.format(Math.abs(EventRecorder.model.currentTime*1000))); + currentTimeLabel.revalidate(); + currentTimeLabel.repaint(); }); // Add Buttons to the Top Panel and Top Panel to the Main Panel: @@ -242,41 +216,29 @@ public void actionPerformed(ActionEvent e) { timeMinusMinusButton = new JButton("--"); timeMinusMinusButton.setToolTipText("Decrease by 60 seconds ( Strg+Shift+Minus )"); - timeMinusMinusButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.model.currentTime -= CURRENT_TIME_BIG_STEP; - updateTimeAndButtons(); - } + timeMinusMinusButton.addActionListener(e -> { + EventRecorder.model.currentTime -= CURRENT_TIME_BIG_STEP; + updateTimeAndButtons(); }); timeMinusButton = new JButton("-"); timeMinusButton.setToolTipText("Decrease by 5 seconds ( Strg+Minus )"); - timeMinusButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.model.currentTime -= CURRENT_TIME_SMALL_STEP; - updateTimeAndButtons(); - } + timeMinusButton.addActionListener(e -> { + EventRecorder.model.currentTime -= CURRENT_TIME_SMALL_STEP; + updateTimeAndButtons(); }); timePlusButton = new JButton("+"); timePlusButton.setToolTipText("Increase by 5 seconds ( Strg+Plus )"); - timePlusButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.model.currentTime += CURRENT_TIME_SMALL_STEP; - updateTimeAndButtons(); - } + timePlusButton.addActionListener(e -> { + EventRecorder.model.currentTime += CURRENT_TIME_SMALL_STEP; + updateTimeAndButtons(); }); timePlusPlusButton = new JButton("++"); timePlusPlusButton.setToolTipText("Increase by 60 seconds ( Strg+Shift+Plus )"); - timePlusPlusButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.model.currentTime += CURRENT_TIME_BIG_STEP; - updateTimeAndButtons(); - } + timePlusPlusButton.addActionListener(e -> { + EventRecorder.model.currentTime += CURRENT_TIME_BIG_STEP; + updateTimeAndButtons(); }); JPanel currentTimePanel = new JPanel(); @@ -388,25 +350,11 @@ public void focusLost(FocusEvent e) { mainWrapper.add(statusPanel, BorderLayout.NORTH); mainWrapper.add(main, BorderLayout.CENTER); - /*String shortCutInfoString = "Strg + Enter: New Entry " - + "    Strg + Plus: Increase Time" - + "    Strg + Minus: Reduce Time" - + "    Strg + Space: Start/Stop Timer" - + ""; - - JPanel shortCutInfoPanel = new JPanel(); - JLabel shortCutInfoLabel = new JLabel(shortCutInfoString); - shortCutInfoLabel.setFont(new Font(shortCutInfoLabel.getFont().getFontName(),Font.PLAIN, 11)); - shortCutInfoPanel.add(shortCutInfoLabel); - shortCutInfoPanel.setBorder(BorderFactory.createEmptyBorder(4,4,4,4)); - shortCutInfoPanel.setLayout(new BoxLayout(shortCutInfoPanel,BoxLayout.X_AXIS)); - - mainWrapper.add(shortCutInfoPanel,BorderLayout.SOUTH);*/ - add(mainWrapper); setVisible(true); // Update some running informations on the gui: + Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask(){ @Override public void run() { @@ -421,102 +369,97 @@ private void setupShortCuts(){ KeyboardFocusManager keyManager; keyManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - keyManager.addKeyEventDispatcher(new KeyEventDispatcher() { - - @Override - public boolean dispatchKeyEvent(KeyEvent e) { - if (e.getID() == KeyEvent.KEY_PRESSED) { - if (e.isControlDown()) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - EventRecorder.history - .execute(new EntryCreateAction(new LogEntry("", "", LogType.Manually))); - e.consume(); - return true; - - } else if(e.getKeyCode() == KeyEvent.VK_Z){ - // Before undo, the action on focusLost has to be executed: - Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - if(focusOwner instanceof TextField) - ((TextField)focusOwner).executeChangeAction(); - if(focusOwner instanceof TimeField) - ((TextField)focusOwner).executeChangeAction(); - - // Undo: - EventRecorder.history.undo(); - e.consume(); - return true; - } else if(e.getKeyCode() == KeyEvent.VK_Y){ - // Before redo, the action on focusLost has to be executed: - Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - if(focusOwner instanceof TextField) - ((TextField)focusOwner).executeChangeAction(); - if(focusOwner instanceof TimeField) - ((TextField)focusOwner).executeChangeAction(); - - // Redo: - EventRecorder.history.redo(); - e.consume(); - return true; - } else if(e.getKeyCode() == KeyEvent.VK_W){ - // Delete last typed word: - Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - - String text = null; - if(focusOwner instanceof JTextField) - text = ((JTextField)focusOwner).getText(); - if(focusOwner instanceof JTextArea) - text = ((JTextArea)focusOwner).getText(); - - String[] textParts = text.split(" "); - - text = ""; - for(int i=0;i { + if (e.getID() == KeyEvent.KEY_PRESSED) { + if (e.isControlDown()) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + EventRecorder.history + .execute(new EntryCreateAction(new LogEntry("", "", LogType.Manually))); + e.consume(); + return true; + + } else if(e.getKeyCode() == KeyEvent.VK_Z){ + // Before undo, the action on focusLost has to be executed: + Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + if(focusOwner instanceof TextField) + ((TextField)focusOwner).executeChangeAction(); + if(focusOwner instanceof TimeField) + ((TimeField)focusOwner).executeChangeAction(); + + // Undo: + EventRecorder.history.undo(); + e.consume(); + return true; + } else if(e.getKeyCode() == KeyEvent.VK_Y){ + // Before redo, the action on focusLost has to be executed: + Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + if(focusOwner instanceof TextField) + ((TextField)focusOwner).executeChangeAction(); + if(focusOwner instanceof TimeField) + ((TimeField)focusOwner).executeChangeAction(); + + // Redo: + EventRecorder.history.redo(); + e.consume(); + return true; + } else if(e.getKeyCode() == KeyEvent.VK_W){ + // Delete last typed word: + Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + + StringBuilder text = null; + if(focusOwner instanceof JTextField) + text = new StringBuilder(((JTextField) focusOwner).getText()); + else if(focusOwner instanceof JTextArea) + text = new StringBuilder(((JTextArea) focusOwner).getText()); + + String[] textParts = text.toString().split(" "); + + text = new StringBuilder(); + for(int i=0;i { + JFrame newWindow = new JFrame("Markdown View"); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + int width = Math.min((int) screenSize.getWidth(), MARKDOWN_WINDOW_WIDTH); + int height = Math.min((int) screenSize.getHeight(), MARKDOWN_WINDOW_HEIGHT); + int x = ((int) screenSize.getWidth() - width) / 2; + int y = ((int) screenSize.getHeight() - height) / 2; - // Set some window settings: - newWindow.setBounds(x, y, width, height); + // Set some window settings: + newWindow.setBounds(x, y, width, height); - JPanel main = new JPanel(); - main.setLayout(new BorderLayout()); + JPanel main = new JPanel(); + main.setLayout(new BorderLayout()); - JTextArea textArea = new JTextArea(); - textArea.setText(MarkDownExporter.toMarkDown(EventRecorder.model)); + JTextArea textArea = new JTextArea(); + textArea.setText(MarkDownExporter.toMarkDown(EventRecorder.model)); - main.add(new JScrollPane(textArea), BorderLayout.CENTER); - - newWindow.add(main); - newWindow.setVisible(true); - } + main.add(new JScrollPane(textArea), BorderLayout.CENTER); + newWindow.add(main); + newWindow.setVisible(true); }); JMenuItem saveLogFile = new JMenuItem("Save as MarkDown"); - saveLogFile.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.gui.saveAs(); - } - - }); + saveLogFile.addActionListener(e -> EventRecorder.gui.saveAs()); JMenuItem exit = new JMenuItem("Exit"); @@ -105,12 +91,7 @@ public void actionPerformed(ActionEvent e) { // Setup the Checkbox: final JCheckBox checkBox = new JCheckBox(penaltyString); checkBox.setSelected(true); - checkBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.setLogPenalty(finalI, checkBox.isSelected()); - } - }); + checkBox.addActionListener(e -> EventRecorder.setLogPenalty(finalI, checkBox.isSelected())); loggingPanel.add(checkBox); } @@ -120,12 +101,7 @@ public void actionPerformed(ActionEvent e) { final JCheckBox checkBox = new JCheckBox("Free Kicks"); checkBox.setSelected(true); - checkBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - EventRecorder.setLogFreeKicks(checkBox.isSelected()); - } - }); + checkBox.addActionListener(e -> EventRecorder.setLogFreeKicks(checkBox.isSelected())); loggingPanel.add(checkBox); loggingPanel.add(new JSeparator(JSeparator.HORIZONTAL)); diff --git a/src/eventrecorder/gui/TextField.java b/src/eventrecorder/gui/TextField.java index 68f2674b..18d1364e 100644 --- a/src/eventrecorder/gui/TextField.java +++ b/src/eventrecorder/gui/TextField.java @@ -27,7 +27,7 @@ public class TextField extends JTextField{ private static final long serialVersionUID = -634374539579879231L; - private LogEntry entry; + private final LogEntry entry; private String savedText = null; public TextField(LogEntry entry){ diff --git a/src/eventrecorder/gui/TimeField.java b/src/eventrecorder/gui/TimeField.java index 3af0ab5a..1e8a7d61 100644 --- a/src/eventrecorder/gui/TimeField.java +++ b/src/eventrecorder/gui/TimeField.java @@ -26,7 +26,7 @@ public class TimeField extends JTextField { private static final long serialVersionUID = 1446285867560827423L; - private LogEntry entry; + private final LogEntry entry; private String savedTime = null; public TimeField(LogEntry entry) { diff --git a/src/exporter/LogExporter.java b/src/exporter/LogExporter.java index 56066cc4..38973eb6 100644 --- a/src/exporter/LogExporter.java +++ b/src/exporter/LogExporter.java @@ -9,8 +9,9 @@ import java.io.IOException; import java.io.EOFException; import java.io.BufferedInputStream; -import java.io.FileInputStream; import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Paths; ///... @@ -32,10 +33,7 @@ public static void main(String[] args) GameControlData gcd = null; // Pointer to last packet from GameController char currentGameState = 'X'; // Current game state - ObjectInputStream stream = null; - try { - // Open file: - stream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(logfile))); + try (ObjectInputStream stream = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(Paths.get(logfile))))) { // Print header to console: System.out.println("Timestamp;Game State;Team;Player;Penalized;Pose X;Pose Y"); while(true) { @@ -80,10 +78,10 @@ else if(gcd.team[0].teamNumber != teamNum) { case GameControlData.STATE_SET: currentGameState = 'S'; break; } } - } else if (stream.readInt() == 1) { - // current event is a timeout of the GameController connection - // nothing to do here now... - } + } /*else if (stream.readInt() == 1) { + current event is a timeout of the GameController connection + nothing to do here now... + }*/ } } catch (EOFException e) { @@ -92,12 +90,6 @@ else if(gcd.team[0].teamNumber != teamNum) { } catch (IOException | ClassNotFoundException e) { System.out.println("Exception: " + e); - } finally { - try { - if(stream != null) - stream.close(); - } catch (IOException ex) { - } } } } diff --git a/src/teamcomm/Config.java b/src/teamcomm/Config.java index 798d6aaa..b0ef35c5 100644 --- a/src/teamcomm/Config.java +++ b/src/teamcomm/Config.java @@ -4,12 +4,12 @@ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.HashMap; /** @@ -35,7 +35,7 @@ public static Config getInstance() { @SuppressWarnings("unchecked") private Config() { HashMap m = new HashMap<>(); - try (final ObjectInputStream stream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(CONFIG_FILE)))) { + try (final ObjectInputStream stream = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(Paths.get(CONFIG_FILE))))) { final Object o = stream.readObject(); if (m.getClass().isInstance(o)) { m = (HashMap) o; @@ -55,7 +55,7 @@ public void set(final String key, final Serializable config) { public void flush() { if (!map.isEmpty()) { - try (final ObjectOutputStream stream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(CONFIG_FILE)))) { + try (final ObjectOutputStream stream = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(Paths.get(CONFIG_FILE))))) { stream.writeObject(map); stream.flush(); } catch (IOException ex) { diff --git a/src/teamcomm/PluginLoader.java b/src/teamcomm/PluginLoader.java index e43c9f48..7cd571fd 100644 --- a/src/teamcomm/PluginLoader.java +++ b/src/teamcomm/PluginLoader.java @@ -3,7 +3,6 @@ import common.Log; import data.SPLTeamMessage; import java.io.File; -import java.io.FilenameFilter; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; @@ -101,7 +100,6 @@ public RobotDetailFrame createRobotDetailFrame(final RobotState robot, final JPa try { return c.getConstructor(RobotState.class, JPanel.class).newInstance(robot, anchor); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); Log.error(e.getClass().getSimpleName() + " was thrown while initializing custom RobotDetailFrame " + c.getName() + ": " + e.getMessage()); } } @@ -127,7 +125,7 @@ public Collection getCommonDrawings() { public Collection getDrawings(final int teamNumber) { final Collection ds = pluginsDisabled && teamNumber != TEAMNUMBER_COMMON ? null : drawings.get(teamNumber); - return ds != null ? ds : new ArrayList(0); + return ds != null ? ds : new ArrayList<>(0); } /** @@ -161,14 +159,11 @@ public void update(final Set teamNumbers) { } // Find dirs that correspond to team numbers - final File[] pluginDirs = pluginDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(final File dir, final String name) { - try { - return teamNumbers.contains(Integer.parseInt(name)); - } catch (NumberFormatException e) { - return false; - } + final File[] pluginDirs = pluginDir.listFiles((dir, name) -> { + try { + return teamNumbers.contains(Integer.parseInt(name)); + } catch (NumberFormatException e) { + return false; } }); @@ -211,7 +206,7 @@ private void scanJar(final File file, final int teamNumber) { while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class")) { - classNames.add(entry.getName().substring(0, entry.getName().length() - 6).replaceAll("/", "\\.")); + classNames.add(entry.getName().substring(0, entry.getName().length() - 6).replaceAll("/", ".")); } } } @@ -241,11 +236,7 @@ private void scanJar(final File file, final int teamNumber) { } else if (PerPlayer.class.isAssignableFrom(cls) || PerPlayerWithTeam.class.isAssignableFrom(cls) || Static.class.isAssignableFrom(cls)) { // Class is a drawing: add it to the team drawings // if it does not yet exist - Collection drawingsForTeam = drawings.get(teamNumber); - if (drawingsForTeam == null) { - drawingsForTeam = new LinkedList<>(); - drawings.put(teamNumber, drawingsForTeam); - } + Collection drawingsForTeam = drawings.computeIfAbsent(teamNumber, k -> new LinkedList<>()); for (final Drawing d : drawingsForTeam) { if (cls.isInstance(d)) { continue classLoop; diff --git a/src/teamcomm/TeamCommunicationMonitor.java b/src/teamcomm/TeamCommunicationMonitor.java index 23350572..3f48a137 100644 --- a/src/teamcomm/TeamCommunicationMonitor.java +++ b/src/teamcomm/TeamCommunicationMonitor.java @@ -42,8 +42,8 @@ public class TeamCommunicationMonitor { public static void main(final String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); GameControlDataReceiver gcDataReceiver = null; - GameControlReturnDataReceiverTCM gcReturnDataReceiver = null; - SPLTeamMessageReceiverTCM receiver = null; + GameControlReturnDataReceiverTCM gcReturnDataReceiver; + SPLTeamMessageReceiverTCM receiver; parseArgs(args); @@ -149,7 +149,7 @@ public static void main(final String[] args) { if (!forceEnablePlugins) { PluginLoader.getInstance().disablePlugins(); } - } else if (!gsvMode) { + } else { if (gsvView != null) { gsvView.terminate(); gsvView = null; diff --git a/src/teamcomm/data/GameState.java b/src/teamcomm/data/GameState.java index c505bb8c..e41517dd 100644 --- a/src/teamcomm/data/GameState.java +++ b/src/teamcomm/data/GameState.java @@ -65,26 +65,22 @@ public class GameState implements GameControlDataEventListener { private final Map> robots = new HashMap<>(); - private static final Comparator playerNumberComparator = new Comparator() { - @Override - public int compare(RobotState o1, RobotState o2) { - if (o1.getPlayerNumber() == null) { - if (o2.getPlayerNumber() == null) { - return o1.hashCode() - o2.hashCode(); - } - return -1; - } else if (o2.getPlayerNumber() == null) { - return 1; + private static final Comparator playerNumberComparator = (o1, o2) -> { + if (o1.getPlayerNumber() == null) { + if (o2.getPlayerNumber() == null) { + return o1.hashCode() - o2.hashCode(); } - return o1.getPlayerNumber() - o2.getPlayerNumber(); + return -1; + } else if (o2.getPlayerNumber() == null) { + return 1; } + return o1.getPlayerNumber() - o2.getPlayerNumber(); }; private final HashMap robotsByAddress = new HashMap<>(); private final EventListenerList listeners = new EventListenerList(); - private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private final ScheduledFuture taskHandle; /** @@ -97,65 +93,57 @@ public static GameState getInstance() { } private GameState() { - taskHandle = scheduler.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - if (!(LogReplayer.getInstance().isReplaying() && LogReplayer.getInstance().isPaused())) { - // Check if the GameController is running - try { - final ApplicationLock lock = new ApplicationLock("GameController"); - if (!lock.acquire()) { - // Do not log messages if a GameController is running on the same system - Logger.getInstance().disableLogging(); - } else { - Logger.getInstance().enableLogging(); - lock.release(); - } - } catch (IOException e) { + ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + taskHandle = scheduler.scheduleAtFixedRate(() -> { + if (!(LogReplayer.getInstance().isReplaying() && LogReplayer.getInstance().isPaused())) { + // Check if the GameController is running + try { + final ApplicationLock lock = new ApplicationLock("GameController"); + if (!lock.acquire()) { + // Do not log messages if a GameController is running on the same system + Logger.getInstance().disableLogging(); + } else { + Logger.getInstance().enableLogging(); + lock.release(); } + } catch (IOException e) { + } - // Update robots - int changed = 0; - synchronized (robotsByAddress) { - final Iterator iter = robotsByAddress.values().iterator(); - while (iter.hasNext()) { - final RobotState r = iter.next(); - if (r.updateConnectionStatus() == RobotState.ConnectionStatus.INACTIVE) { - iter.remove(); - } - } - - for (final Entry> team : robots.entrySet()) { - final Iterator it = team.getValue().iterator(); - while (it.hasNext()) { - final RobotState r = it.next(); - if (!robotsByAddress.containsKey(r.getAddress())) { - it.remove(); - - synchronized (teamNumbers) { - if (team.getKey() == teamNumbers[TEAM_LEFT]) { - changed |= CHANGED_LEFT; - if (team.getValue().isEmpty() && lastGameControlData == null) { - teamNumbers[TEAM_LEFT] = 0; - } - } else if (team.getKey() == teamNumbers[TEAM_RIGHT]) { - changed |= CHANGED_RIGHT; - if (team.getValue().isEmpty() && lastGameControlData == null) { - teamNumbers[TEAM_RIGHT] = 0; - } - } else { - changed |= CHANGED_OTHER; + // Update robots + int changed = 0; + synchronized (robotsByAddress) { + robotsByAddress.values().removeIf(r -> r.updateConnectionStatus() == RobotState.ConnectionStatus.INACTIVE); + + for (final Entry> team : robots.entrySet()) { + final Iterator it = team.getValue().iterator(); + while (it.hasNext()) { + final RobotState r = it.next(); + if (!robotsByAddress.containsKey(r.getAddress())) { + it.remove(); + + synchronized (teamNumbers) { + if (team.getKey() == teamNumbers[TEAM_LEFT]) { + changed |= CHANGED_LEFT; + if (team.getValue().isEmpty() && lastGameControlData == null) { + teamNumbers[TEAM_LEFT] = 0; + } + } else if (team.getKey() == teamNumbers[TEAM_RIGHT]) { + changed |= CHANGED_RIGHT; + if (team.getValue().isEmpty() && lastGameControlData == null) { + teamNumbers[TEAM_RIGHT] = 0; } + } else { + changed |= CHANGED_OTHER; } } } } } - - sendEvents(changed); } + + sendEvents(changed); } - }, RobotState.ConnectionStatus.HIGH_LATENCY.threshold * 2, RobotState.ConnectionStatus.HIGH_LATENCY.threshold / 2, TimeUnit.MILLISECONDS); + }, RobotState.ConnectionStatus.HIGH_LATENCY.threshold * 2L, RobotState.ConnectionStatus.HIGH_LATENCY.threshold / 2L, TimeUnit.MILLISECONDS); } /** @@ -346,11 +334,7 @@ public void receiveMessage(final String address, final int teamNumber, final SPL robotsByAddress.put(address, r); } - Collection set = robots.get(teamNumber); - if (set == null) { - set = new HashSet<>(); - robots.put(teamNumber, set); - } + Collection set = robots.computeIfAbsent(teamNumber, k -> new HashSet<>()); if (set.add(r)) { if (teamNumbers[TEAM_LEFT] == teamNumber) { changed |= CHANGED_LEFT; @@ -396,11 +380,7 @@ public void receiveMessage(final String address, final GameControlReturnData mes robotsByAddress.put(address, r); } - Collection set = robots.get((int) message.teamNum); - if (set == null) { - set = new HashSet<>(); - robots.put((int) message.teamNum, set); - } + Collection set = robots.computeIfAbsent((int) message.teamNum, k -> new HashSet<>()); if (set.add(r)) { if (teamNumbers[TEAM_LEFT] == message.teamNum) { changed |= CHANGED_LEFT; @@ -490,7 +470,7 @@ private void fireEvent(final TeamEvent e) { * @param teamNumber number of the team * @param playerNumber number of the player * @return the team color - * @see TeamInfo#teamColor + * @see TeamInfo#fieldPlayerColor and TeamInfo#goalkeeperColor */ public int getTeamColor(final int teamNumber, final int playerNumber) { if (lastGameControlData == null || (lastGameControlData.team[0].teamNumber != teamNumber && lastGameControlData.team[1].teamNumber != teamNumber)) { diff --git a/src/teamcomm/data/RobotState.java b/src/teamcomm/data/RobotState.java index 4048a006..5c39480a 100644 --- a/src/teamcomm/data/RobotState.java +++ b/src/teamcomm/data/RobotState.java @@ -16,7 +16,7 @@ */ public class RobotState { - public static enum ConnectionStatus { + public enum ConnectionStatus { INACTIVE(10000), OFFLINE(5000), @@ -25,7 +25,7 @@ public static enum ConnectionStatus { public final int threshold; - private ConnectionStatus(final int threshold) { + ConnectionStatus(final int threshold) { this.threshold = threshold; } } @@ -149,7 +149,7 @@ public double getTeamMessagesPerSecond() { it.remove(); } - return recentTeamMessageTimestamps.size() > 0 ? ((recentTeamMessageTimestamps.size() - 1) * 1000.0 / Math.max(1000, lastTeamMessageTimestamp - recentTeamMessageTimestamps.getLast())) : 0; + return !recentTeamMessageTimestamps.isEmpty() ? ((recentTeamMessageTimestamps.size() - 1) * 1000.0 / Math.max(1000, lastTeamMessageTimestamp - recentTeamMessageTimestamps.getLast())) : 0; } } @@ -166,7 +166,7 @@ public double getGCRDMessagesPerSecond() { it.remove(); } - return recentGCRDMessageTimestamps.size() > 0 ? ((recentGCRDMessageTimestamps.size() - 1) * 1000.0 / Math.max(1000, lastGCRDMessageTimestamp - recentGCRDMessageTimestamps.getLast())) : 0; + return !recentGCRDMessageTimestamps.isEmpty() ? ((recentGCRDMessageTimestamps.size() - 1) * 1000.0 / Math.max(1000, lastGCRDMessageTimestamp - recentGCRDMessageTimestamps.getLast())) : 0; } } diff --git a/src/teamcomm/data/event/GameControlDataEventListener.java b/src/teamcomm/data/event/GameControlDataEventListener.java index 5442630b..4defbd1b 100644 --- a/src/teamcomm/data/event/GameControlDataEventListener.java +++ b/src/teamcomm/data/event/GameControlDataEventListener.java @@ -15,12 +15,12 @@ public interface GameControlDataEventListener extends EventListener { * * @param e event */ - public void gameControlDataChanged(final GameControlDataEvent e); + void gameControlDataChanged(final GameControlDataEvent e); /** * Called when no data was received from the GameController for some time. * * @param e event */ - public void gameControlDataTimeout(final GameControlDataTimeoutEvent e); + void gameControlDataTimeout(final GameControlDataTimeoutEvent e); } diff --git a/src/teamcomm/data/event/RobotStateEventListener.java b/src/teamcomm/data/event/RobotStateEventListener.java index 6a925bc7..2888d99d 100644 --- a/src/teamcomm/data/event/RobotStateEventListener.java +++ b/src/teamcomm/data/event/RobotStateEventListener.java @@ -15,12 +15,12 @@ public interface RobotStateEventListener extends EventListener { * * @param e event */ - public void robotStateChanged(RobotStateEvent e); + void robotStateChanged(RobotStateEvent e); /** * Called when the state of the robot which sent this event changes. * * @param e event */ - public void connectionStatusChanged(RobotStateEvent e); + void connectionStatusChanged(RobotStateEvent e); } diff --git a/src/teamcomm/data/event/TeamEventListener.java b/src/teamcomm/data/event/TeamEventListener.java index 53ece88f..3c7caf21 100644 --- a/src/teamcomm/data/event/TeamEventListener.java +++ b/src/teamcomm/data/event/TeamEventListener.java @@ -15,5 +15,5 @@ public interface TeamEventListener extends EventListener { * * @param e event */ - public void teamChanged(TeamEvent e); + void teamChanged(TeamEvent e); } diff --git a/src/teamcomm/gui/LogReplayFrame.java b/src/teamcomm/gui/LogReplayFrame.java index 8f05f483..f7794166 100644 --- a/src/teamcomm/gui/LogReplayFrame.java +++ b/src/teamcomm/gui/LogReplayFrame.java @@ -2,8 +2,6 @@ import java.awt.Dimension; import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.Box; @@ -56,90 +54,66 @@ public LogReplayFrame(final JFrame parent) { this.parent = parent; final LogReplayFrame frame = this; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setDefaultCloseOperation(HIDE_ON_CLOSE); - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - LogReplayer.getInstance().close(); - } - }); - - final JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); - contentPane.setBorder(new EmptyBorder(5, 5, 10, 5)); - setContentPane(contentPane); - - final JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.X_AXIS)); - infoPanel.setBorder(new EmptyBorder(5, 8, 5, 8)); - stateLabel.setHorizontalAlignment(SwingConstants.LEFT); - infoPanel.add(stateLabel); - infoPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); - timeLabel.setHorizontalAlignment(SwingConstants.RIGHT); - infoPanel.add(timeLabel); - contentPane.add(infoPanel); - - contentPane.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(0, 32767))); - - final JPanel controlsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0)); - fastRewindButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (lastSpeed < 0) { - LogReplayer.getInstance().setPlaybackSpeed(Math.max(lastSpeed * 2, -MAX_REPLAY_SPEED)); - } else { - LogReplayer.getInstance().setPlaybackSpeed(-2); - } - } - }); - controlsPanel.add(fastRewindButton); - controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); - rewindButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - LogReplayer.getInstance().setPlaybackSpeed(-1); - } - }); - controlsPanel.add(rewindButton); - controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); - pauseButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - LogReplayer.getInstance().setPlaybackSpeed(0); - } - }); - controlsPanel.add(pauseButton); - controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); - playButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - LogReplayer.getInstance().setPlaybackSpeed(1); - } - }); - controlsPanel.add(playButton); - controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); - fastForwardButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (lastSpeed > 0) { - LogReplayer.getInstance().setPlaybackSpeed(Math.min(lastSpeed * 2, MAX_REPLAY_SPEED)); - } else { - LogReplayer.getInstance().setPlaybackSpeed(2); - } - } - }); - controlsPanel.add(fastForwardButton); - contentPane.add(controlsPanel); - - setAlwaysOnTop(true); - setResizable(false); - pack(); - - LogReplayer.getInstance().addListener(frame); - } + SwingUtilities.invokeLater(() -> { + setDefaultCloseOperation(HIDE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + LogReplayer.getInstance().close(); + } + }); + + final JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); + contentPane.setBorder(new EmptyBorder(5, 5, 10, 5)); + setContentPane(contentPane); + + final JPanel infoPanel = new JPanel(); + infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.X_AXIS)); + infoPanel.setBorder(new EmptyBorder(5, 8, 5, 8)); + stateLabel.setHorizontalAlignment(SwingConstants.LEFT); + infoPanel.add(stateLabel); + infoPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); + timeLabel.setHorizontalAlignment(SwingConstants.RIGHT); + infoPanel.add(timeLabel); + contentPane.add(infoPanel); + + contentPane.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(0, 32767))); + + final JPanel controlsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0)); + fastRewindButton.addActionListener(e -> { + if (lastSpeed < 0) { + LogReplayer.getInstance().setPlaybackSpeed(Math.max(lastSpeed * 2, -MAX_REPLAY_SPEED)); + } else { + LogReplayer.getInstance().setPlaybackSpeed(-2); + } + }); + controlsPanel.add(fastRewindButton); + controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); + rewindButton.addActionListener(e -> LogReplayer.getInstance().setPlaybackSpeed(-1)); + controlsPanel.add(rewindButton); + controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); + pauseButton.addActionListener(e -> LogReplayer.getInstance().setPlaybackSpeed(0)); + controlsPanel.add(pauseButton); + controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); + playButton.addActionListener(e -> LogReplayer.getInstance().setPlaybackSpeed(1)); + controlsPanel.add(playButton); + controlsPanel.add(new Box.Filler(new Dimension(), new Dimension(), new Dimension(32767, 0))); + fastForwardButton.addActionListener(e -> { + if (lastSpeed > 0) { + LogReplayer.getInstance().setPlaybackSpeed(Math.min(lastSpeed * 2, MAX_REPLAY_SPEED)); + } else { + LogReplayer.getInstance().setPlaybackSpeed(2); + } + }); + controlsPanel.add(fastForwardButton); + contentPane.add(controlsPanel); + + setAlwaysOnTop(true); + setResizable(false); + pack(); + + LogReplayer.getInstance().addListener(frame); }); } diff --git a/src/teamcomm/gui/MainWindow.java b/src/teamcomm/gui/MainWindow.java index cb8af77b..1d2f2450 100644 --- a/src/teamcomm/gui/MainWindow.java +++ b/src/teamcomm/gui/MainWindow.java @@ -4,11 +4,8 @@ import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; @@ -64,13 +61,8 @@ public class MainWindow extends JFrame implements TeamEventListener { public MainWindow() { super("TeamCommunicationMonitor"); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - // Initialize - initialize(); - } - }); + // Initialize + SwingUtilities.invokeLater(this::initialize); } /** @@ -81,26 +73,23 @@ public void run() { * @param file log file to replay. */ public void replayLogFile(final File file) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { + SwingUtilities.invokeLater(() -> { + try { try { - try { - Config.getInstance().set("ReplayLogfileDir", file.getParentFile().getCanonicalPath()); - } catch (IOException ex) { - Config.getInstance().set("ReplayLogfileDir", file.getParentFile().getAbsolutePath()); - } - LogReplayer.getInstance().open(file); + Config.getInstance().set("ReplayLogfileDir", file.getParentFile().getCanonicalPath()); } catch (IOException ex) { - Log.error("Could not open log file for replay: " + file); + Config.getInstance().set("ReplayLogfileDir", file.getParentFile().getAbsolutePath()); } + LogReplayer.getInstance().open(file); + } catch (IOException ex) { + Log.error("Could not open log file for replay: " + file); } }); } private void initialize() { // Setup window - getRootPane().putClientProperty("apple.awt.fullscreenable", Boolean.valueOf(true)); + getRootPane().putClientProperty("apple.awt.fullscreenable", true); setLocationByPlatform(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { @@ -155,58 +144,44 @@ public void windowClosed(WindowEvent e) { private JMenu createFileMenu() { final JMenu fileMenu = new JMenu("File"); final JMenuItem resetItem = new JMenuItem("Reset"); - resetItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - GameState.getInstance().reset(); - } - }); + resetItem.addActionListener(e -> GameState.getInstance().reset()); resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); fileMenu.add(resetItem); final JMenuItem replayItem = new JMenuItem("Replay log file"); fileMenu.add(replayItem); - replayItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - final String dir = (String) Config.getInstance().get("ReplayLogfileDir"); - final JFileChooser fc = new JFileChooser(dir == null ? new File(new File(".").getAbsoluteFile(), "logs_teamcomm") : new File(dir)); - if (fc.showOpenDialog(MainWindow.this) == JFileChooser.APPROVE_OPTION) { + replayItem.addActionListener(e -> { + final String dir = (String) Config.getInstance().get("ReplayLogfileDir"); + final JFileChooser fc = new JFileChooser(dir == null ? new File(new File(".").getAbsoluteFile(), "logs_teamcomm") : new File(dir)); + if (fc.showOpenDialog(MainWindow.this) == JFileChooser.APPROVE_OPTION) { + try { try { - try { - Config.getInstance().set("ReplayLogfileDir", fc.getSelectedFile().getParentFile().getCanonicalPath()); - } catch (IOException ex) { - Config.getInstance().set("ReplayLogfileDir", fc.getSelectedFile().getParentFile().getAbsolutePath()); - } - LogReplayer.getInstance().open(fc.getSelectedFile()); + Config.getInstance().set("ReplayLogfileDir", fc.getSelectedFile().getParentFile().getCanonicalPath()); } catch (IOException ex) { - JOptionPane.showMessageDialog(null, - "Error opening log file.", - ex.getClass().getSimpleName(), - JOptionPane.ERROR_MESSAGE); + Config.getInstance().set("ReplayLogfileDir", fc.getSelectedFile().getParentFile().getAbsolutePath()); } + LogReplayer.getInstance().open(fc.getSelectedFile()); + } catch (IOException ex) { + JOptionPane.showMessageDialog(null, + "Error opening log file.", + ex.getClass().getSimpleName(), + JOptionPane.ERROR_MESSAGE); } } }); replayItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); final JMenuItem switchItem = new JMenuItem("Switch to GameStateVisualizer"); - switchItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - TeamCommunicationMonitor.switchToGSV(); - setVisible(false); - } + switchItem.addActionListener(e -> { + TeamCommunicationMonitor.switchToGSV(); + setVisible(false); }); fileMenu.add(switchItem); final JMenuItem exitItem = new JMenuItem("Exit"); - exitItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - TeamCommunicationMonitor.shutdown(); - setVisible(false); - } + exitItem.addActionListener(e -> { + TeamCommunicationMonitor.shutdown(); + setVisible(false); }); fileMenu.add(exitItem); @@ -218,12 +193,7 @@ private JMenu createViewMenu() { // Mirroring final JCheckBoxMenuItem mirrorOption = new JCheckBoxMenuItem("Mirror", GameState.getInstance().isMirrored()); - mirrorOption.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(final ItemEvent e) { - GameState.getInstance().setMirrored(e.getStateChange() == ItemEvent.SELECTED); - } - }); + mirrorOption.addItemListener(e -> GameState.getInstance().setMirrored(e.getStateChange() == ItemEvent.SELECTED)); viewMenu.add(mirrorOption); // Drawings @@ -242,43 +212,40 @@ public void terminate() { @Override public void teamChanged(final TeamEvent e) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (e.side != GameState.TEAM_OTHER) { - teamLogos[e.side].setIcon(TeamLogoLoader.getInstance().getTeamLogoPanelIcon(e.teamNumber)); - } + SwingUtilities.invokeLater(() -> { + if (e.side != GameState.TEAM_OTHER) { + teamLogos[e.side].setIcon(TeamLogoLoader.getInstance().getTeamLogoPanelIcon(e.teamNumber)); + } - int i = 0; - for (final RobotState r : e.players) { - RobotPanel panel = robotPanels.get(r.getAddress()); - if (panel == null) { - panel = new RobotPanel(r); - robotPanels.put(r.getAddress(), panel); - } + int i = 0; + for (final RobotState r : e.players) { + RobotPanel panel = robotPanels.get(r.getAddress()); + if (panel == null) { + panel = new RobotPanel(r); + robotPanels.put(r.getAddress(), panel); + } - if (teamPanels[e.side].getComponentCount() <= i + (e.side < 2 ? 1 : 0)) { - teamPanels[e.side].add(panel); - panel.revalidate(); - } else if (panel != teamPanels[e.side].getComponent(i + (e.side < 2 ? 1 : 0))) { - teamPanels[e.side].remove(panel); - teamPanels[e.side].add(panel, i + (e.side < 2 ? 1 : 0)); - panel.revalidate(); - } + if (teamPanels[e.side].getComponentCount() <= i + (e.side < 2 ? 1 : 0)) { + teamPanels[e.side].add(panel); + panel.revalidate(); + } else if (panel != teamPanels[e.side].getComponent(i + (e.side < 2 ? 1 : 0))) { + teamPanels[e.side].remove(panel); + teamPanels[e.side].add(panel, i + (e.side < 2 ? 1 : 0)); + panel.revalidate(); + } - panel.setTeamLogoVisible(e.side == GameState.TEAM_OTHER); + panel.setTeamLogoVisible(e.side == GameState.TEAM_OTHER); - i++; - } + i++; + } - while (e.players.size() < teamPanels[e.side].getComponentCount() - (e.side < 2 ? 1 : 0)) { - final RobotPanel panel = (RobotPanel) teamPanels[e.side].getComponent(teamPanels[e.side].getComponentCount() - 1); - teamPanels[e.side].remove(teamPanels[e.side].getComponentCount() - 1); - robotPanels.remove(panel.getRobotAddress()); - panel.dispose(); - } - teamPanels[e.side].repaint(); + while (e.players.size() < teamPanels[e.side].getComponentCount() - (e.side < 2 ? 1 : 0)) { + final RobotPanel panel = (RobotPanel) teamPanels[e.side].getComponent(teamPanels[e.side].getComponentCount() - 1); + teamPanels[e.side].remove(teamPanels[e.side].getComponentCount() - 1); + robotPanels.remove(panel.getRobotAddress()); + panel.dispose(); } + teamPanels[e.side].repaint(); }); } } diff --git a/src/teamcomm/gui/RobotDetailFrame.java b/src/teamcomm/gui/RobotDetailFrame.java index d692de06..f9c7f5cd 100644 --- a/src/teamcomm/gui/RobotDetailFrame.java +++ b/src/teamcomm/gui/RobotDetailFrame.java @@ -31,27 +31,24 @@ public RobotDetailFrame(final RobotState robot, final JPanel anchor) { final RobotStateEventListener listener = this; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - anchor.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - if (!isVisible()) { - setLocationRelativeTo(anchor); - } - setVisible(true); - robotStateChanged(new RobotStateEvent(robot)); - connectionStatusChanged(new RobotStateEvent(robot)); + SwingUtilities.invokeLater(() -> { + setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + anchor.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + if (!isVisible()) { + setLocationRelativeTo(anchor); } + setVisible(true); + robotStateChanged(new RobotStateEvent(robot)); + connectionStatusChanged(new RobotStateEvent(robot)); } - }); + } + }); - init(robot); - robot.addListener(listener); - } + init(robot); + robot.addListener(listener); }); } diff --git a/src/teamcomm/gui/RobotDetailFrameDefault.java b/src/teamcomm/gui/RobotDetailFrameDefault.java index d4a6f972..3f3da1c6 100644 --- a/src/teamcomm/gui/RobotDetailFrameDefault.java +++ b/src/teamcomm/gui/RobotDetailFrameDefault.java @@ -71,12 +71,9 @@ protected void init(final RobotState robot) { @Override public void robotStateChanged(final RobotStateEvent e) { if (isVisible()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - update((RobotState) e.getSource()); - repaint(); - } + SwingUtilities.invokeLater(() -> { + update((RobotState) e.getSource()); + repaint(); }); } } @@ -227,7 +224,7 @@ private void update(final RobotState robot) { contentInCurrentRow = false; sb.setLength(6); } - } else if (row.length() > 0) { + } else if (!row.isEmpty()) { sb.append(row); contentInCurrentRow = true; } diff --git a/src/teamcomm/gui/RobotPanel.java b/src/teamcomm/gui/RobotPanel.java index d630a9b5..ccdc4682 100644 --- a/src/teamcomm/gui/RobotPanel.java +++ b/src/teamcomm/gui/RobotPanel.java @@ -69,78 +69,75 @@ public RobotPanel(final RobotState robot) { this.robot = robot; final RobotPanel robotPanel = this; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(getForeground()), robot.getAddress(), TitledBorder.CENTER, TitledBorder.TOP)); - setLayout(new OverlayLayout(robotPanel)); - setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); - setMaximumSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); - - foregroundPanel.setLayout(new BoxLayout(foregroundPanel, BoxLayout.Y_AXIS)); - foregroundPanel.setOpaque(false); - for (int i = 0; i < 4; i++) { - foregroundPanel.add(new JLabel(" ", JLabel.LEFT)); - } - final JPanel foregroundContainer = new JPanel(); - foregroundContainer.setOpaque(false); - final GroupLayout foregroundContainerLayout = new GroupLayout(foregroundContainer); - foregroundContainer.setLayout(foregroundContainerLayout); - foregroundContainerLayout.setHorizontalGroup( - foregroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) - .addComponent(foregroundPanel, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_WIDTH, Short.MAX_VALUE) - ); - foregroundContainerLayout.setVerticalGroup( - foregroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) - .addComponent(foregroundPanel, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_HEIGHT, Short.MAX_VALUE) - ); - add(foregroundContainer); - - connectionStatus.setIcon(iconOnline); - final JPanel backgroundContainer = new JPanel(); - backgroundContainer.setOpaque(false); - final GroupLayout backgroundContainerLayout = new GroupLayout(backgroundContainer); - backgroundContainer.setLayout(backgroundContainerLayout); - backgroundContainerLayout.setHorizontalGroup( - backgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) - .addGroup(GroupLayout.Alignment.TRAILING, backgroundContainerLayout.createSequentialGroup() - .addGap(0, 220, Short.MAX_VALUE) - .addComponent(connectionStatus)) - ); - backgroundContainerLayout.setVerticalGroup( - backgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) - .addGroup(backgroundContainerLayout.createSequentialGroup() - .addComponent(connectionStatus) - .addGap(0, 181, Short.MAX_VALUE)) - ); - add(backgroundContainer); - - final JPanel backbackgroundContainer = new JPanel(); - backbackgroundContainer.setOpaque(false); - final GroupLayout backbackgroundContainerLayout = new GroupLayout(backbackgroundContainer); - backbackgroundContainer.setLayout(backbackgroundContainerLayout); - backbackgroundContainerLayout.setHorizontalGroup( - backbackgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) - .addComponent(teamLogo, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_WIDTH, Short.MAX_VALUE) - ); - backbackgroundContainerLayout.setVerticalGroup( - backbackgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) - .addComponent(teamLogo, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_HEIGHT, Short.MAX_VALUE) - ); - add(backbackgroundContainer); - - foregroundContainer.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(final ComponentEvent e) { - if (teamLogo.getIcon() != null) { - teamLogo.setIcon(TeamLogoLoader.getInstance().getScaledSemiTransparentTeamLogoIcon(robot.getTeamNumber(), Math.min((PANEL_WIDTH * 3) >> 2, foregroundPanel.getWidth()), Math.min((PANEL_HEIGHT * 3) >> 2, foregroundPanel.getHeight()))); - } + SwingUtilities.invokeLater(() -> { + setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(getForeground()), robot.getAddress(), TitledBorder.CENTER, TitledBorder.TOP)); + setLayout(new OverlayLayout(robotPanel)); + setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); + setMaximumSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); + + foregroundPanel.setLayout(new BoxLayout(foregroundPanel, BoxLayout.Y_AXIS)); + foregroundPanel.setOpaque(false); + for (int i = 0; i < 4; i++) { + foregroundPanel.add(new JLabel(" ", JLabel.LEFT)); + } + final JPanel foregroundContainer = new JPanel(); + foregroundContainer.setOpaque(false); + final GroupLayout foregroundContainerLayout = new GroupLayout(foregroundContainer); + foregroundContainer.setLayout(foregroundContainerLayout); + foregroundContainerLayout.setHorizontalGroup( + foregroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(foregroundPanel, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_WIDTH, Short.MAX_VALUE) + ); + foregroundContainerLayout.setVerticalGroup( + foregroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(foregroundPanel, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_HEIGHT, Short.MAX_VALUE) + ); + add(foregroundContainer); + + connectionStatus.setIcon(iconOnline); + final JPanel backgroundContainer = new JPanel(); + backgroundContainer.setOpaque(false); + final GroupLayout backgroundContainerLayout = new GroupLayout(backgroundContainer); + backgroundContainer.setLayout(backgroundContainerLayout); + backgroundContainerLayout.setHorizontalGroup( + backgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup(GroupLayout.Alignment.TRAILING, backgroundContainerLayout.createSequentialGroup() + .addGap(0, 220, Short.MAX_VALUE) + .addComponent(connectionStatus)) + ); + backgroundContainerLayout.setVerticalGroup( + backgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup(backgroundContainerLayout.createSequentialGroup() + .addComponent(connectionStatus) + .addGap(0, 181, Short.MAX_VALUE)) + ); + add(backgroundContainer); + + final JPanel backbackgroundContainer = new JPanel(); + backbackgroundContainer.setOpaque(false); + final GroupLayout backbackgroundContainerLayout = new GroupLayout(backbackgroundContainer); + backbackgroundContainer.setLayout(backbackgroundContainerLayout); + backbackgroundContainerLayout.setHorizontalGroup( + backbackgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(teamLogo, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_WIDTH, Short.MAX_VALUE) + ); + backbackgroundContainerLayout.setVerticalGroup( + backbackgroundContainerLayout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(teamLogo, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, PANEL_HEIGHT, Short.MAX_VALUE) + ); + add(backbackgroundContainer); + + foregroundContainer.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(final ComponentEvent e) { + if (teamLogo.getIcon() != null) { + teamLogo.setIcon(TeamLogoLoader.getInstance().getScaledSemiTransparentTeamLogoIcon(robot.getTeamNumber(), Math.min((PANEL_WIDTH * 3) >> 2, foregroundPanel.getWidth()), Math.min((PANEL_HEIGHT * 3) >> 2, foregroundPanel.getHeight()))); } - }); + } + }); - update(); - robot.addListener(robotPanel); - } + update(); + robot.addListener(robotPanel); }); detailFrame = PluginLoader.getInstance().createRobotDetailFrame(robot, robotPanel); @@ -176,26 +173,23 @@ public void connectionStatusChanged(final RobotStateEvent e) { private void update() { final DecimalFormat df = new DecimalFormat("#.##"); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (robot.getPlayerNumber() == null || (robot.getLastGCRDMessage() != null && !robot.getLastGCRDMessage().playerNumValid)) { - ((JLabel) foregroundPanel.getComponent(0)).setForeground(Color.red); - ((JLabel) foregroundPanel.getComponent(0)).setText("Player no: " + (robot.getLastGCRDMessage() != null ? robot.getLastGCRDMessage().playerNum : "unknown")); - } else { - ((JLabel) foregroundPanel.getComponent(0)).setForeground(defaultColor); - ((JLabel) foregroundPanel.getComponent(0)).setText("Player no: " + robot.getPlayerNumber()); - } - ((JLabel) foregroundPanel.getComponent(1)).setText("Messages: " + robot.getTeamMessageCount() + " / " + robot.getGCRDMessageCount()); + SwingUtilities.invokeLater(() -> { + if (robot.getPlayerNumber() == null || (robot.getLastGCRDMessage() != null && !robot.getLastGCRDMessage().playerNumValid)) { + foregroundPanel.getComponent(0).setForeground(Color.red); + ((JLabel) foregroundPanel.getComponent(0)).setText("Player no: " + (robot.getLastGCRDMessage() != null ? robot.getLastGCRDMessage().playerNum : "unknown")); + } else { + foregroundPanel.getComponent(0).setForeground(defaultColor); + ((JLabel) foregroundPanel.getComponent(0)).setText("Player no: " + robot.getPlayerNumber()); + } + ((JLabel) foregroundPanel.getComponent(1)).setText("Messages: " + robot.getTeamMessageCount() + " / " + robot.getGCRDMessageCount()); - ((JLabel) foregroundPanel.getComponent(2)).setText("Per second: " + df.format(robot.getTeamMessagesPerSecond()) + " / " + df.format(robot.getGCRDMessagesPerSecond())); - if ((robot.getLastTeamMessage() != null && !robot.getLastTeamMessage().valid) || (robot.getLastGCRDMessage() != null && !robot.getLastGCRDMessage().valid)) { - ((JLabel) foregroundPanel.getComponent(3)).setForeground(Color.red); - } else { - ((JLabel) foregroundPanel.getComponent(3)).setForeground(defaultColor); - } - ((JLabel) foregroundPanel.getComponent(3)).setText("Illegal: " + robot.getIllegalTeamMessageCount() + " (" + Math.round(robot.getIllegalTeamMessageRatio() * 100.0) + "%) / " + robot.getIllegalGCRDMessageCount() + " (" + Math.round(robot.getIllegalGCRDMessageCount() * 100.0) + "%)"); + ((JLabel) foregroundPanel.getComponent(2)).setText("Per second: " + df.format(robot.getTeamMessagesPerSecond()) + " / " + df.format(robot.getGCRDMessagesPerSecond())); + if ((robot.getLastTeamMessage() != null && !robot.getLastTeamMessage().valid) || (robot.getLastGCRDMessage() != null && !robot.getLastGCRDMessage().valid)) { + foregroundPanel.getComponent(3).setForeground(Color.red); + } else { + foregroundPanel.getComponent(3).setForeground(defaultColor); } + ((JLabel) foregroundPanel.getComponent(3)).setText("Illegal: " + robot.getIllegalTeamMessageCount() + " (" + Math.round(robot.getIllegalTeamMessageRatio() * 100.0) + "%) / " + robot.getIllegalGCRDMessageCount() + " (" + Math.round(robot.getIllegalGCRDMessageCount() * 100.0) + "%)"); }); } @@ -207,19 +201,9 @@ public void run() { */ public void setTeamLogoVisible(final boolean toggle) { if (toggle) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - teamLogo.setIcon(TeamLogoLoader.getInstance().getScaledSemiTransparentTeamLogoIcon(robot.getTeamNumber(), Math.min((PANEL_WIDTH * 3) >> 2, Math.max(PANEL_WIDTH >> 2, foregroundPanel.getWidth())), Math.min((PANEL_HEIGHT * 3) >> 2, Math.max(PANEL_HEIGHT >> 2, foregroundPanel.getHeight())))); - } - }); + SwingUtilities.invokeLater(() -> teamLogo.setIcon(TeamLogoLoader.getInstance().getScaledSemiTransparentTeamLogoIcon(robot.getTeamNumber(), Math.min((PANEL_WIDTH * 3) >> 2, Math.max(PANEL_WIDTH >> 2, foregroundPanel.getWidth())), Math.min((PANEL_HEIGHT * 3) >> 2, Math.max(PANEL_HEIGHT >> 2, foregroundPanel.getHeight()))))); } else { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - teamLogo.setIcon(null); - } - }); + SwingUtilities.invokeLater(() -> teamLogo.setIcon(null)); } } diff --git a/src/teamcomm/gui/TeamLogoLoader.java b/src/teamcomm/gui/TeamLogoLoader.java index 5faad8b9..75499adb 100644 --- a/src/teamcomm/gui/TeamLogoLoader.java +++ b/src/teamcomm/gui/TeamLogoLoader.java @@ -102,7 +102,7 @@ public ImageIcon getScaledTeamLogoIcon(final int team, final int width, final in if (image == null) { return null; } else { - final double scaleFactor = Math.min((double) width / image.getWidth(null), (double) height / image.getHeight(null));; + final double scaleFactor = Math.min((double) width / image.getWidth(null), (double) height / image.getHeight(null)); return new ImageIcon(image.getScaledInstance( (int) (image.getWidth(null) * scaleFactor), (int) (image.getHeight(null) * scaleFactor), @@ -136,7 +136,7 @@ public ImageIcon getScaledSemiTransparentTeamLogoIcon(final int team, final int semiTransparentLogos.put(team, image); } - final double scaleFactor = Math.min((double) width / image.getWidth(null), (double) height / image.getHeight(null));; + final double scaleFactor = Math.min((double) width / image.getWidth(null), (double) height / image.getHeight(null)); return new ImageIcon(image.getScaledInstance( (int) (image.getWidth(null) * scaleFactor), (int) (image.getHeight(null) * scaleFactor), diff --git a/src/teamcomm/gui/View3D.java b/src/teamcomm/gui/View3D.java index ce3875ee..f04bf1dc 100644 --- a/src/teamcomm/gui/View3D.java +++ b/src/teamcomm/gui/View3D.java @@ -9,7 +9,6 @@ import com.jogamp.opengl.util.AnimatorBase; import common.Log; import java.nio.FloatBuffer; -import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; @@ -47,20 +46,17 @@ public abstract class View3D implements GLEventListener, TeamEventListener { private int width = 0; private int height = 0; - protected static final Comparator drawingComparator = new Comparator() { - @Override - public int compare(final Drawing o1, final Drawing o2) { - // opaque objects have priority over transparent objects - if (o1.hasAlpha() && !o2.hasAlpha()) { - return 1; - } - if (!o1.hasAlpha() && o2.hasAlpha()) { - return -1; - } - - // higher priorities are drawn earlier - return o2.getPriority() - o1.getPriority(); + protected static final Comparator drawingComparator = (o1, o2) -> { + // opaque objects have priority over transparent objects + if (o1.hasAlpha() && !o2.hasAlpha()) { + return 1; } + if (!o1.hasAlpha() && o2.hasAlpha()) { + return -1; + } + + // higher priorities are drawn earlier + return o2.getPriority() - o1.getPriority(); }; protected final List drawings = new LinkedList<>(); @@ -137,7 +133,7 @@ public void init(final GLAutoDrawable glad) { // Setup common drawings drawings.addAll(PluginLoader.getInstance().getCommonDrawings()); - Collections.sort(drawings, drawingComparator); + drawings.sort(drawingComparator); for (final Drawing d : drawings) { d.initialize(gl); } diff --git a/src/teamcomm/gui/View3DCanvas.java b/src/teamcomm/gui/View3DCanvas.java index 1d696824..010497b5 100644 --- a/src/teamcomm/gui/View3DCanvas.java +++ b/src/teamcomm/gui/View3DCanvas.java @@ -6,11 +6,7 @@ import com.jogamp.opengl.awt.GLJPanel; import com.jogamp.opengl.util.FPSAnimator; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.util.Collections; import java.util.HashMap; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; @@ -75,12 +71,7 @@ public void mouseDragged(final MouseEvent e) { }; canvas.addMouseListener(listener); canvas.addMouseMotionListener(listener); - canvas.addMouseWheelListener(new MouseWheelListener() { - @Override - public void mouseWheelMoved(final MouseWheelEvent e) { - camera.addRadius((float) (-e.getPreciseWheelRotation() * 0.05)); - } - }); + canvas.addMouseWheelListener(e -> camera.addRadius((float) (-e.getPreciseWheelRotation() * 0.05))); // Start rendering animator = new FPSAnimator(autoDrawable, ANIMATION_FPS); @@ -123,12 +114,7 @@ private void updateDrawingsMenu() { // Create menu items for drawings for (final Drawing d : drawings) { final JCheckBoxMenuItem m = new JCheckBoxMenuItem(d.getClass().getSimpleName(), d.isActive()); - m.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(final ItemEvent e) { - d.setActive(e.getStateChange() == ItemEvent.SELECTED); - } - }); + m.addItemListener(e -> d.setActive(e.getStateChange() == ItemEvent.SELECTED)); final JMenu submenu = submenus.get(d.getTeamNumber()); if (submenu != null) { submenu.add(m); @@ -169,7 +155,7 @@ public void teamChanged(final TeamEvent e) { if (teamNumbers[1] != PluginLoader.TEAMNUMBER_COMMON) { drawings.addAll(PluginLoader.getInstance().getDrawings(teamNumbers[1])); } - Collections.sort(drawings, drawingComparator); + drawings.sort(drawingComparator); updateDrawingsMenu(); } } diff --git a/src/teamcomm/gui/View3DGSV.java b/src/teamcomm/gui/View3DGSV.java index c97b811b..c15ace37 100644 --- a/src/teamcomm/gui/View3DGSV.java +++ b/src/teamcomm/gui/View3DGSV.java @@ -21,14 +21,11 @@ import java.awt.Rectangle; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.IOException; -import java.util.Collections; import javax.swing.JFrame; import javax.swing.SwingUtilities; import teamcomm.PluginLoader; @@ -94,100 +91,94 @@ public View3DGSV(final boolean forceWindowed) { autoDrawable.addGLEventListener(this); // Initialize - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!forceWindowed) { - // Display on external display if possible. - final GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); - currentScreenDevice = devices[devices[0].equals( - GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()) ? devices.length - 1 : 0]; - final Rectangle bounds = currentScreenDevice.getDefaultConfiguration().getBounds(); - window.setLocation((int) bounds.getX(), (int) bounds.getY()); - canvas.setPreferredSize(bounds.getSize()); - window.setUndecorated(true); - window.setResizable(false); - currentScreenDevice.setFullScreenWindow(window); - } else { - canvas.setPreferredSize(new Dimension(640, 480)); - window.setUndecorated(false); - } + SwingUtilities.invokeLater(() -> { + if (!forceWindowed) { + // Display on external display if possible. + final GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); + currentScreenDevice = devices[devices[0].equals( + GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()) ? devices.length - 1 : 0]; + final Rectangle bounds = currentScreenDevice.getDefaultConfiguration().getBounds(); + window.setLocation((int) bounds.getX(), (int) bounds.getY()); + canvas.setPreferredSize(bounds.getSize()); + window.setUndecorated(true); + window.setResizable(false); + currentScreenDevice.setFullScreenWindow(window); + } else { + canvas.setPreferredSize(new Dimension(640, 480)); + window.setUndecorated(false); + } - // Setup keyboard / mouse interaction - canvas.addMouseWheelListener(new MouseWheelListener() { - @Override - public void mouseWheelMoved(final MouseWheelEvent me) { - camera.addRadius((float) (-me.getPreciseWheelRotation() * 0.05)); - camera.shiftToBottom(NEAR_FIELD_BORDER_Y); - } - }); - canvas.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(final KeyEvent ke) { - switch (ke.getKeyCode()) { - case KeyEvent.VK_ESCAPE: - TeamCommunicationMonitor.shutdown(); - window.setVisible(false); - break; - case KeyEvent.VK_F2: - TeamCommunicationMonitor.switchToTCM(); - window.setVisible(false); - break; - case KeyEvent.VK_UP: - case KeyEvent.VK_PLUS: - camera.addRadius(-0.05f * ((ke.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0 ? 2 : 1)); - camera.shiftToBottom(NEAR_FIELD_BORDER_Y); - break; - case KeyEvent.VK_DOWN: - case KeyEvent.VK_MINUS: - camera.addRadius(0.05f * ((ke.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0 ? 2 : 1)); - camera.shiftToBottom(NEAR_FIELD_BORDER_Y); - break; - } + // Setup keyboard / mouse interaction + canvas.addMouseWheelListener(me -> { + camera.addRadius((float) (-me.getPreciseWheelRotation() * 0.05)); + camera.shiftToBottom(NEAR_FIELD_BORDER_Y); + }); + canvas.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(final KeyEvent ke) { + switch (ke.getKeyCode()) { + case KeyEvent.VK_ESCAPE: + TeamCommunicationMonitor.shutdown(); + window.setVisible(false); + break; + case KeyEvent.VK_F2: + TeamCommunicationMonitor.switchToTCM(); + window.setVisible(false); + break; + case KeyEvent.VK_UP: + case KeyEvent.VK_PLUS: + camera.addRadius(-0.05f * ((ke.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0 ? 2 : 1)); + camera.shiftToBottom(NEAR_FIELD_BORDER_Y); + break; + case KeyEvent.VK_DOWN: + case KeyEvent.VK_MINUS: + camera.addRadius(0.05f * ((ke.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0 ? 2 : 1)); + camera.shiftToBottom(NEAR_FIELD_BORDER_Y); + break; } + } - @Override - public void keyReleased(final KeyEvent ke) { - if ((ke.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) != 0) { - if (!forceWindowed && (ke.getKeyCode() == KeyEvent.VK_LEFT || ke.getKeyCode() == KeyEvent.VK_RIGHT)) { - final GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); - if (devices.length > 1) { - int i; - for (i = 0; i < devices.length; i++) { - if (devices[i].equals(currentScreenDevice)) { - break; - } + @Override + public void keyReleased(final KeyEvent ke) { + if ((ke.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) != 0) { + if (!forceWindowed && (ke.getKeyCode() == KeyEvent.VK_LEFT || ke.getKeyCode() == KeyEvent.VK_RIGHT)) { + final GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); + if (devices.length > 1) { + int i; + for (i = 0; i < devices.length; i++) { + if (devices[i].equals(currentScreenDevice)) { + break; } - animator.pause(); - currentScreenDevice.setFullScreenWindow(null); - currentScreenDevice = devices[(i + (ke.getKeyCode() == KeyEvent.VK_LEFT ? -1 : 1) + devices.length) % devices.length]; - final Rectangle bounds = currentScreenDevice.getDefaultConfiguration().getBounds(); - window.setLocation((int) bounds.getX(), (int) bounds.getY()); - canvas.setPreferredSize(bounds.getSize()); - currentScreenDevice.setFullScreenWindow(window); - window.pack(); - animator.resume(); } + animator.pause(); + currentScreenDevice.setFullScreenWindow(null); + currentScreenDevice = devices[(i + (ke.getKeyCode() == KeyEvent.VK_LEFT ? -1 : 1) + devices.length) % devices.length]; + final Rectangle bounds = currentScreenDevice.getDefaultConfiguration().getBounds(); + window.setLocation((int) bounds.getX(), (int) bounds.getY()); + canvas.setPreferredSize(bounds.getSize()); + currentScreenDevice.setFullScreenWindow(window); + window.pack(); + animator.resume(); } } } - }); - window.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(final WindowEvent e) { - TeamCommunicationMonitor.shutdown(); - } - }); + } + }); + window.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(final WindowEvent e) { + TeamCommunicationMonitor.shutdown(); + } + }); - // Start rendering - animator = new FPSAnimator(autoDrawable, ANIMATION_FPS); - animator.start(); + // Start rendering + animator = new FPSAnimator(autoDrawable, ANIMATION_FPS); + animator.start(); - // Pack the window - window.add(canvas, BorderLayout.CENTER); - window.pack(); - window.setVisible(true); - } + // Pack the window + window.add(canvas, BorderLayout.CENTER); + window.pack(); + window.setVisible(true); }); } @@ -242,22 +233,19 @@ public void reshape(final GLAutoDrawable glad, final int x, final int y, final i textRendererSizes[RENDERER_TIME] = 120 * window.getWidth() / 1920; textRendererSizes[RENDERER_SCORE] = window.getWidth() / 6; for (int i = 0; i < textRenderers.length; i++) { - textRenderers[i] = new TextRenderer(new Font(Font.DIALOG, 0, textRendererSizes[i]), true, true); + textRenderers[i] = new TextRenderer(new Font(Font.DIALOG, Font.PLAIN, textRendererSizes[i]), true, true); } } @Override public void terminate() { super.terminate(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - for (final WindowListener wl : window.getWindowListeners()) { - window.removeWindowListener(wl); - } - window.setVisible(false); - window.dispose(); + SwingUtilities.invokeLater(() -> { + for (final WindowListener wl : window.getWindowListeners()) { + window.removeWindowListener(wl); } + window.setVisible(false); + window.dispose(); }); } @@ -342,7 +330,7 @@ public void draw(final GL2 gl) { // Time textRenderers[RENDERER_TIME].beginRendering(window.getWidth(), window.getHeight()); - drawText(textRenderers[RENDERER_TIME], formatTime((int) data.secsRemaining), (int) Math.round((window.getWidth() - textRenderers[RENDERER_TIME].getBounds("00:00").getWidth()) / 2 - (data.secsRemaining < 0 ? textRenderers[RENDERER_TIME].getCharWidth('-') : 0)), window.getHeight() - textRendererSizes[RENDERER_GAME_PHASE] - textRendererSizes[RENDERER_TIME], Color.black); + drawText(textRenderers[RENDERER_TIME], formatTime(data.secsRemaining), (int) Math.round((window.getWidth() - textRenderers[RENDERER_TIME].getBounds("00:00").getWidth()) / 2 - (data.secsRemaining < 0 ? textRenderers[RENDERER_TIME].getCharWidth('-') : 0)), window.getHeight() - textRendererSizes[RENDERER_GAME_PHASE] - textRendererSizes[RENDERER_TIME], Color.black); textRenderers[RENDERER_TIME].endRendering(); // State @@ -514,7 +502,7 @@ public void teamChanged(final TeamEvent e) { if (teamNumbers[1] != PluginLoader.TEAMNUMBER_COMMON) { drawings.addAll(PluginLoader.getInstance().getDrawings(teamNumbers[1])); } - Collections.sort(drawings, drawingComparator); + drawings.sort(drawingComparator); } } } diff --git a/src/teamcomm/gui/drawings/Drawing.java b/src/teamcomm/gui/drawings/Drawing.java index c1c1c8ff..ff582bb9 100644 --- a/src/teamcomm/gui/drawings/Drawing.java +++ b/src/teamcomm/gui/drawings/Drawing.java @@ -23,7 +23,7 @@ public abstract class Drawing { */ public void setActive(final boolean active) { this.active = active; - Config.getInstance().set("DrawingActive_" + getClass().getName() + (getTeamNumber() < 0 ? "" : "_" + getTeamNumber()), (Boolean) active); + Config.getInstance().set("DrawingActive_" + getClass().getName() + (getTeamNumber() < 0 ? "" : "_" + getTeamNumber()), active); } /** diff --git a/src/teamcomm/gui/drawings/RoSi2Element.java b/src/teamcomm/gui/drawings/RoSi2Element.java index fa70fa84..77f2c789 100644 --- a/src/teamcomm/gui/drawings/RoSi2Element.java +++ b/src/teamcomm/gui/drawings/RoSi2Element.java @@ -35,7 +35,7 @@ /** * Class for parsing ros2 scene files. Instances of this class correspond to - * named scene elements and can be instantiated to RoSi2Drawabled which may be + * named scene elements and can be instantiated to RoSi2Drawable which may be * drawn in a OpenGL context. * * @author Felix Thielke @@ -200,7 +200,7 @@ public RoSi2Drawable instantiate(final GL2 gl, final Map vars) t return instantiate(gl, vars, null); } - private RoSi2Drawable instantiate(final GL2 gl, final Map vars, final List refChilds) throws RoSi2ParseException { + private RoSi2Drawable instantiate(final GL2 gl, final Map vars, final List refChildren) throws RoSi2ParseException { // The instantiation is constant unless it references a variable boolean constant = true; @@ -223,7 +223,7 @@ private RoSi2Drawable instantiate(final GL2 gl, final Map vars, } // Instantiate all child elements - final List childInstances = (refChilds != null) ? new LinkedList<>(refChilds) : new LinkedList(); + final List childInstances = (refChildren != null) ? new LinkedList<>(refChildren) : new LinkedList<>(); for (final RoSi2Element child : children) { final RoSi2Drawable childInst = child.instantiate(gl, varBindings, null); if (childInst != null) { @@ -335,7 +335,7 @@ private RoSi2Drawable instantiate(final GL2 gl, final Map vars, final ParsePosition p = new ParsePosition(pos); final Number n = fmt.parse(str, p); if (n == null) { - throw new RoSi2ParseException("Vertex coordinate is not a number: " + str.substring(pos, pos + 1)); + throw new RoSi2ParseException("Vertex coordinate is not a number: " + str.charAt(pos)); } pos = p.getIndex(); vertex[i++] = n.doubleValue(); @@ -724,7 +724,7 @@ private String getAttributeValue(final Map varBindings, final St final StringBuilder value = new StringBuilder(raw.length()); int varEnd = 0; while (varStart >= 0) { - value.append(raw.substring(varEnd, varStart)); + value.append(raw, varEnd, varStart); if (varStart + 1 == raw.length()) { varEnd = varStart; break; @@ -750,7 +750,7 @@ private String getAttributeValue(final Map varBindings, final St final String binding = varBindings.get(varName); if (binding == null) { - value.append(raw.substring(varStart, varEnd)); + value.append(raw, varStart, varEnd); } else { value.append(binding); } @@ -1271,9 +1271,9 @@ private Normals computeNormals() { final Normals.Normal n = new Normals.Normal(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x, 1); double len = Math.sqrt(n.x * n.x + n.y * n.y + n.z * n.z); len = len == 0 ? 1.f : 1.f / len; - n.x *= len; - n.y *= len; - n.z *= len; + n.x *= (float) len; + n.y *= (float) len; + n.z *= (float) len; ns.get(i1).add(n); ns.get(i2).add(n); @@ -1408,11 +1408,11 @@ public static class TexCoord { /** * The x-component of the point. */ - public float x; + public final float x; /** * The y-component of the point. */ - public float y; + public final float y; /** * Constructs a point of a texture @@ -1424,7 +1424,7 @@ public TexCoord(final float x, final float y) { this.x = x; this.y = y; } - }; + } public final List coords; @@ -1563,7 +1563,7 @@ public void unset(final GL2 gl, final boolean defaultTextureSize) { * @throws teamcomm.gui.drawings.RoSi2Element.RoSi2ParseException if the * file could not be parsed as a ros2 file * @throws javax.xml.stream.XMLStreamException if the file could not be - * parsed as a XML file + * parsed as an XML file * @throws java.io.FileNotFoundException if the file could not be found * @throws java.io.IOException on other IO errors */ @@ -1617,7 +1617,7 @@ public static RoSi2Element parseFile(final String filename) throws RoSi2ParseExc } else { // Create and add element final String name = getXmlAttribute(e, "name", false); - final RoSi2Element elem = new RoSi2Element(inputFileStack.getFirst().path, tag, name, (Iterator) e.getAttributes(), namedElements); + final RoSi2Element elem = new RoSi2Element(inputFileStack.getFirst().path, tag, name, e.getAttributes(), namedElements); if (name != null && !withinSceneElement) { namedElements.put(tag + '#' + name, elem); } diff --git a/src/teamcomm/gui/drawings/RoSi2Loader.java b/src/teamcomm/gui/drawings/RoSi2Loader.java index fc4b3eef..7be345d6 100644 --- a/src/teamcomm/gui/drawings/RoSi2Loader.java +++ b/src/teamcomm/gui/drawings/RoSi2Loader.java @@ -5,7 +5,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.swing.JOptionPane; @@ -67,22 +66,13 @@ public void cacheModels(final GL2 gl, final String filename, final String... mod if (modelFileMap != null) { final Map modelMap = modelFileMap.get(filename); if (modelMap != null) { - final Iterator iter = modelNameSet.iterator(); - while (iter.hasNext()) { - if (modelMap.containsKey(iter.next())) { - iter.remove(); - } - } + modelNameSet.removeIf(modelMap::containsKey); } } // Add models to the set of models to load if (!modelNameSet.isEmpty()) { - Map> fileMap = modelsToLoad.get(gl); - if (fileMap == null) { - fileMap = new HashMap<>(); - modelsToLoad.put(gl, fileMap); - } + Map> fileMap = modelsToLoad.computeIfAbsent(gl, k -> new HashMap<>()); Set nameSet = fileMap.get(filename); if (nameSet == null) { fileMap.put(filename, modelNameSet); @@ -115,11 +105,7 @@ public int loadModel(final GL2 gl, final String modelname) { */ public int loadModel(final GL2 gl, final String filename, final String modelname) { // Check if the model has already been loaded - Map> fileMap = models.get(gl); - if (fileMap == null) { - fileMap = new HashMap<>(); - models.put(gl, fileMap); - } + Map> fileMap = models.computeIfAbsent(gl, k -> new HashMap<>()); Map modelMap = fileMap.get(filename); if (modelMap == null) { modelMap = new HashMap<>(); @@ -132,16 +118,8 @@ public int loadModel(final GL2 gl, final String filename, final String modelname } // Determine models to load from the same file - Map> loadFileMap = modelsToLoad.get(gl); - if (loadFileMap == null) { - loadFileMap = new HashMap<>(); - modelsToLoad.put(gl, loadFileMap); - } - Set nameSet = loadFileMap.get(filename); - if (nameSet == null) { - nameSet = new HashSet<>(); - loadFileMap.put(filename, nameSet); - } + Map> loadFileMap = modelsToLoad.computeIfAbsent(gl, k -> new HashMap<>()); + Set nameSet = loadFileMap.computeIfAbsent(filename, k -> new HashSet<>()); nameSet.add(modelname); // Load models diff --git a/src/teamcomm/gui/drawings/TextureLoader.java b/src/teamcomm/gui/drawings/TextureLoader.java index 28bdf48c..0f11d210 100644 --- a/src/teamcomm/gui/drawings/TextureLoader.java +++ b/src/teamcomm/gui/drawings/TextureLoader.java @@ -87,11 +87,7 @@ public static TextureLoader getInstance() { */ public Texture loadTexture(final GL gl, final File filename) throws IOException { // Get the map for the given gl context - Map map = textures.get(gl); - if (map == null) { - map = new HashMap<>(); - textures.put(gl, map); - } + Map map = textures.computeIfAbsent(gl, k -> new HashMap<>()); // Check if the texture has already been loaded Texture tex = map.get(filename.getAbsolutePath()); diff --git a/src/teamcomm/net/GameControlReturnDataReceiverTCM.java b/src/teamcomm/net/GameControlReturnDataReceiverTCM.java index 9a7ac2e7..8c1c7c08 100644 --- a/src/teamcomm/net/GameControlReturnDataReceiverTCM.java +++ b/src/teamcomm/net/GameControlReturnDataReceiverTCM.java @@ -4,7 +4,6 @@ import common.net.GameControlReturnDataReceiver; import data.GameControlReturnData; import java.io.IOException; -import java.net.InetAddress; import java.nio.ByteBuffer; import javax.swing.JOptionPane; import teamcomm.data.GameState; diff --git a/src/teamcomm/net/logging/LogReplayEventListener.java b/src/teamcomm/net/logging/LogReplayEventListener.java index ae34ba41..494d71d7 100644 --- a/src/teamcomm/net/logging/LogReplayEventListener.java +++ b/src/teamcomm/net/logging/LogReplayEventListener.java @@ -15,15 +15,15 @@ public interface LogReplayEventListener extends EventListener { * * @param e event */ - public void logReplayStatus(LogReplayEvent e); + void logReplayStatus(LogReplayEvent e); /** * Called when a log file was opened. */ - public void logReplayStarted(); + void logReplayStarted(); /** * Called when a log file was closed. */ - public void logReplayEnded(); + void logReplayEnded(); } diff --git a/src/teamcomm/net/logging/LogReplayTask.java b/src/teamcomm/net/logging/LogReplayTask.java index d1a29af2..9ef238cf 100644 --- a/src/teamcomm/net/logging/LogReplayTask.java +++ b/src/teamcomm/net/logging/LogReplayTask.java @@ -7,9 +7,9 @@ import java.io.BufferedInputStream; import java.io.EOFException; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; +import java.nio.file.Files; import java.util.Deque; import java.util.LinkedList; import javax.swing.event.EventListenerList; @@ -60,7 +60,7 @@ public LoggedObject(final long time, final int typeid) { public LogReplayTask(final File logfile, final EventListenerList listeners) throws IOException { this.listeners = listeners; - stream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(logfile))); + stream = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(logfile.toPath()))); next(); } @@ -187,10 +187,8 @@ private void handleObject(final LoggedObject obj) { GameState.getInstance().gameControlDataChanged(new GameControlDataEvent(this, (GameControlData) obj.object)); } } else { - switch (obj.typeid) { - case 1: - GameState.getInstance().gameControlDataTimeout(new GameControlDataTimeoutEvent(this)); - break; + if (obj.typeid == 1) { + GameState.getInstance().gameControlDataTimeout(new GameControlDataTimeoutEvent(this)); } } } diff --git a/src/tester/MainWindow.java b/src/tester/MainWindow.java index b0082de8..140a521f 100644 --- a/src/tester/MainWindow.java +++ b/src/tester/MainWindow.java @@ -30,35 +30,32 @@ public class MainWindow extends JFrame implements GameControlDataEventListener { public MainWindow() { super("GameControllerTester"); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setLocationByPlatform(true); - setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(final WindowEvent e) { - GameControllerTester.shutdown(); - } - }); - setPreferredSize(new Dimension(400, 1000)); + SwingUtilities.invokeLater(() -> { + setLocationByPlatform(true); + setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosed(final WindowEvent e) { + GameControllerTester.shutdown(); + } + }); + setPreferredSize(new Dimension(400, 1000)); - final JPanel contentPane = new JPanel(); - setContentPane(contentPane); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); - final JPanel gcInfoContainer = new JPanel(); - gcInfoContainer.setLayout(new BoxLayout(gcInfoContainer, BoxLayout.X_AXIS)); - gcInfoContainer.add(gcInfo); - contentPane.add(gcInfoContainer); - final JPanel teamInfoContainer = new JPanel(); - teamInfoContainer.setLayout(new BoxLayout(teamInfoContainer, BoxLayout.X_AXIS)); - teamInfoContainer.add(team0Info); - teamInfoContainer.add(team1Info); - contentPane.add(teamInfoContainer); + final JPanel contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); + final JPanel gcInfoContainer = new JPanel(); + gcInfoContainer.setLayout(new BoxLayout(gcInfoContainer, BoxLayout.X_AXIS)); + gcInfoContainer.add(gcInfo); + contentPane.add(gcInfoContainer); + final JPanel teamInfoContainer = new JPanel(); + teamInfoContainer.setLayout(new BoxLayout(teamInfoContainer, BoxLayout.X_AXIS)); + teamInfoContainer.add(team0Info); + teamInfoContainer.add(team1Info); + contentPane.add(teamInfoContainer); - pack(); - setVisible(true); - } + pack(); + setVisible(true); }); }