JTable how to change BackGround Color - java

I inspired by MeBigFatGuy interesting question, in this conection I have very specific question about Graphisc2D, how to change BackGround Color by depends if is JTables Row visible in the JViewPort,
1) if 1st. & last JTables Row will be visible in the JViewPort, then BackGround would be colored to the Color.red
2) if 1st. & last JTables Row will not be visible in the JViewPort, then BackGround would be colored to the Color.whatever
from SSCCE
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.RepaintManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableModel;
/*
https://stackoverflow.com/questions/1249278/
how-to-disable-the-default-painting-behaviour-of-wheel-scroll-event-on-jscrollpan
*
and
*
https://stackoverflow.com/questions/8195959/
swing-jtable-event-when-row-is-visible-or-when-scrolled-to-the-bottom
*/
public class ViewPortFlickering {
private JFrame frame = new JFrame("Table");
private JViewport viewport = new JViewport();
private Rectangle RECT = new Rectangle();
private Rectangle RECT1 = new Rectangle();
private JTable table = new JTable(50, 3);
private javax.swing.Timer timer;
private int count = 0;
public ViewPortFlickering() {
GradientViewPort tableViewPort = new GradientViewPort(table);
viewport = tableViewPort.getViewport();
viewport.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
RECT = table.getCellRect(0, 0, true);
RECT1 = table.getCellRect(table.getRowCount() - 1, 0, true);
Rectangle viewRect = viewport.getViewRect();
if (viewRect.intersects(RECT)) {
System.out.println("Visible RECT -> " + RECT);
} else if (viewRect.intersects(RECT1)) {
System.out.println("Visible RECT1 -> " + RECT1);
} else {
//
}
}
});
frame.add(tableViewPort);
frame.setPreferredSize(new Dimension(600, 300));
frame.pack();
frame.setLocation(50, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RepaintManager.setCurrentManager(new RepaintManager() {
#Override
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Container con = c.getParent();
while (con instanceof JComponent) {
if (!con.isVisible()) {
return;
}
if (con instanceof GradientViewPort) {
c = (JComponent) con;
x = 0;
y = 0;
w = con.getWidth();
h = con.getHeight();
}
con = con.getParent();
}
super.addDirtyRegion(c, x, y, w, h);
}
});
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(100, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("updating row " + (count + 1));
TableModel model = table.getModel();
int cols = model.getColumnCount();
int row = 0;
for (int j = 0; j < cols; j++) {
row = count;
table.changeSelection(row, 0, false, false);
timer.setDelay(100);
Object value = "row " + (count + 1) + " item " + (j + 1);
model.setValueAt(value, count, j);
}
count++;
if (count >= table.getRowCount()) {
timer.stop();
table.changeSelection(0, 0, false, false);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
table.clearSelection();
}
});
}
}
};
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ViewPortFlickering viewPortFlickering = new ViewPortFlickering();
}
});
}
}
class GradientViewPort extends JScrollPane {
private static final long serialVersionUID = 1L;
private final int h = 50;
private BufferedImage img = null;
private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB);
private JViewport viewPort;
public GradientViewPort(JComponent com) {
super(com);
viewPort = this.getViewport();
viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE);
viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(new Color(250, 150, 150));
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h,
new Color(0.5f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paint(Graphics g) {
if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paint(g2);
Rectangle bounds = getViewport().getVisibleRect();
g2.scale(bounds.getWidth(), -1);
int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight();
g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null);
g2.scale(1, -1);
g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
}
}

since I search for different suggestion I closed this question with my original knowledges about Graphics
based on code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
//import java.awt.image.ColorModel; // I don't know how to use that
//import java.awt.image.SampleModel;// I don't know how to use that
import javax.swing.*;
import javax.swing.RepaintManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableModel;
public class ViewPortFlickeringOriginal {
private JFrame frame = new JFrame("Table");
private JViewport viewport = new JViewport();
private Rectangle RECT = new Rectangle();
private Rectangle RECT1 = new Rectangle();
private JTable table = new JTable(50, 3);
private javax.swing.Timer timer;
private int count = 0;
private boolean topOrBottom = false;
private GradientViewPortOriginal tableViewPort;
public ViewPortFlickeringOriginal() {
tableViewPort = new GradientViewPortOriginal(table);
viewport = tableViewPort.getViewport();
viewport.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (tableViewPort.bolStart) {
RECT = table.getCellRect(0, 0, true);
RECT1 = table.getCellRect(table.getRowCount() - 1, 0, true);
Rectangle viewRect = viewport.getViewRect();
if (viewRect.intersects(RECT)) {
System.out.println("Visible RECT -> " + RECT);
tableViewPort.paintBackGround(new Color(250, 150, 150));
} else if (viewRect.intersects(RECT1)) {
System.out.println("Visible RECT1 -> " + RECT1);
tableViewPort.paintBackGround(new Color(150, 250, 150));
} else {
System.out.println("Visible RECT1 -> ???? ");
tableViewPort.paintBackGround(new Color(150, 150, 250));
}
}
}
});
frame.add(tableViewPort);
frame.setPreferredSize(new Dimension(600, 300));
frame.pack();
frame.setLocation(50, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RepaintManager.setCurrentManager(new RepaintManager() {
#Override
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Container con = c.getParent();
while (con instanceof JComponent) {
if (!con.isVisible()) {
return;
}
if (con instanceof GradientViewPortOriginal) {
c = (JComponent) con;
x = 0;
y = 0;
w = con.getWidth();
h = con.getHeight();
}
con = con.getParent();
}
super.addDirtyRegion(c, x, y, w, h);
}
});
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(100, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("updating row " + (count + 1));
TableModel model = table.getModel();
int cols = model.getColumnCount();
int row = 0;
for (int j = 0; j < cols; j++) {
row = count;
table.changeSelection(row, 0, false, false);
timer.setDelay(100);
Object value = "row " + (count + 1) + " item " + (j + 1);
model.setValueAt(value, count, j);
}
count++;
if (count >= table.getRowCount()) {
timer.stop();
table.changeSelection(0, 0, false, false);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
table.clearSelection();
tableViewPort.bolStart = true;
}
});
}
}
};
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ViewPortFlickeringOriginal viewPortFlickering = new ViewPortFlickeringOriginal();
}
});
}
}
class GradientViewPortOriginal extends JScrollPane {
private static final long serialVersionUID = 1L;
private final int h = 50;
private BufferedImage img = null;
private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB);
private JViewport viewPort;
public boolean bolStart = false;
public GradientViewPortOriginal(JComponent com) {
super(com);
viewPort = this.getViewport();
viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE);
viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
paintBackGround(new Color(250, 150, 150));
}
public void paintBackGround(Color g) {
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(g);
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h,
new Color(0.1f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paint(Graphics g) {
if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paint(g2);
Rectangle bounds = getViewport().getVisibleRect();
g2.scale(bounds.getWidth(), -1);
int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight();
g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null);
g2.scale(1, -1);
g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
}
}

Something like this... a bit of a hack.
class GradientViewPort extends JScrollPane {
private static final long serialVersionUID = 1L;
private final int h = 50;
private BufferedImage img = null;
private BufferedImage imgBottom = null;
private BufferedImage shadow = new BufferedImage(1, h,
BufferedImage.TYPE_INT_ARGB);
private BufferedImage shadowBottom = new BufferedImage(1, h,
BufferedImage.TYPE_INT_ARGB);
private JViewport viewPort;
public GradientViewPort(JComponent com) {
super(com);
viewPort = this.getViewport();
viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE);
viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
createShadow(new Color(250, 150, 150),shadow);
createShadow(Color.BLUE,shadowBottom);
}
private void createShadow(Color color, BufferedImage shadow) {
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(color);
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h,
new Color(0.5f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paint(Graphics g) {
paintTop(g,img);
paintBottom(g,imgBottom);
}
private void paintBottom(Graphics g,BufferedImage img) {
if (img == null || img.getWidth() != getWidth()
|| img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
//super.paint(g2);
Rectangle bounds = getViewport().getVisibleRect();
g2.scale(bounds.getWidth(), -1);
int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight();
//g2.drawImage(shadowBottom, bounds.x, -bounds.y - y - h, null);
g2.scale(1, -1);
g2.drawImage(shadowBottom, bounds.x, bounds.y + bounds.height - h + y, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
}
private void paintTop(Graphics g,BufferedImage img) {
if (img == null || img.getWidth() != getWidth()
|| img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paint(g2);
Rectangle bounds = getViewport().getVisibleRect();
g2.scale(bounds.getWidth(), -1);
int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight();
g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null);
g2.scale(1, -1);
//g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
}
EDIT fixed the code so when first and last row are in the view port the color is red when they are not the color is blue.
class GradientViewPort extends JScrollPane {
private static final long serialVersionUID = 1L;
private final int h = 50;
private BufferedImage imgRed = null;
private BufferedImage imgBlue = null;
private BufferedImage shadowRed = new BufferedImage(1, h,
BufferedImage.TYPE_INT_ARGB);
private BufferedImage shadowBlue = new BufferedImage(1, h,
BufferedImage.TYPE_INT_ARGB);
private JViewport viewPort;
private boolean recVisible = true;
public GradientViewPort(JComponent com) {
super(com);
viewPort = this.getViewport();
viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE);
viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
createShadow(new Color(250, 150, 150),shadowRed);
createShadow(Color.BLUE,shadowBlue);
final JTable table = (JTable) com;
viewport.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
Rectangle RECT = table.getCellRect(0, 0, true);
Rectangle viewRect = viewport.getViewRect();
if (viewRect.intersects(RECT)) {
System.out.println("Visible RECT -> " + RECT);
recVisible = true;
} else {
recVisible = false;
}
}
});
}
private void createShadow(Color color, BufferedImage shadow) {
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(color);
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h,
new Color(0.5f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paint(Graphics g) {
if(recVisible){
paintShadow(g,imgRed,shadowRed);
} else {
paintShadow(g,imgBlue,shadowBlue);
}
}
private void paintShadow(Graphics g,BufferedImage img, BufferedImage shadow) {
if (img == null || img.getWidth() != getWidth()
|| img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paint(g2);
Rectangle bounds = getViewport().getVisibleRect();
g2.scale(bounds.getWidth(), -1);
int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight();
g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null);
g2.scale(1, -1);
g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
}
}

Related

AccessControlException Applet in a html page

I wrote a game in Java and I want to put it on a HTML page. I know how, but the problem is that it gives me a AcessControlException (java.io.FilePermission "/SomePath/SomeFile.SomeExtension" "read").
Here is the Game class (loads the files at initGame method and init the JApplet):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.swing.JApplet;
public class Game extends JApplet implements Runnable {
private static final long serialVersionUID = 1L;
private Thread thread;
public static BufferedImage level;
public static BufferedImage background;
public static Image2d tileset;
public static Sprite red;
public static Sprite green;
public static Sprite player;
public static boolean mouse_left, mouse_right;
public static boolean jumping;
public static boolean play;
private boolean running = false;
private Image screen;
public static RandomLevel map;
public static Listener listener;
public static Gui gui;
public static int FALL_SPEED = 3;
public static int JUMP_SPEED = 3;
public static int JUMP_HEIGHT = 20;
public static int jump_amount = 0;
public static float START_OFFSET_SPEED = 3.0f;
public static float OFFSET_SPEED = 2.0f;
public static final int sxOffset = 0, syOffset = 0;
public static int xOffset = 0, yOffset = 0;
public static final int CURR_COLOR_SCALE = 32;
public static Sprite[] tiles = new Sprite[2];
public static int selected_color = 0;
public static int SCORE = 0;
public static final int TILE_SIZE = 16;
public static final int SCALE = TILE_SIZE * 2;
public static boolean left, right;
public static int currTime = 0;
public static final Dimension size = new Dimension(800, 600);
public static final Dimension pixel = new Dimension(size.width - SCALE, size.height - SCALE);
public void initGame() {
try {
URL levelUrl = new URL(getCodeBase(), "res/map.png");
level = new Image2d(levelUrl).getImage();
URL backgroundUrl = new URL(getCodeBase(), "res/background.png");
background = new Image2d(backgroundUrl).getImage();
URL tilesetUrl = new URL(getCodeBase(), "res/tileset.png");
tileset = new Image2d(tilesetUrl);
} catch (IOException e) {
}
red = new Sprite(new Image2d(tileset.crop(0, 0, Game.TILE_SIZE, Game.TILE_SIZE)));
green = new Sprite(new Image2d(tileset.crop(1, 0, Game.TILE_SIZE, Game.TILE_SIZE)));
player = new Sprite(new Image2d(tileset.crop(2, 0, Game.TILE_SIZE, Game.TILE_SIZE)));
tiles[0] = red;
tiles[1] = green;
gui = new Gui();
listener = new Listener();
player.setX((size.width - player.getImage().getWidth(null)) / 2);
player.setY((size.height - player.getImage().getHeight(null)) / 2 + 100);
map = new RandomLevel(10000, 20, TILE_SIZE, SCALE, size, xOffset, yOffset);
map.addCollsion(tiles[0]);
addMouseListener(listener);
addMouseMotionListener(new Mouse());
}
public static void switchCollision(Sprite tile) {
map.collision.add(0, tile);
for (int i = 0; i < map.collision.size(); i++) {
if (i != 0)
map.collision.remove(i);
}
}
public void resetGame() {
xOffset = sxOffset;
yOffset = syOffset;
OFFSET_SPEED = START_OFFSET_SPEED;
Game.SCORE = 0;
play = false;
map.generateLevel();
}
public void startGame() {
if (running)
return;
initGame();
running = true;
thread = new Thread(this);
thread.start();
}
public void stopGame() {
if (!running)
return;
running = true;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
screen = createVolatileImage(pixel.width, pixel.height);
requestFocus();
while (running) {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 1000000000.0 / 60.0;
double delta = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
update();
delta--;
}
render();
if (System.currentTimeMillis() - timer > 100) {
timer += 1000;
}
}
stop();
}
}
public void update() {
if (!play && mouse_left)
play = true;
if (play) {
switchCollision(tiles[selected_color]);
if (yOffset > 180)
resetGame();
map.update();
map.setxOffset(xOffset);
map.setyOffset(yOffset);
player.update(25);
gui.update();
if (!map.getTileDownCollision(player))
yOffset += FALL_SPEED;
if (!Game.map.getTileRightCollision(player))
xOffset += Math.round(OFFSET_SPEED);
if (SCORE > 20)
OFFSET_SPEED = 4.0f;
if (SCORE > 40)
OFFSET_SPEED = 5.0f;
if (SCORE > 60)
OFFSET_SPEED = 6.0f;
if (SCORE > 80)
OFFSET_SPEED = 7.0f;
if (SCORE > 100)
OFFSET_SPEED = 8.0f;
if (SCORE > 120)
OFFSET_SPEED = 9.0f;
if (SCORE > 140)
OFFSET_SPEED = 10.0f;
if (jumping) {
FALL_SPEED = 0;
yOffset -= JUMP_SPEED;
jump_amount++;
if (jump_amount >= JUMP_HEIGHT) {
jumping = false;
FALL_SPEED = 3;
jump_amount = 0;
}
}
}
}
public void render() {
Graphics g = screen.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, size.width, size.height);
map.render(g);
g.drawImage(player.getImage(), Math.round(player.getX()), Math.round(player.getY()), Game.TILE_SIZE + Game.SCALE, Game.TILE_SIZE + Game.SCALE, null);
g.setFont(new Font("new Font", Font.PLAIN, 10));
g.setColor(Color.white);
g.drawString("CLICK ON THIS SIDE TO JUMP", 200 - xOffset, 240);
g.drawString("CLICK ON THIS SIDE TO SWITCH COLOR", size.width - 350 - xOffset, 240);
g.drawImage(background, 0, 0, null);
g.drawImage(map.collision.get(0).getImage(), (size.width - (Game.TILE_SIZE + CURR_COLOR_SCALE)) / 2, CURR_COLOR_SCALE / 2 - 5, Game.TILE_SIZE + CURR_COLOR_SCALE, Game.TILE_SIZE + CURR_COLOR_SCALE, null);
gui.render(g);
g.setFont(new Font("new Font", Font.BOLD, 32));
g.setColor(Color.yellow);
g.drawString("SCORE: " + SCORE, 10, 32);
g = getGraphics();
g.drawImage(screen, 0, 0, size.width, size.height, 0, 0, pixel.width, pixel.height, null);
g.dispose();
}
public void destroy() {
System.exit(0);
}
public void init() {
setSize(size);
setVisible(true);
startGame();
}
}
EDIT: Here is the Image2d class(holds ImageIO.read command)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Image2d{
private BufferedImage image;
public Image2d(URL url) {
try {
image = ImageIO.read(url);
} catch (IOException e) {
System.err.println("No file found at: " + url);
}
}
public Image2d(String path) {
try {
image = ImageIO.read(new File(path));
} catch (IOException e) {
System.err.println("No file found at: " + path);
}
}
public static BufferedImage load(URL url) {
try {
return ImageIO.read(url);
} catch (IOException e) {
System.err.println("No file found at: " + url.getPath());
return null;
}
}
public static BufferedImage load(String path) {
try {
return ImageIO.read(new File(path));
} catch (IOException e) {
System.err.println("No file found at: " + path);
return null;
}
}
public Image2d(BufferedImage image) {
this.image = image;
}
public BufferedImage crop(int x, int y, int w, int h) {
return image.getSubimage(x * w, y * h, w, h);
}
public static BufferedImage insert(Image2d target, Image2d component) {
BufferedImage tile = new BufferedImage(target.getImage().getWidth(), target.getImage().getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = tile.getGraphics();
g.drawImage(component.getImage(), 0, 0, component.getImage().getWidth(), component.getImage().getHeight(), null);
g.drawImage(target.getImage(), 0, 0, target.getImage().getWidth(), target.getImage().getHeight(), null);
return tile;
}
public static BufferedImage switchColor(BufferedImage image, Color color1, Color color2) {
Graphics g = image.getGraphics();
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color color = new Color(image.getRGB(x, y));
if (color.getRed() == color1.getRed() && color.getGreen() == color1.getGreen() && color.getBlue() == color1.getBlue() && color.getAlpha() == color1.getAlpha()) {
g.setColor(color2);
g.fillRect(x, y, 1, 1);
}
}
}
return image;
}
public static BufferedImage fill(Color color, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(color);
g.fillRect(0, 0, width, height);
return image;
}
public static BufferedImage switchColor(BufferedImage image, Color[] color1, Color[] color2) {
Graphics g = image.getGraphics();
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color color = new Color(image.getRGB(x, y));
for (int i = 0; i < color1.length; i++)
if (color.getRed() == color1[i].getRed() && color.getGreen() == color1[i].getGreen() && color.getBlue() == color1[i].getBlue() && color.getAlpha() == color1[i].getAlpha()) {
g.setColor(color2[i]);
g.fillRect(x, y, 1, 1);
}
}
}
return image;
}
public static BufferedImage createYDropShadow(int width, int height, int startAlpha, float density, float offset, Color color) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
int alpha = startAlpha;
for (int y = 0; y < image.getHeight(); y++) {
if (alpha >= density)
alpha -= density;
for (int x = 0; x < image.getWidth(); x++) {
g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha));
g.fillRect(x + Math.round(offset), y + Math.round(offset), 1 + Math.round(offset), 1 + Math.round(offset));
}
}
return image;
}
public static BufferedImage createXDropShadow(int width, int height, int startAlpha, float density, float offset, Color color) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
int alpha = startAlpha;
for (int x = 0; x < image.getWidth(); x++) {
if (alpha >= density)
alpha -= density;
for (int y = 0; y < image.getHeight(); y++) {
g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha));
g.fillRect(x + Math.round(offset), y + Math.round(offset), 1 + Math.round(offset), 1 + Math.round(offset));
}
}
return image;
}
public BufferedImage getImage() {
return image;
}
}
And here is html code (it is inside a jar file called Blocks.jar):
<!DOCTYPE html>
<html>
<body>
<applet code="Game.class" archive="Blocks.jar" width="600" height="600"> </applet>
</body>
</html>
I saw people getting the same error but, no answer gave me a solution that worked. So what shoud I do for load the images without erros?
PS: The JApplet is running fine in eclipse, but at the html page throws me this error.
Thanks!

How to make JButton with transparent background and regular text?

Is there a way to make a JButton which has a transparent fill(30% transparent) and a text which is not transparent?
For now I discovered the following options:
make both the button and the text transparent.
make both of them not transparent.
is there an option in between?
Here is one possible implementation using JButton#setIcon(Icon_30%_transparent):
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
public final class TranslucentButtonIconTest {
private static final TexturePaint TEXTURE = makeCheckerTexture();
public JComponent makeUI() {
JPanel p = new JPanel() {
#Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(TEXTURE);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
p.add(makeButton("aaa"));
p.add(makeButton("bbbbbbb"));
p.add(makeButton("ccccccccccc"));
p.add(makeButton("ddddddddddddddddddddddddddddd"));
return p;
}
private static AbstractButton makeButton(String title) {
return new JButton(title) {
#Override public void updateUI() {
super.updateUI();
setVerticalAlignment(SwingConstants.CENTER);
setVerticalTextPosition(SwingConstants.CENTER);
setHorizontalAlignment(SwingConstants.CENTER);
setHorizontalTextPosition(SwingConstants.CENTER);
setBorder(BorderFactory.createEmptyBorder(2, 8, 2, 8));
setMargin(new Insets(2, 8, 2, 8));
setContentAreaFilled(false);
setFocusPainted(false);
setOpaque(false);
setForeground(Color.WHITE);
setIcon(new TranslucentButtonIcon());
}
};
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TranslucentButtonIconTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static TexturePaint makeCheckerTexture() {
int cs = 6;
int sz = cs * cs;
BufferedImage img = new BufferedImage(sz, sz, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setPaint(new Color(120, 120, 220));
g2.fillRect(0, 0, sz, sz);
g2.setPaint(new Color(200, 200, 200, 20));
for (int i = 0; i * cs < sz; i++) {
for (int j = 0; j * cs < sz; j++) {
if ((i + j) % 2 == 0) {
g2.fillRect(i * cs, j * cs, cs, cs);
}
}
}
g2.dispose();
return new TexturePaint(img, new Rectangle(0, 0, sz, sz));
}
}
class TranslucentButtonIcon implements Icon {
private static final int R = 8;
private int width;
private int height;
#Override public void paintIcon(Component c, Graphics g, int x, int y) {
if (c instanceof AbstractButton) {
AbstractButton b = (AbstractButton) c;
Insets i = b.getMargin();
int w = c.getWidth();
int h = c.getHeight();
width = w - i.left - i.right;
height = h - i.top - i.bottom;
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Shape area = new RoundRectangle2D.Float(x - i.left, y - i.top, w - 1, h - 1, R, R);
Color color = new Color(0f, 0f, 0f, .3f);
ButtonModel m = b.getModel();
if (m.isPressed()) {
color = new Color(0f, 0f, 0f, .3f);
} else if (m.isRollover()) {
color = new Color(1f, 1f, 1f, .3f);
}
g2.setPaint(color);
g2.fill(area);
g2.setPaint(Color.WHITE);
g2.draw(area);
g2.dispose();
}
}
#Override public int getIconWidth() {
return Math.max(width, 100);
}
#Override public int getIconHeight() {
return Math.max(height, 24);
}
}

Java: create shadow effect on image

I'm trying to create a shadow effect (with java) on an image.
I've seen multiple related questions and I've implemented several of the suggested solutions. Unfortunately I always have the same problem: the shadow effect repaints the entire image in gray (i.e. the shadow color) - hence the original image is not visible anymore.
Example of code I tested (based on the JIDE freely available library):
ShadowFactory sf = new ShadowFactory(2, 0.5f, Color.black);
ImageIO.write(sf.createShadow(ImageIO.read(new File("c:\\out2.png"))), "png", new File("c:\\out3.png"));
No need to says that I tested this with multiple source files (out2.png).
I'm clueless: any hint/help would be highly appreciated.
The over all theory is simple. Basically, you need to generate a mask of the image (using a AlphaComposite and fill that resulting image with the color you want (also using an AlphaComposite. This, of course, all works on the alpha channel of the image...
Once you have that mask, you need to combine the two images (overlaying the original image with the masked image)
This examples make use of JHLabs filters to supply the blur...
public class TestImageDropShadow {
public static void main(String[] args) {
new TestImageDropShadow();
}
public TestImageDropShadow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
private BufferedImage background;
public ImagePane() {
try {
BufferedImage master = ImageIO.read(getClass().getResource("/Scaled.png"));
background = applyShadow(master, 5, Color.BLACK, 0.5f);
} catch (IOException ex) {
Logger.getLogger(TestImageDropShadow.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}
public static void applyQualityRenderingHints(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
}
public static BufferedImage createCompatibleImage(int width, int height) {
return createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
public static BufferedImage createCompatibleImage(int width, int height, int transparency) {
BufferedImage image = getGraphicsConfiguration().createCompatibleImage(width, height, transparency);
image.coerceData(true);
return image;
}
public static BufferedImage createCompatibleImage(BufferedImage image) {
return createCompatibleImage(image, image.getWidth(), image.getHeight());
}
public static BufferedImage createCompatibleImage(BufferedImage image,
int width, int height) {
return getGraphicsConfiguration().createCompatibleImage(width, height, image.getTransparency());
}
public static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
public static BufferedImage generateMask(BufferedImage imgSource, Color color, float alpha) {
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgBlur.createGraphics();
applyQualityRenderingHints(g2);
g2.drawImage(imgSource, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2.setColor(color);
g2.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2.dispose();
return imgBlur;
}
public static BufferedImage generateBlur(BufferedImage imgSource, int size, Color color, float alpha) {
GaussianFilter filter = new GaussianFilter(size);
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgBlur.createGraphics();
applyQualityRenderingHints(g2);
g2.drawImage(imgSource, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2.setColor(color);
g2.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2.dispose();
imgBlur = filter.filter(imgBlur, null);
return imgBlur;
}
public static BufferedImage applyShadow(BufferedImage imgSource, int size, Color color, float alpha) {
BufferedImage result = createCompatibleImage(imgSource, imgSource.getWidth() + (size * 2), imgSource.getHeight() + (size * 2));
Graphics2D g2d = result.createGraphics();
g2d.drawImage(generateShadow(imgSource, size, color, alpha), size, size, null);
g2d.drawImage(imgSource, 0, 0, null);
g2d.dispose();
return result;
}
public static BufferedImage generateShadow(BufferedImage imgSource, int size, Color color, float alpha) {
int imgWidth = imgSource.getWidth() + (size * 2);
int imgHeight = imgSource.getHeight() + (size * 2);
BufferedImage imgMask = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgMask.createGraphics();
applyQualityRenderingHints(g2);
int x = Math.round((imgWidth - imgSource.getWidth()) / 2f);
int y = Math.round((imgHeight - imgSource.getHeight()) / 2f);
g2.drawImage(imgSource, x, y, null);
g2.dispose();
// ---- Blur here ---
BufferedImage imgGlow = generateBlur(imgMask, (size * 2), color, alpha);
return imgGlow;
}
public static Image applyMask(BufferedImage sourceImage, BufferedImage maskImage) {
return applyMask(sourceImage, maskImage, AlphaComposite.DST_IN);
}
public static BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {
BufferedImage maskedImage = null;
if (sourceImage != null) {
int width = maskImage.getWidth(null);
int height = maskImage.getHeight(null);
maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D mg = maskedImage.createGraphics();
int x = (width - sourceImage.getWidth(null)) / 2;
int y = (height - sourceImage.getHeight(null)) / 2;
mg.drawImage(sourceImage, x, y, null);
mg.setComposite(AlphaComposite.getInstance(method));
mg.drawImage(maskImage, 0, 0, null);
mg.dispose();
}
return maskedImage;
}
}
This is my Version:
private static Image dropShadow(BufferedImage img) {
// a filter which converts all colors except 0 to black
ImageProducer prod = new FilteredImageSource(img.getSource(), new RGBImageFilter() {
#Override
public int filterRGB(int x, int y, int rgb) {
if (rgb == 0)
return 0;
else
return 0xff000000;
}
});
// create whe black image
Image shadow = Toolkit.getDefaultToolkit().createImage(prod);
// result
BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
Graphics2D g = (Graphics2D) result.getGraphics();
// draw shadow with offset
g.drawImage(shadow, 10, 0, null);
// draw original image
g.drawImage(img, 0, 0, null);
return result;
}

Translucent JFrame border JDK 7

I was asking question about Translucent JFrame border (see here) and I got very good answers, but unfortunatelly, given answers work perfectly only on JDK 6, but not 7. Any ideas how to make it work with JDK 7?
In JDK 6 it looks like this:
And JDK 7:
And my code looks like this:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.border.AbstractBorder;
public class ShadowBorder extends AbstractBorder {
private static final int RADIUS = 30;
private static BufferedImage shadowTop;
private static BufferedImage shadowRight;
private static BufferedImage shadowBottom;
private static BufferedImage shadowLeft;
private static BufferedImage shadowTopLeft;
private static BufferedImage shadowTopRight;
private static BufferedImage shadowBottomLeft;
private static BufferedImage shadowBottomRight;
private static boolean shadowsLoaded = false;
public ShadowBorder() {
if (!shadowsLoaded) {
try {
shadowTop = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-top.png"));
shadowRight = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-right.png"));
shadowBottom = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-bottom.png"));
shadowLeft = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-left.png"));
shadowTopLeft = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-top-left.png"));
shadowTopRight = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-top-right.png"));
shadowBottomLeft = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-bottom-left.png"));
shadowBottomRight = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-bottom-right.png"));
shadowsLoaded = true;
} catch (IOException ex) {
Logger.getLogger(ShadowBorder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public boolean isBorderOpaque() {
return false;
}
#Override
public Insets getBorderInsets(Component c) {
return new Insets(RADIUS, RADIUS, RADIUS, RADIUS);
}
#Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.top = RADIUS;
insets.left = RADIUS;
insets.bottom = RADIUS;
insets.right = RADIUS;
return insets;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_ATOP, 1f));
int recWidth = width - (2 * RADIUS);
int recHeight = height - (2 * RADIUS);
int recX = width - RADIUS;
int recY = height - RADIUS;
//edges
g2d.drawImage(shadowTop.getScaledInstance(recWidth, RADIUS, Image.SCALE_REPLICATE), RADIUS, 0, null);
g2d.drawImage(shadowRight.getScaledInstance(RADIUS, recHeight, Image.SCALE_REPLICATE), recX, RADIUS, null);
g2d.drawImage(shadowBottom.getScaledInstance(recWidth, RADIUS, Image.SCALE_REPLICATE), RADIUS, recY, null);
g2d.drawImage(shadowLeft.getScaledInstance(RADIUS, recHeight, Image.SCALE_REPLICATE), 0, RADIUS, null);
//corners
g2d.drawImage(shadowTopLeft, 0, 0, null);
g2d.drawImage(shadowTopRight, recX, 0, null);
g2d.drawImage(shadowBottomLeft, 0, recY, null);
g2d.drawImage(shadowBottomRight, recX, recY, null);
}
}
Thanks a lot!
I've just solved my problem. The problem was, that JDK 7 implements AWTUtilities.setWindowOpaque() method from JDK6 in setBackground() method and I was (NetBeans did :-)) setting default background for JFrame in different place, so setting background to new Color(0, 0, 0, 0); makes JFrame transparent and all goes well now.
For whoever stumbles upon this thread and wants his own transparent window, I devised this example. With how little information is available on the web, I almost had to break a leg to come up with something just works, and doesn't use image files or anything. (Combined from different examples on this site)
public class GradientTranslucentWindowDemo
{
public static void main(String[] args)
{
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
final JFrame f = new JFrame("Per-pixel translucent window");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.setBackground(new Color(0, 0, 0, 0));
final BufferedImage backrgoundImage = makeBackrgoundImage(400, 400);
JPanel panel = new JPanel()
{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (g instanceof Graphics2D)
{
g.drawImage(backrgoundImage, 0, 0, null);
}
}
};
panel.setOpaque(false);
f.setContentPane(panel);
f.setLayout(new GridBagLayout()); // Centers the button
f.add(new JButton(new AbstractAction("Close")
{
#Override
public void actionPerformed(ActionEvent e)
{
f.dispose();
}
}));
f.setBounds(100, 100, 400, 400);
f.setVisible(true);
}
});
}
static BufferedImage makeBackrgoundImage(int w, int h)
{
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// Draw something transparent
Graphics2D g = img.createGraphics();
g.setPaint(new RadialGradientPaint(new Point2D.Float(w / 2, h / 2), (w + h) / 4, new float[]{0, 1}, new Color[]{Color.RED, new Color(1f, 0, 0, 0)}));
g.fillRect(0, 0, w, h);
g.setPaint(Color.RED);
g.drawRect(0, 0, w - 1, h - 1);
g.dispose();
return img;
}
}

Text Scrolling in java

Pleae help to solve this problem... I has a page designed in JFrames
Now i need to make a text scrolling at the top of the page.... Please provide me the code...
Check this out, is is commented and will most likely help you.
http://www.abbeyworkshop.com/howto/java/ta_scroll/index.html
Perhaps this thread may be of interest to you: Creating A Scrolling Marquee
ScrollText s= new ScrollText("ello Everyone.");
jLabel3.add(s);//add it to jLabel
public class ScrollText extends JComponent {
private BufferedImage image;
private Dimension imageSize;
private volatile int currOffset;
private Thread internalThread;
private volatile boolean noStopRequested;
public ScrollText(String text) {
currOffset = 0;
buildImage(text);
setMinimumSize(imageSize);
setPreferredSize(imageSize);
setMaximumSize(imageSize);
setSize(imageSize);
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch (Exception x) {
x.printStackTrace();
}
}
};
internalThread = new Thread(r, "ScrollText");
internalThread.start();
}
private void buildImage(String text) {
RenderingHints renderHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage scratchImage = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_RGB);
Graphics2D scratchG2 = scratchImage.createGraphics();
scratchG2.setRenderingHints(renderHints);
Font font = new Font("Serif", Font.BOLD | Font.ITALIC, 24);
FontRenderContext frc = scratchG2.getFontRenderContext();
TextLayout tl = new TextLayout(text, font, frc);
Rectangle2D textBounds = tl.getBounds();
int textWidth = (int) Math.ceil(textBounds.getWidth());
int textHeight = (int) Math.ceil(textBounds.getHeight());
int horizontalPad = 600;
int verticalPad = 10;
imageSize = new Dimension(textWidth + horizontalPad, textHeight
+ verticalPad);
image = new BufferedImage(imageSize.width, imageSize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHints(renderHints);
int baselineOffset = (verticalPad / 2) - ((int) textBounds.getY());
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, imageSize.width, imageSize.height);
g2.setColor(Color.GREEN);
tl.draw(g2, 0, baselineOffset);
// Free-up resources right away, but keep "image" for
// animation.
scratchG2.dispose();
scratchImage.flush();
g2.dispose();
}
public void paint(Graphics g) {
// Make sure to clip the edges, regardless of curr size
g.setClip(0, 0, imageSize.width, imageSize.height);
int localOffset = currOffset; // in case it changes
g.drawImage(image, -localOffset, 0, this);
g.drawImage(image, imageSize.width - localOffset, 0, this);
g.setColor(Color.black);
g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
}
private void runWork() {
while (noStopRequested) {
try {
Thread.sleep(10); // 10 frames per second
// adjust the scroll position
currOffset = (currOffset + 1) % imageSize.width;
// signal the event thread to call paint()
repaint();
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
}
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive() {
return internalThread.isAlive();
}
}

Categories

Resources