Last active
December 29, 2015 10:59
-
-
Save ayapi/7660869 to your computer and use it in GitHub Desktop.
Swing JLayerで任意のコンポーネントを階調反転させる
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 javax.swing.*; | |
import javax.swing.plaf.LayerUI; | |
import java.awt.*; | |
import java.awt.image.*; | |
public class InvertColorLayerUI extends LayerUI<JComponent> { | |
private BufferedImage bufferedImage; | |
@Override | |
public void paint(Graphics g, JComponent c) { | |
int w = c.getWidth(); | |
int h = c.getHeight(); | |
if (w == 0 || h == 0) return; | |
if (bufferedImage == null | |
|| bufferedImage.getWidth() != w | |
|| bufferedImage.getHeight() != h) { | |
bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); | |
} | |
Graphics2D g2 = bufferedImage.createGraphics(); | |
g2.setClip(g.getClip()); | |
super.paint(g2, c); | |
g2.dispose(); | |
FilteredImageSource filtered = new FilteredImageSource( | |
bufferedImage.getSource(), | |
new InvertColorFilter() | |
); | |
Image image = c.createImage(filtered); | |
g.drawImage(image, 0, 0, c); | |
} | |
class InvertColorFilter extends RGBImageFilter { | |
@Override | |
public int filterRGB(int x, int y, int argb) { | |
int alpha = argb & 0xFF000000; | |
int rgb = ~(argb & 0xFFFFFF); | |
return alpha | rgb; | |
} | |
} | |
} | |
class InvertTestWindow { | |
public static void main(String[] args) throws Exception { | |
JFrame frame = new JFrame(); | |
frame.setSize(200, 200); | |
JPanel panel = new JPanel(); | |
LayerUI<JComponent> layerUI = new InvertColorLayerUI(); | |
JLayer<JComponent> layer = new JLayer<JComponent>(panel, layerUI); | |
frame.add(layer); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.setVisible(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment