view src/name/blackcap/imageprep/MaxDimSpinner.kt @ 24:a4737a525af8

Fix icons a bit.
author David Barts <n5jrn@me.com>
date Wed, 25 Nov 2020 08:40:45 -0800
parents d3979a2155a8
children
line wrap: on
line source

/*
 * A standard combo box for inputting the maximum dimension of an image.
 * Note that this IS NOT a spinner; this class is so named for historical
 * reasons.
 */
package name.blackcap.imageprep

import java.awt.Toolkit
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.util.logging.Level
import java.util.logging.Logger
import javax.swing.*

/* maximum allowable maximum dimension */
private val MAXDIM = 16384

/* preferred standard dimensions */
private val STDDIMS = arrayOf<Int>(1600, 1280, 1024, 800, 640, 512, 400, 320).apply {
    sort()
}

class MaxDimSpinner(val default: Int): JComboBox<Int>(STDDIMS)
{
    private var _value: Int = 0
    var value: Int
    get() = _value
    set(v) {
        if (outOfRange(v))
            throw IllegalArgumentException("bad max dimension: $v")
        _value = v
        val pos = STDDIMS.binarySearch(v)
        if (pos >= 0)
            selectedIndex = pos
        else
            selectedItem = v
    }

    private fun outOfRange(v: Int): Boolean = v < 1 || v > MAXDIM

    init {
        value = default
        maximumSize = preferredSize
        setEditable(true)
        prototypeDisplayValue = MAXDIM
        addActionListener(ActionListener {
            val v = selectedItem as? Int ?: (selectedItem as? String)?.toIntOrNull()
            if (v == null || outOfRange(v)) {
                LOGGER.log(Level.INFO, "bad max dimension: $selectedItem")
                Toolkit.getDefaultToolkit().beep()
                value = default
            } else {
                _value = v
            }
        })
    }
}