Last active
October 23, 2019 19:30
-
-
Save sorokod/be90a6f3bb00d546577d067627c4514b to your computer and use it in GitHub Desktop.
A quick way of displaying pixels (with optional animation) in a JFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Color.BLACK | |
import java.awt.Dimension | |
import java.awt.Graphics | |
import java.awt.Toolkit | |
import java.awt.image.BufferedImage | |
import java.awt.image.BufferedImage.TYPE_INT_ARGB | |
import java.awt.image.BufferedImage.TYPE_INT_RGB | |
import javax.swing.JFrame | |
import javax.swing.JPanel | |
import kotlin.Int.Companion.MAX_VALUE | |
import kotlin.random.Random.Default.nextInt | |
/** | |
* A quick way of displaying pixels (with optional animation) in a JFrame | |
*/ | |
class PFrame(image: BufferedImage, tit: String = "") : JFrame() { | |
private val panel: PPanel = PPanel(image) | |
init { | |
add(panel) | |
pack() | |
setLocationRelativeTo(null) | |
isResizable = false | |
title = tit | |
defaultCloseOperation = EXIT_ON_CLOSE | |
isVisible = true | |
} | |
fun render() = panel.repaint() | |
private class PPanel(val image: BufferedImage) : JPanel() { | |
init { | |
background = BLACK | |
preferredSize = Dimension(image.width, image.height) | |
} | |
public override fun paintComponent(g: Graphics) { | |
super.paintComponent(g) | |
g.drawImage(image, 0, 0, this) | |
Toolkit.getDefaultToolkit().sync() | |
} | |
} | |
} | |
fun randomPixels(imageType: Int = TYPE_INT_ARGB) { | |
val size = 350 | |
val image = BufferedImage(size, size, imageType) | |
val frame = PFrame(image) | |
for (i in 0..1000000) { | |
image.setRGB(nextInt(size), nextInt(size), nextInt()) | |
if (i.rem(10000) == 0) { | |
frame.render() | |
Thread.sleep(100) | |
} | |
} | |
frame.render() | |
} | |
fun squares() { | |
val size = 400 | |
val sqSize = size / 10 | |
val image = BufferedImage(size, size, TYPE_INT_RGB) | |
val frame = PFrame(image) | |
for (i in 0 until size) { | |
for (j in 0 until size) { | |
val x = (i / sqSize).rem(2) | |
val y = (j / sqSize).rem(2) | |
if (x + y == 0 || x + y == 2) { | |
image.setRGB(i, j, MAX_VALUE) | |
} | |
} | |
} | |
frame.render() | |
} | |
fun main() { | |
randomPixels() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment