Blog-Archiv

Donnerstag, 29. Mai 2025

Set Java Swing JSlider Position by Mouse Click

You can set the position of the Java/Swing JSlider knob by dragging it with the left mouse button. But you can not set its position by clicking into the slider's running track, neither by left nor by right click. The left click moves the knob just a little by its increment value, which may require lots of clicks to get to the desired position. But the right mouse click is not used by JSlider, so why not use it for moving the knob to the click location?

Another idea would be to show tooltips according to the current mouse position over the slider. That means if you move the mouse e.g. over the value "2" of the slider, you would like to show a tooltip that says "Mouse is over the value of 2" (or something not so silly:-).

Move Knob to Right Mouse Click Location

All of the following applies to both horizontal and vertical sliders.

    private JSlider createSlider() {
        final JSlider slider = new JSlider();
        
        slider.addMouseListener(new MouseAdapter() {
            /** Moves the slider knob to the given event location when it was a right-mouse click.*/
            @Override
            public void mouseClicked(MouseEvent e) {
                if (((JComponent) e.getSource()).isEnabled() && SwingUtilities.isRightMouseButton(e)) {
                    final int sliderValue = new SliderMouseEventLocator(e).sliderValue;
                    slider.setValue(sliderValue);
                }
            }
        });

        return slider;
    }

So this was the mouse event catching, but what is SliderMouseEventLocator?

public class SliderMouseEventLocator
{
    /** Result of construction. */
    public final Integer sliderValue;
    
    public SliderMouseEventLocator(MouseEvent e) {
        final JSlider slider = (JSlider) e.getSource();
        final BasicSliderUI ui = (BasicSliderUI) slider.getUI();
        final boolean horizontal = (slider.getOrientation() != SwingConstants.VERTICAL);
        this.sliderValue = horizontal ? ui.valueForXPosition(e.getX()) : ui.valueForYPosition(e.getY());
    }
}

This code converts the mouse click location to a slider value. The mouse-event coordinate is relative to the slider, not relative to the window. We can let BasicSliderUI do the work.

You need a new SliderMouseEventLocator for each arriving mouse event. If you want to reuse that object, you would have to implement a mouse-event converter-method instead of the immutable public final sliderValue result field (that must be evaluated at least on constructor execution).

Show Tooltip According to Mouse Location

Having the SliderMouseEventLocator class, it is easy to implement different tooltips according to mouse moves.

        slider.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                final Integer sliderValue = new SliderMouseEventLocator(e).sliderValue;
                final String tooltip = getTextRepresentation(sliderValue);
                // TODO: implement getTextRepresentation
                slider.setToolTipText(tooltip);
            }
        });

Add this snippet to the createSlider() method and implement getTextRepresentation(sliderValue).

Hope this was helpful for the few remaining Swing programmers!




Freitag, 23. Mai 2025

Basic Ubuntu LINUX Firewall Security

LINUX has a built-in firewall called netfilter, configurable through iptables. There is a user friendly Ubuntu command-line tool called ufw to configure this firewall. All three should be already installed in your Ubuntu LINUX. (Probably you don't want to mess with snort!)

By default, the firewall is not turned on!
You must activate it manually. For the purpose of working with your firewall, it may be useful to additionally install its graphical user interface:

  • sudo apt install gufw

And run it:

  • sudo gufw

You will see this:

If you move the "Status" switch to the right, the firewall will be turned on. Now enter this command-line:

  • sudo ufw status

You should see "Status: active". This will survive a reboot. You can reach the gufw graphical user interface without command-line when you enter "firewall" in your application-finder ("Show Apps" button on Ubuntu taskbar). Of course you must enter the superuser password here, as you must do when running any sudo commandline. Remember to read the documentation, especially when you use P2P applications, because ports may be closed now!




Single Web Page Upload to the Internet

Just copied my (self-contained) information page about Austrian mountains to the Internet ("Berge Österreichs mit mindestens 100 m Schartenhöhe"):

This contains lots of information, and why shouldn't it be visible to all?
The Internet provides a free single web-page upload on

Only an accessible e-mail address is required. (Hopefully no ads coming now...)

This page is full of JavaScript (ES6) code that lets you filter and sort table rows, and even collapse and expand table columns. Click onto the column header to try out. It also displays the number of all and that of currently filtered rows on top left.

I published and explained the JavaScript (ES6) code for this type of HTML-table in a series of 4 Blog articles, starting with Sortable Filterable HTML Table with ES6, Part 1. You can use this code for free. Have fun!

Samstag, 10. Mai 2025

HTML Page Reload on Focus

Imagine you need a page that always reloads itself from the server when the user focuses it, that means the according browser tab or window was in background and gets clicked to foreground. For such a page the user would never have to press the "Reload" button when coming back to it, which may make sense e.g. for a wheather-report site (to always show the current temperature).

This is different from updating the page periodically, which can be done via the refresh attribute in a <head> <meta> element. Mind that such would take control away from the user, may consume valuable resources, and is not applicable in all environments.

Code

Following HTML would do a page reload on focus. Mind that this is not recommendable for big expensive pages that need several seconds to render!

<!DOCTYPE HTML>
<html>
  <body onfocus="window.location = window.location;">

    <!-- Here goes the page HTML -->

  </body>
</html>

The technique is to install an event handler for the focus event in the <body> element. The JavaScript code "window.location = window.location;" inside the event handler may look ridiculous, but it actually performs a page reload.

Test

Here is a test-page to verify that behavior. It displays the current time every time it gets loaded, and it has the above mechanism installed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE HTML>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Show Load Time when Focused</title>
  </head>

  <body
    onpageshow="renderTime();"
    onfocus="window.location = window.location;"
  >
    <fieldset>
      <legend>Load Time:</legend>
      <div id="time"></div>
    </fieldset>
	
    <script>
      function renderTime() {
        const date = new Date();
        const timeField = document.getElementById("time");
        timeField.innerHTML = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
      }
    </script>
  </body>
</html>

To verify,

  1. load this page in your web-browser,
  2. look at the displayed time, remember it,
  3. then open a new tab or window and focus it (or click onto some already opened),
  4. then change back to this page

→ The displayed time must have changed now.

Resume

I do not know if this is the simplest way to make a page reload itself automatically when it is looked at, but at least it needs very few code. If you need to update just single elements or fields on focus, you will have to use AJAX.