Merge pull request #54 from informatik-ag-ngl/f/scrollbar

Enhanced Scroll Bar
This commit is contained in:
Kai S. K. Engelbart 2019-12-18 22:14:05 +01:00 committed by GitHub
commit fdeb922bdd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 298 additions and 119 deletions

View File

@ -1,8 +1,8 @@
package envoy.client.event;
/**
* Project: <strong>envoy-clientChess</strong><br>
* File: <strong>Event.javaEvent.java</strong><br>
* Project: <strong>envoy-client</strong><br>
* File: <strong>Event.java</strong><br>
* Created: <strong>04.12.2019</strong><br>
*
* @author Kai S. K. Engelbart

View File

@ -1,8 +1,9 @@
package envoy.client.event;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class handles events by allowing {@link EventHandler} object to register
@ -10,7 +11,8 @@ import java.util.List;
* bus.<br>
* <br>
* The event bus is a singleton and can be used across the entire application to
* guarantee the propagation of events.
* guarantee the propagation of events.<br>
*
* Project: <strong>envoy-client</strong><br>
* File: <strong>EventBus.java</strong><br>
* Created: <strong>04.12.2019</strong><br>
@ -22,9 +24,10 @@ public class EventBus {
/**
* Contains all {@link EventHandler} instances registered at this
* {@link EventBus}.
* {@link EventBus} as values mapped to by their supported {@link Event}
* classes.
*/
private List<EventHandler> handlers = new ArrayList<>();
private Map<Class<? extends Event<?>>, List<EventHandler>> handlers = new HashMap<>();
/**
* The singleton instance of this {@link EventBus} that is used across the
@ -46,13 +49,17 @@ public class EventBus {
public static EventBus getInstance() { return eventBus; }
/**
* Registers a list of {@link EventHandler} objects to be notified when a
* {@link Event} is dispatched that they are subscribed to.
* Registers an {@link EventHandler} to be notified when a
* {@link Event} of a certain type is dispatched.
*
* @param handlers the {@link EventHandler} objects to register
* @param eventClass the class which the {@link EventHandler} is subscribed to
* @param handler the {@link EventHandler} to register
* @since Envoy v0.2-alpha
*/
public void register(EventHandler... handlers) { this.handlers.addAll(Arrays.asList(handlers)); }
public void register(Class<? extends Event<?>> eventClass, EventHandler handler) {
if (!handlers.containsKey(eventClass)) handlers.put(eventClass, new ArrayList<>());
handlers.get(eventClass).add(handler);
}
/**
* Dispatches a {@link Event} to every {@link EventHandler} subscribed to it.
@ -60,12 +67,15 @@ public class EventBus {
* @param event the {@link Event} to dispatch
* @since Envoy v0.2-alpha
*/
public void dispatch(Event<?> event) { handlers.stream().filter(h -> h.supports().contains(event.getClass())).forEach(h -> h.handle(event)); }
public void dispatch(Event<?> event) {
handlers.keySet().stream().filter(event.getClass()::isAssignableFrom).map(handlers::get).flatMap(List::stream).forEach(h -> h.handle(event));
}
/**
* @return a list of all {@link EventHandler} instances currently registered at
* this {@link EventBus}
* @return a map of all {@link EventHandler} instances currently registered at
* this {@link EventBus} with the {@link Event} classes they are
* subscribed to as keys
* @since Envoy v0.2-alpha
*/
public List<EventHandler> getHandlers() { return handlers; }
public Map<Class<? extends Event<?>>, List<EventHandler>> getHandlers() { return handlers; }
}

View File

@ -1,7 +1,5 @@
package envoy.client.event;
import java.util.Set;
/**
* Project: <strong>envoy-clientChess</strong><br>
* File: <strong>EventHandler.javaEvent.java</strong><br>
@ -17,9 +15,4 @@ public interface EventHandler {
* @param event The event dispatched by the event bus, only of supported type
*/
void handle(Event<?> event);
/**
* @return A set of classes this class is supposed to handle in events
*/
Set<Class<? extends Event<?>>> supports();
}

View File

@ -0,0 +1,20 @@
package envoy.client.event;
import envoy.client.ui.Theme;
/**
* Project: <strong>envoy-client</strong><br>
* File: <strong>ThemeChangeEvent.java</strong><br>
* Created: <strong>15 Dec 2019</strong><br>
*
* @author Kai S. K. Engelbart
*/
public class ThemeChangeEvent implements Event<Theme> {
private final Theme theme;
public ThemeChangeEvent(Theme theme) { this.theme = theme; }
@Override
public Theme get() { return theme; }
}

View File

@ -19,7 +19,6 @@ import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
@ -31,6 +30,8 @@ import envoy.client.Client;
import envoy.client.Config;
import envoy.client.LocalDB;
import envoy.client.Settings;
import envoy.client.event.EventBus;
import envoy.client.event.ThemeChangeEvent;
import envoy.schema.Message;
import envoy.schema.User;
@ -48,18 +49,18 @@ public class ChatWindow extends JFrame {
private static final long serialVersionUID = 6865098428255463649L;
// user specific objects
// User specific objects
private Client client;
private LocalDB localDB;
// GUI components
private JPanel contentPane = new JPanel();
private PrimaryTextArea messageEnterTextArea = new PrimaryTextArea(space);
private JList<User> userList = new JList<>();
private Chat currentChat;
private JList<Message> messageList = new JList<>();
private JScrollPane scrollPane = new JScrollPane();
private PrimaryScrollPane scrollPane = new PrimaryScrollPane();
private JTextPane textPane = new JTextPane();
// private JCheckBox jCbChangeMode;
private PrimaryButton postButton = new PrimaryButton("Post");
private PrimaryButton settingsButton = new PrimaryButton("Settings");
@ -112,7 +113,6 @@ public class ChatWindow extends JFrame {
messageList.setBorder(new EmptyBorder(space, space, space, space));
scrollPane.setViewportView(messageList);
scrollPane.setBorder(null);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
@ -168,7 +168,6 @@ public class ChatWindow extends JFrame {
settingsButton.addActionListener((evt) -> {
try {
SettingsScreen.open();
changeChatWindowColors(Settings.getInstance().getCurrentTheme());
} catch (Exception e) {
SettingsScreen.open();
logger.log(Level.WARNING, "An error occured while opening the settings screen", e);
@ -196,7 +195,6 @@ public class ChatWindow extends JFrame {
@SuppressWarnings("unchecked")
final JList<User> selectedUserList = (JList<User>) listSelectionEvent.getSource();
final User user = selectedUserList.getSelectedValue();
client.setRecipient(user);
currentChat = localDB.getChats().stream().filter(chat -> chat.getRecipient().getID() == user.getID()).findFirst().get();
@ -207,6 +205,7 @@ public class ChatWindow extends JFrame {
textPane.setText(currentChat.getRecipient().getName());
messageList.setModel(currentChat.getModel());
scrollPane.setChatOpened(true);
contentPane.revalidate();
}
});
@ -221,11 +220,13 @@ public class ChatWindow extends JFrame {
gbc_userList.anchor = GridBagConstraints.PAGE_START;
gbc_userList.insets = new Insets(space, space, space, space);
changeChatWindowColors(Settings.getInstance().getCurrentTheme());
changeChatWindowColors(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()));
contentPane.add(userList, gbc_userList);
contentPane.revalidate();
EventBus.getInstance().register(ThemeChangeEvent.class, (evt) -> changeChatWindowColors((Theme) evt.get()));
loadUsersAndChats();
if (client.isOnline()) startSyncThread(Config.getInstance().getSyncTimeout());
@ -238,9 +239,7 @@ public class ChatWindow extends JFrame {
*
* @since Envoy v0.1-alpha
*/
public void changeChatWindowColors(String key) {
Theme theme = Settings.getInstance().getThemes().get(key);
private void changeChatWindowColors(Theme theme) {
// contentPane
contentPane.setBackground(theme.getBackgroundColor());
contentPane.setForeground(theme.getUserNameColor());
@ -250,8 +249,9 @@ public class ChatWindow extends JFrame {
messageList.setForeground(theme.getMessageColorChat());
messageList.setBackground(theme.getCellColor());
// scrollPane
scrollPane.setForeground(theme.getBackgroundColor());
scrollPane.setBackground(theme.getCellColor());
scrollPane.applyTheme(theme);
scrollPane.autoscroll();
// messageEnterTextArea
messageEnterTextArea.setCaretColor(theme.getTypingMessageColor());
messageEnterTextArea.setForeground(theme.getTypingMessageColor());

View File

@ -31,7 +31,7 @@ public class PrimaryButton extends JButton {
* Creates a primary button
*
* @param title the title of the button
* @param the size of the arc used to draw the round button edges
* @param arcSize the size of the arc used to draw the round button edges
* @since Envoy 0.2-alpha
*/
public PrimaryButton(String title, int arcSize) {

View File

@ -0,0 +1,115 @@
package envoy.client.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.plaf.basic.BasicScrollBarUI;
import envoy.client.Settings;
/**
* Project: <strong>envoy-client</strong><br>
* File: <strong>PrimaryScrollBar.java</strong><br>
* Created: <strong>14.12.2019</strong><br>
*
* @author Maximilian K&auml;fer
* @since Envoy v0.2-alpha
*/
public class PrimaryScrollBar extends BasicScrollBarUI {
private final Dimension d = new Dimension();
private final int arcSize;
private final Color scrollBarColor;
private final Color hoverColor;
private final Color draggingColor;
private final boolean isVertical;
/**
* Initializes a {@link PrimaryScrollBar} with a color scheme.
*
* @param arcSize the size of the arc used to draw the round scroll bar
* edges
* @param scrollBarColor the default color
* @param hoverColor the color while hovering
* @param draggingColor the color while dragging
* @param isVertical indicates whether this is a vertical
* {@link PrimaryScrollBar}
*/
public PrimaryScrollBar(int arcSize, Color scrollBarColor, Color hoverColor, Color draggingColor, boolean isVertical) {
this.arcSize = arcSize;
this.scrollBarColor = scrollBarColor;
this.hoverColor = hoverColor;
this.draggingColor = draggingColor;
this.isVertical = isVertical;
}
/**
* Initializes a {@link PrimaryScrollBar} using a color scheme specified in a
* {@link Theme}
*
* @param theme the {@link Theme} to be applied to this
* {@link PrimaryScrollBar}
* @param isVertical indicates whether this is a vertical
* {@link PrimaryScrollBar}
*/
public PrimaryScrollBar(Theme theme, boolean isVertical) {
this(5, theme.getInteractableBackgroundColor(), new Color(theme.getInteractableBackgroundColor().getRGB() - 50),
new Color(theme.getInteractableBackgroundColor().getRGB() + 170), isVertical);
}
@Override
protected JButton createDecreaseButton(int orientation) {
JButton button = new JButton();
button.setPreferredSize(d);
return button;
}
@Override
protected JButton createIncreaseButton(int orientation) {
JButton button = new JButton();
button.setPreferredSize(d);
return button;
}
@Override
protected void paintTrack(Graphics g, JComponent c, Rectangle r) {}
@Override
protected void paintThumb(Graphics g, JComponent c, Rectangle r) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color color;
JScrollBar sb = (JScrollBar) c;
if (!sb.isEnabled()) return;
if (isDragging) color = draggingColor;
else if (isThumbRollover()) color = hoverColor;
else color = scrollBarColor;
g2.setPaint(color);
if (isVertical) {
g2.fillRoundRect(r.x - 9, r.y, r.width, r.height, arcSize, arcSize);
g2.setPaint(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getCellColor());
g2.drawRoundRect(r.x - 9, r.y, r.width, r.height, arcSize, arcSize);
} else {
g2.fillRoundRect(r.x, r.y + 9, r.width, r.height - 10, arcSize, arcSize);
g2.setPaint(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getCellColor());
g2.drawRoundRect(r.x, r.y + 9, r.width, r.height - 10, arcSize, arcSize);
}
g2.dispose();
}
@Override
protected void setThumbBounds(int x, int y, int width, int height) {
super.setThumbBounds(x, y, width, height);
scrollbar.repaint();
}
}

View File

@ -0,0 +1,83 @@
package envoy.client.ui;
import javax.swing.JScrollPane;
/**
* Project: <strong>envoy-client</strong><br>
* File: <strong>PrimaryScrollPane.java</strong><br>
* Created: <strong>15 Dec 2019</strong><br>
*
* @author Kai S. K. Engelbart
* @author Maximilian K&auml;fer
*/
public class PrimaryScrollPane extends JScrollPane {
private static final long serialVersionUID = -4786837444056228439L;
private int verticalScrollBarMaximum = getVerticalScrollBar().getMaximum();
private boolean chatOpened = false;
/**
* Initializes a {@link JScrollPane} with the primary Envoy design scheme
*
* @since Envoy v0.2-alpha
*/
public PrimaryScrollPane() { setBorder(null); }
/**
* Styles the vertical and horizontal scroll bars.
*
* @param theme
* @since Envoy v0.2-alpha
*/
public void applyTheme(Theme theme) {
setForeground(theme.getBackgroundColor());
setBackground(theme.getCellColor());
getVerticalScrollBar().setBackground(theme.getCellColor());
getVerticalScrollBar().setUI(new PrimaryScrollBar(theme, true));
getHorizontalScrollBar().setBackground(theme.getCellColor());
getHorizontalScrollBar().setUI(new PrimaryScrollBar(theme, false));
}
/**
* Implements <b>autoscroll functionality</b> for the vertical scroll bar. </br>
* </br>
* Functionality to automatically scroll down when user views </br>
* the bottom of the chat while there are new messages added. </br>
* </br>
* When chat is opened, the vertical scroll bar starts at the bottom. </br>
* </br>
* When rereading messages, the chat doesn't scroll down if new messages </br>
* are added. (Besides see first point)
*
* @since Envoy v0.2-alpha
*/
public void autoscroll() {
// Automatic scrolling to the bottom
getVerticalScrollBar().addAdjustmentListener(e -> {
if (verticalScrollBarMaximum == e.getAdjustable().getMaximum()) return;
if (chatOpened) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
verticalScrollBarMaximum = getVerticalScrollBar().getMaximum();
chatOpened = false;
return;
}
if (getVerticalScrollBar().getValue() + getVerticalScrollBar().getVisibleAmount() + 100 >= getVerticalScrollBar().getMaximum()) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
verticalScrollBarMaximum = getVerticalScrollBar().getMaximum();
}
});
}
/**
* Indicates a chat being opened by the user to this {@link PrimaryScrollPane}
* triggering it to automatically scroll down.
*
* @param chatOpened indicates the chat opening status
* @since Envoy v0.2-alpha
*/
public void setChatOpened(boolean chatOpened) { this.chatOpened = chatOpened; }
}

View File

@ -27,6 +27,8 @@ import javax.swing.ListSelectionModel;
import envoy.client.LocalDB;
import envoy.client.Settings;
import envoy.client.event.EventBus;
import envoy.client.event.ThemeChangeEvent;
/**
* This class provides the GUI to change the user specific settings.
@ -45,12 +47,12 @@ public class SettingsScreen extends JDialog {
private final JPanel contentPanel = new JPanel();
private DefaultListModel<String> optionsListModel = new DefaultListModel<>();
private final JList<String> options = new JList<String>();
private final JList<String> options = new JList<>();
private JPanel buttonPane = new JPanel();
private JPanel themeContent = new JPanel();
private String[] themeArray = Settings.getInstance().getThemes().keySet().toArray(new String[0]);
private JComboBox<String> themes = new JComboBox<String>(themeArray);
private JComboBox<String> themes = new JComboBox<>(themeArray);
private GridBagConstraints gbc_themeContent = new GridBagConstraints();
@ -63,7 +65,6 @@ public class SettingsScreen extends JDialog {
private JButton cancelButton = new JButton("Cancel");
private static int space = 5;
private boolean colorChanged = false;
private Theme temporaryTheme;
private static final Logger logger = Logger.getLogger(LocalDB.class.getSimpleName());
@ -296,9 +297,10 @@ public class SettingsScreen extends JDialog {
Settings.getInstance().setCurrentTheme(selectedTheme.getThemeName());
System.out.println(selectedTheme.getThemeName());
changeSettingsScreenColors(Settings.getInstance().getCurrentTheme());
updateColorVariables(Settings.getInstance().getCurrentTheme());
final Theme currentTheme = Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme());
changeSettingsScreenColors(currentTheme);
updateColorVariables(currentTheme);
EventBus.getInstance().dispatch(new ThemeChangeEvent(currentTheme));
Settings.getInstance().save();
revalidate();
@ -310,11 +312,10 @@ public class SettingsScreen extends JDialog {
});
}
}
changeSettingsScreenColors(Settings.getInstance().getCurrentTheme());
changeSettingsScreenColors(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()));
}
private void changeSettingsScreenColors(String key) {
Theme theme = Settings.getInstance().getThemes().get(key);
private void changeSettingsScreenColors(Theme theme) {
// whole JDialog
setBackground(theme.getBackgroundColor());
// contentPanel
@ -345,19 +346,8 @@ public class SettingsScreen extends JDialog {
}
private void updateColorVariables(String key) {
Theme theme = Settings.getInstance().getThemes().get(key);
temporaryTheme = new Theme("temporaryTheme",
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getBackgroundColor(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getCellColor(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getInteractableForegroundColor(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getInteractableBackgroundColor(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getMessageColorChat(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getDateColorChat(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getSelectionColor(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getTypingMessageColor(),
Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()).getUserNameColor());
private void updateColorVariables(Theme theme) {
temporaryTheme = new Theme("temporaryTheme", theme);
colorsPanel.removeAll();
@ -462,7 +452,6 @@ public class SettingsScreen extends JDialog {
// TODO: When Theme changed in same settings screen, color variable doesnt
// update.
temporaryTheme.setColor(yIndex, newColor);
colorChanged = true;
createNewThemeButton.setEnabled(true);
}
button.setBackground(newColor);
@ -481,8 +470,5 @@ public class SettingsScreen extends JDialog {
colorsPanel.add(panel);
}
private Color getInvertedColor(Color color) {
return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue());
}
private Color getInvertedColor(Color color) { return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue()); }
}

View File

@ -11,12 +11,8 @@ import java.awt.TrayIcon.MessageType;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashSet;
import java.util.Set;
import envoy.client.event.Event;
import envoy.client.event.EventBus;
import envoy.client.event.EventHandler;
import envoy.client.event.MessageCreationEvent;
import envoy.exception.EnvoyException;
import envoy.schema.Message;
@ -29,7 +25,7 @@ import envoy.schema.Message;
* @author Kai S. K. Engelbart
* @since Envoy v0.2-alpha
*/
public class StatusTrayIcon implements EventHandler {
public class StatusTrayIcon {
/**
* The {@link TrayIcon} provided by the System Tray API for controlling the
@ -85,7 +81,10 @@ public class StatusTrayIcon implements EventHandler {
trayIcon.addActionListener((evt) -> { focusTarget.setVisible(true); focusTarget.requestFocus(); });
// Start processing message events
EventBus.getInstance().register(this);
EventBus.getInstance().register(MessageCreationEvent.class, (evt) -> {
if (displayMessages)
trayIcon.displayMessage("New message received", ((MessageCreationEvent) evt).get().getContent().get(0).getText(), MessageType.INFO);
});
}
/**
@ -102,31 +101,4 @@ public class StatusTrayIcon implements EventHandler {
throw new EnvoyException("Could not attach Envoy tray icon to system tray.", e);
}
}
/**
* Notifies the user of a message by displaying a pop-up every time a new
* message is received.
*
* @since Envoy v0.2-alpha
*/
@Override
public void handle(Event<?> event) {
System.out.println("Message received. Displaying message: " + displayMessages);
if (displayMessages)
trayIcon.displayMessage("New message received", ((MessageCreationEvent) event).get().getContent().get(0).getText(), MessageType.INFO);
}
/**
* The {@link StatusTrayIcon} only reacts to {@link MessageCreationEvent}
* instances which signify newly received messages.
*
* @return A set with the single element {@code MessageCreationEvent.class}
* @since Envoy v0.2-alpha
*/
@Override
public Set<Class<? extends Event<?>>> supports() {
Set<Class<? extends Event<?>>> supportedEvents = new HashSet<>();
supportedEvents.add(MessageCreationEvent.class);
return supportedEvents;
}
}