I am programming a sprite editor and I would like to implement an Undo button to my program. In order to achieve that, I have thought to use an ArrayList that store my updated BufferedImage after each action in an ArrayList. Then I will just read the ArrayList and find the right image to draw thanks to an index. However, it seems like it always store the same image. I don't know what I am doing wrong so I am asking for your help and advice.
Here is a test code:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
#SuppressWarnings("serial")
public class FromGraphicsToBufferedImage extends JPanel{
private static final int BI_WIDTH = 600;
private static final int BI_HEIGHT = BI_WIDTH;
private static BufferedImage bImage = new BufferedImage(BI_WIDTH, BI_HEIGHT, BufferedImage.TYPE_INT_ARGB); //Enregistrement de l'image en RGBA
private List<Point> pointList = new ArrayList<Point>();
private JLabel imageLabel;
private boolean isInit = false;
private static ArrayList<BufferedImage> historic = new ArrayList<BufferedImage>();
private int historicIndex = 0;
//Constructeur
public FromGraphicsToBufferedImage() {
imageLabel = new JLabel(new ImageIcon(bImage)) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintInLabel(g);
}
};
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
imageLabel.addMouseListener(myMouseAdapter);
imageLabel.addMouseMotionListener(myMouseAdapter);
imageLabel.setBorder(BorderFactory.createEtchedBorder());
JButton saveImageBtn = new JButton("Save Image");
saveImageBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveImageActionPerformed();
}
});
JButton clearImageBtn = new JButton("Clear Image");
clearImageBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Graphics2D g2 = bImage.createGraphics();
g2.setBackground(new Color(255,255,255,0));
g2.clearRect(0, 0, BI_WIDTH, BI_HEIGHT);
g2.dispose();
imageLabel.repaint();
}
});
JButton undo = new JButton("Undo");
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("UNDO");
historicIndex -= 1;
bImage = historic.get(historicIndex);
Graphics2D g2 = bImage.createGraphics();
g2.drawImage(bImage, 0, 0, bImage.getWidth(), bImage.getHeight(), imageLabel);
g2.dispose();
imageLabel.setIcon(new ImageIcon(bImage));
imageLabel.repaint();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(saveImageBtn);
btnPanel.add(clearImageBtn);
btnPanel.add(undo);
setLayout(new BorderLayout());
add(imageLabel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
} //Fin du Constructeur
private void saveImageActionPerformed() {
JFileChooser filechooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Images", "png");
filechooser.setFileFilter(filter);
int result = filechooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File saveFile = filechooser.getSelectedFile();
try {
ImageIO.write(bImage, "png", saveFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void paintInLabel(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d = bImage.createGraphics();
if(isInit == false) {
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, BI_WIDTH, BI_HEIGHT);
g2d.dispose();
isInit = true;
}
else {
g2d.setColor(Color.BLUE);
if(pointList.size() == 0) {
return;
}
//System.out.println(bImage.getRGB(50, 50));
int x1 = pointList.get(0).x;
int y1 = pointList.get(0).y;
int x2 = pointList.get(0).x+32;
int y2 = pointList.get(0).y+32;
g2d.setComposite(AlphaComposite.Src);
g2d.setColor(new Color(255,255,255,0));
g2d.fillRect(x1,y1,32,32);
g2d.dispose();
pointList.clear();
}
historic.add(deepCopy(bImage));
imageLabel.repaint();
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
pointList.add(e.getPoint());
imageLabel.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
//historic.add(deepCopy(bImage));
System.out.println("Historic Size: " + historic.size());
int tailleHistorique = historic.size();
historicIndex = tailleHistorique-1;
if(historic.size() >= 2) {
System.out.println("The 2 images are the same: " + compareImages(historic.get(historicIndex-1), historic.get(historicIndex)));
}
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("DrawAndSaveImage");
frame.getContentPane().add(new FromGraphicsToBufferedImage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static BufferedImage getBufferedImage() {
return bImage;
}
public static boolean compareImages(BufferedImage imgA, BufferedImage imgB) {
if (imgA.getWidth() == imgB.getWidth() && imgA.getHeight() == imgB.getHeight()) {
int largeurImage = imgA.getWidth();
int hauteurImage = imgA.getHeight();
for (int y = 0; y < hauteurImage; y++) {
for (int x = 0; x < largeurImage; x++) {
if (imgA.getRGB(x, y) != imgB.getRGB(x, y)){
return false;
}
}
}
}
else {
return false;
}
return true;
}
static BufferedImage deepCopy(BufferedImage bi) {
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(null);
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
DeepCopy Code Snippet
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
#SuppressWarnings("serial")
public class FromGraphicsToBufferedImage extends JPanel{
private static final int BI_WIDTH = 600;
private static final int BI_HEIGHT = BI_WIDTH;
private static BufferedImage bImage = new BufferedImage(BI_WIDTH, BI_HEIGHT, BufferedImage.TYPE_INT_ARGB); //Enregistrement de l'image en RGBA
private List<Point> pointList = new ArrayList<Point>();
private JLabel imageLabel;
private boolean isInit = false;
private static ArrayList<BufferedImage> historic = new ArrayList<BufferedImage>();
private int historicIndex = 0;
//Constructeur
public FromGraphicsToBufferedImage() {
imageLabel = new JLabel(new ImageIcon(bImage)) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintInLabel(g);
}
};
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
imageLabel.addMouseListener(myMouseAdapter);
imageLabel.addMouseMotionListener(myMouseAdapter);
imageLabel.setBorder(BorderFactory.createEtchedBorder());
JButton saveImageBtn = new JButton("Save Image");
saveImageBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveImageActionPerformed();
}
});
JButton clearImageBtn = new JButton("Clear Image");
clearImageBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Graphics2D g2 = bImage.createGraphics();
g2.setBackground(new Color(255,255,255,0));
g2.clearRect(0, 0, BI_WIDTH, BI_HEIGHT);
g2.dispose();
imageLabel.repaint();
}
});
JButton undo = new JButton("Undo");
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("UNDO");
historicIndex -= 1;
bImage = historic.get(historicIndex);
Graphics2D g2 = bImage.createGraphics();
g2.drawImage(bImage, 0, 0, bImage.getWidth(), bImage.getHeight(), imageLabel);
g2.dispose();
imageLabel.setIcon(new ImageIcon(bImage));
imageLabel.repaint();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(saveImageBtn);
btnPanel.add(clearImageBtn);
btnPanel.add(undo);
setLayout(new BorderLayout());
add(imageLabel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
} //Fin du Constructeur
private void saveImageActionPerformed() {
JFileChooser filechooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Images", "png");
filechooser.setFileFilter(filter);
int result = filechooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File saveFile = filechooser.getSelectedFile();
try {
ImageIO.write(bImage, "png", saveFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void paintInLabel(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d = bImage.createGraphics();
if(isInit == false) {
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, BI_WIDTH, BI_HEIGHT);
g2d.dispose();
isInit = true;
}
else {
g2d.setColor(Color.BLUE);
if(pointList.size() == 0) {
return;
}
//System.out.println(bImage.getRGB(50, 50));
int x1 = pointList.get(0).x;
int y1 = pointList.get(0).y;
int x2 = pointList.get(0).x+32;
int y2 = pointList.get(0).y+32;
g2d.setComposite(AlphaComposite.Src);
g2d.setColor(new Color(255,255,255,0));
g2d.fillRect(x1,y1,32,32);
g2d.dispose();
pointList.clear();
}
historic.add(deepCopy(bImage));
imageLabel.repaint();
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
pointList.add(e.getPoint());
imageLabel.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
//historic.add(deepCopy(bImage));
System.out.println("Historic Size: " + historic.size());
int tailleHistorique = historic.size();
historicIndex = tailleHistorique-1;
if(historic.size() >= 2) {
System.out.println("The 2 images are the same: " + compareImages(historic.get(historicIndex-1), historic.get(historicIndex)));
}
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("DrawAndSaveImage");
frame.getContentPane().add(new FromGraphicsToBufferedImage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static BufferedImage getBufferedImage() {
return bImage;
}
public static boolean compareImages(BufferedImage imgA, BufferedImage imgB) {
if (imgA.getWidth() == imgB.getWidth() && imgA.getHeight() == imgB.getHeight()) {
int largeurImage = imgA.getWidth();
int hauteurImage = imgA.getHeight();
for (int y = 0; y < hauteurImage; y++) {
for (int x = 0; x < largeurImage; x++) {
if (imgA.getRGB(x, y) != imgB.getRGB(x, y)){
return false;
}
}
}
}
else {
return false;
}
return true;
}
static BufferedImage deepCopy(BufferedImage bi) {
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(null);
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Related
I have a problem using Graphics to put an image in a jPanel. I have the next code:
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
lienzo.paintComponents(imagenAbrir.getGraphics());
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Ocurriò un error al guardar la imàgen");
}
}
The code is part of a button, the user could select an imagen from any path, but it doesn't show anything in the panel. What could be the problem?
I think you have to change you method with BufferedImage object not a Graphics object
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
Then, if you want to draw image, create customized JPanel class on your own.
The paintCompoent method of JComponent will be invoked automatically, every time you call repaint method in your code.
final class ImagePane extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage myImage;
public ImagePane(final BufferedImage myImage) {
this.myImage = myImage;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(240, 220);
}
public void drawImage(BufferedImage img)
{
this.myImage = img;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myImage != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - myImage.getWidth()) / 2;
int y = (getHeight() - myImage.getHeight()) / 2;
g2d.drawImage(myImage, x, y, this);
g2d.dispose();
}
}
}
Here is full source code.
public class JFileChooserTest {
static Runnable doRun = new Runnable()
{
final class ChooseAction implements ActionListener
{
final ImagePane drawPan;
ChooseAction(final ImagePane drawPan)
{
this.drawPan = drawPan;
}
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
}
final class ImagePane extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage myImage;
public ImagePane(final BufferedImage myImage) {
this.myImage = myImage;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(240, 220);
}
public void drawImage(BufferedImage img)
{
this.myImage = img;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myImage != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - myImage.getWidth()) / 2;
int y = (getHeight() - myImage.getHeight()) / 2;
g2d.drawImage(myImage, x, y, this);
g2d.dispose();
}
}
}
#Override
public void run() {
final JFrame frame = new JFrame();
//frame.setSize(new Dimension(300,400));
JPanel lienzo = new JPanel();
lienzo.setLayout(new BorderLayout());
ImagePane drawPan = new ImagePane(null);
JButton drawMe = new JButton("draw me");
lienzo.add(drawMe, BorderLayout.NORTH);
lienzo.add(drawPan, BorderLayout.CENTER);
frame.add(lienzo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
drawMe.addActionListener(new ChooseAction(drawPan));
}
};
public static void main(String[] args)
{
SwingUtilities.invokeLater(doRun);
}
}
I hope this will help you.
The code is part of a button, the user could select an imagen from any path, but it doesn't show anything in the panel. What could be the problem?
Basically, this is not how custom painting works in Swing. Never call paintComponent or paintComponents yourself, it's not your responsibility.
What you want to do is paint the image to the component via its Graphics context
Take a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works and how you're suppose to use it
Then take a look at How to use lables for a simple solution for displaying images
You can also have a look at How to set a background picture in JPanel. It demonstrates using a JLabel and custom component for displaying an image
So, Do you want add image on the panel in which some base image is displayed?
If so, there is some trick to achieve to do this.
I prepare two images on the internet ( I am afraid these are licensed images )
Then, now i have three buttons put on your class
JButton drawMe = new JButton("draw me");
JButton pickMe = new JButton("pick me");
JButton clearMe = new JButton("clear me");
I decided to let the DrawAction class reuse with three action commands that are a draw, pick and clear together.
drawMe.addActionListener(drawAct);
drawMe.setActionCommand("draw");
pickMe.addActionListener(drawAct);
pickMe.setActionCommand("pick");
clearMe.addActionListener(drawAct);
clearMe.setActionCommand("clear");
We'll see the ImagePane class again. If you want to add a image on a image, you should have a paintcomponent method inherited from JComponent whatever components you want to use.
The 'draw me' button is to set the base image after clearing all images in the image list in which array list of the bufferedimage class.
public void drawImage(BufferedImage img)
{
if (imageList.size() > 0) imageList.clear();
imageList.add(img);
repaint();
}
The 'pick me' button is the method that add a image to the image list.
public void addImage(BufferedImage imagenAbrir) {
imageList.add(imagenAbrir);
repaint();
}
The last one is clear button, flush and clear all image buffers in the image list.
public void clearImage() {
imageList.clear();
isClear = true;
repaint();
}
Here is my trick to clear image on the panel, it is accomplished by re-drawing canvas(jPanel at this time) with some specific color(gray).
The main method, paintComponent as following..
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(isClear)
{
Graphics2D g2d = (Graphics2D) g.create();
Rectangle2D rectangle = new Rectangle2D.Double(0,0,getWidth(),getHeight());
g2d.setPaint(Color.GRAY);
g2d.fill(rectangle);
g2d.dispose();
isClear = false;
return;
}
if (imageList.size() > 0) {
BufferedImage img = null;
for(int i = 0; i < imageList.size(); i++)
{
img = imageList.get(i);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}
}
Finally, you read the code below how to handle action commands along with java's component,
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("draw"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurrio un error al guardar la imagen");
}
}
}
else if(e.getActionCommand().equals("pick"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.addImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurrio un error al guardar la imagen");
}
}
}
else if(e.getActionCommand().equals("clear"))
{
drawPan.clearImage();
}
}
As you see the code, picking a file is required every time you click both the pick or draw me button.
Full source code
package com.tobee.ui.test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JFileChooserTest {
static Runnable doRun = new Runnable()
{
final class DrawAction implements ActionListener
{
final ImagePane drawPan;
DrawAction(final ImagePane drawPan)
{
this.drawPan = drawPan;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
if(e.getActionCommand().equals("draw"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
else if(e.getActionCommand().equals("pick"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.addImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
else if(e.getActionCommand().equals("clear"))
{
drawPan.clearImage();
}
}
}
final class ImagePane extends JPanel {
private static final long serialVersionUID = 1L;
private boolean isClear;
private List<BufferedImage> imageList;
public ImagePane()
{
imageList = new ArrayList<BufferedImage>();
isClear = false;
}
public void clearImage() {
imageList.clear();
isClear = true;
repaint();
}
public void addImage(BufferedImage imagenAbrir) {
imageList.add(imagenAbrir);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(240, 220);
}
public void drawImage(BufferedImage img)
{
if (imageList.size() > 0) imageList.clear();
imageList.add(img);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(isClear)
{
Graphics2D g2d = (Graphics2D) g.create();
Rectangle2D rectangle = new Rectangle2D.Double(0,0,getWidth(),getHeight());
g2d.setPaint(Color.GRAY);
g2d.fill(rectangle);
g2d.dispose();
isClear = false;
return;
}
if (imageList.size() > 0) {
BufferedImage img = null;
for(int i = 0; i < imageList.size(); i++)
{
img = imageList.get(i);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}
}
}
#Override
public void run() {
final JFrame frame = new JFrame();
JPanel lienzo = new JPanel();
lienzo.setLayout(new BorderLayout());
JPanel optionPan = new JPanel();
ImagePane drawPan = new ImagePane();
JButton drawMe = new JButton("draw me");
JButton pickMe = new JButton("pick me");
JButton clearMe = new JButton("clear me");
DrawAction drawAct = new DrawAction(drawPan);
optionPan.add(drawMe);
optionPan.add(pickMe);
optionPan.add(clearMe);
lienzo.add(optionPan, BorderLayout.NORTH);
lienzo.add(drawPan, BorderLayout.CENTER);
frame.add(lienzo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
drawMe.addActionListener(drawAct);
drawMe.setActionCommand("draw");
pickMe.addActionListener(drawAct);
pickMe.setActionCommand("pick");
clearMe.addActionListener(drawAct);
clearMe.setActionCommand("clear");
}
};
public static void main(String[] args)
{
SwingUtilities.invokeLater(doRun);
}
}
Here is my code. I am drawing rectangle, oval, lines on the image. Drawing a line is working fine. I can draw the rectangle, but it is not visible on mouse drag. How to modify this program to show rectangle on mouse drag. How to provide eraser for this program to erase only the shapes while preserving the background image.
package com.sobis.hindalco.bean
import java.awt.*;
import java.awt.RenderingHints.Key;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
public class ImageEdit extends JFrame{
private BufferedImage originalImage;
private BufferedImage canvasImage;
private JPanel gui;
private Color color = Color.WHITE;
private JLabel output = new JLabel("You DooDoodle!");
BufferedImage image=null;
private BufferedImage colorSample = new BufferedImage(
16,16,BufferedImage.TYPE_INT_RGB);
private JLabel imageLabel;
private int activeTool;
public static final int RECTANGLE_TOOL = 0;
public static final int DRAW_TOOL = 1;
public static final int TEXT_TOOL = 2;
public static final int ERASER_TOOL = 3;
public static final int OVAL_TOOL = 4;
Point startDrag, endDrag;
private Point selectionStart;
private Rectangle selection;
private boolean dirty = false;
// private Stroke stroke = new BasicStroke(
// 3,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,1.7f);
private RenderingHints renderingHints;
public JComponent getGui() {
if(gui==null) {
Map<Key, Object> hintsMap = new
HashMap();
hintsMap.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
hintsMap.put(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_ENABLE);
hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
renderingHints = new RenderingHints(hintsMap);
setImage(new BufferedImage(320,240,BufferedImage.TYPE_INT_RGB));
gui = new JPanel(new BorderLayout(4,4));
gui.setBorder(new EmptyBorder(5,3,5,3));
JPanel imageView = new JPanel(new GridBagLayout());
imageView.setPreferredSize(new Dimension(480,320));
imageLabel = new JLabel(new ImageIcon(canvasImage));
JScrollPane imageScroll = new JScrollPane(imageView);
imageView.add(imageLabel);
imageLabel.addMouseMotionListener(new
ImageMouseMotionListener());
imageLabel.addMouseListener(new ImageMouseListener());
gui.add(imageScroll,BorderLayout.CENTER);
JToolBar tb = new JToolBar();
tb.setFloatable(false);
JButton colorButton = new JButton("Color");
colorButton.setMnemonic('o'); colorButton.setToolTipText("Choose a Color");
ActionListener colorListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Color c = JColorChooser.showDialog(
gui, "Choose a color", color);
if(c!=null) {
setColor(c);
}
}
};
colorButton.addActionListener(colorListener);
colorButton.setIcon(new ImageIcon(colorSample));
tb.add(colorButton);
setColor(color);
// final SpinnerNumberModel strokeModel =
// new SpinnerNumberModel(3,1,16,1);
/// JSpinner strokeSize = new JSpinner(strokeModel);
ChangeListener strokeListener = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
}
};
tb.addSeparator();
ActionListener clearListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.OK_OPTION;
if(dirty) {
result = JOptionPane.showConfirmDialog(
gui, "Erase the current painting?");
}
if(result==JOptionPane.OK_OPTION) {
clear(canvasImage);
}
}
};
JButton clearButton = new JButton("Clear");
tb.add(clearButton);
clearButton.addActionListener(clearListener);
gui.add(tb, BorderLayout.PAGE_START);
JToolBar tools = new JToolBar(JToolBar.VERTICAL);
tools.setFloatable(false);
JButton crop = new JButton("Crop");
final JRadioButton select = new JRadioButton("Rectangle", true);
final JRadioButton eraser = new JRadioButton("Eraser", true);
final JRadioButton draw = new JRadioButton("Draw");
final JRadioButton text = new JRadioButton("Text");
final JRadioButton oval = new JRadioButton("oval");
tools.add(select);
tools.add(draw);
tools.add(text);
tools.add(eraser);
tools.add(oval);
ButtonGroup bg = new ButtonGroup();
bg.add(select);
bg.add(text);
bg.add(draw);
bg.add(eraser);
bg.add(oval);
ActionListener toolGroupListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==select) {
activeTool = RECTANGLE_TOOL;
}else if(ae.getSource()==draw) {
activeTool = DRAW_TOOL;
}else if(ae.getSource()==text) {
activeTool = TEXT_TOOL;
}else if(ae.getSource()==eraser) {
activeTool = ERASER_TOOL;
}else if(ae.getSource()==oval) {
activeTool = OVAL_TOOL;
}
}
};
select.addActionListener(toolGroupListener);
draw.addActionListener(toolGroupListener);
text.addActionListener(toolGroupListener);
eraser.addActionListener(toolGroupListener);
oval.addActionListener(toolGroupListener);
gui.add(tools, BorderLayout.LINE_END);
gui.add(output,BorderLayout.PAGE_END);
clear(colorSample);
clear(canvasImage);
}
return gui;
}
/** Clears the entire image area by painting it with the current color. */
public void clear(BufferedImage bi) {
try{
image = ImageIO.read(new File("D:\\images.jpeg"));
}catch(Exception e){
}
this.originalImage = image;
int w = image.getWidth();
int h = image.getHeight();
canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.drawImage(image, 0, 0, gui);
g.dispose();
selection = new Rectangle(0,0,w,h);
if(this.imageLabel!=null) {
imageLabel.setIcon(new ImageIcon(canvasImage));
this.imageLabel.repaint();
}
if(gui!=null) {
gui.invalidate();
}
}
public void setImage(BufferedImage image1) {
try{
image = ImageIO.read(new File("D:\\images.jpeg"));
}catch(Exception e){
}
this.originalImage = image;
int w = image.getWidth();
int h = image.getHeight();
canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.drawImage(image, 0, 0, gui);
g.dispose();
selection = new Rectangle(0,0,w,h);
if(this.imageLabel!=null) {
imageLabel.setIcon(new ImageIcon(canvasImage));
this.imageLabel.repaint();
}
if(gui!=null) {
gui.invalidate();
}
}
/** Set the current painting color and refresh any elements needed. */
public void setColor(Color color) {
this.color = color;
clear(colorSample);
}
private JMenu getFileMenu(boolean webstart){
JMenu file = new JMenu("File");
file.setMnemonic('f');
//JMenuItem newImageItem = new JMenuItem("New");
//newImageItem.setMnemonic('n');
ActionListener newImage = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
BufferedImage bi = new BufferedImage(
360, 300, BufferedImage.TYPE_INT_ARGB);
clear(bi);
setImage(bi);
}
};
if(webstart) {
//TODO Add open/save functionality using JNLP API
}else{
//TODO Add save functionality using J2SE API
file.addSeparator();
ActionListener saveListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser ch = getFileChooser();
int result = ch.showSaveDialog(gui);
if(result==JFileChooser.APPROVE_OPTION ) {
try {
File f = ch.getSelectedFile();
ImageIO.write(ImageEdit.this.canvasImage, "png",
f); ImageEdit.this.originalImage =
ImageEdit.this.canvasImage;
dirty = false;
} catch (IOException ioe) {
showError(ioe);
ioe.printStackTrace();
}
}
}
};
JMenuItem saveItem = new JMenuItem("Save");
saveItem.addActionListener(saveListener);
saveItem.setMnemonic('s');
file.add(saveItem);
}
if(canExit()) {
ActionListener exit = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
};
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.addSeparator();
exitItem.addActionListener(exit);
file.add(exitItem);
}
return file;
}
private void showError(Throwable t) {
JOptionPane.showMessageDialog(
gui,
t.getMessage(),
t.toString(),
JOptionPane.ERROR_MESSAGE);
}
JFileChooser chooser = null;
public JFileChooser getFileChooser() {
if(chooser==null) {
chooser = new JFileChooser();
FileFilter ff= new FileNameExtensionFilter( "myfiles","jpg",
"jpeg","png");
chooser.addChoosableFileFilter(ff);
}
return chooser;
}
public boolean canExit() {
boolean canExit = false;
SecurityManager sm = System.getSecurityManager();
if(sm==null) {
canExit = true;
}else{
try {
sm.checkExit(0);
canExit = true;
} catch(Exception stayFalse) {
}
}
return canExit;
}
public JMenuBar getMenuBar(boolean webstart){
JMenuBar mb = new JMenuBar();
mb.add(this.getFileMenu(webstart));
return mb;
}
public void openPanel() {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// use default
}
ImageEdit bp = new ImageEdit();
JFrame f = new JFrame("Image Editing");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(bp.getGui());
f.setJMenuBar(bp.getMenuBar(false));
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
public void text(Point point) {
String text = JOptionPane.showInputDialog(gui, "Text to add",
"Text");
if(text!=null) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
// g.setStroke(stroke);
int n = 0;
g.drawString(text,point.x,point.y);
g.dispose();
this.imageLabel.repaint();
}
}
public void draw(Point point) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
int n = 0;
g.drawLine(point.x, point.y, point.x+n, point.y+n);
g.dispose();
this.imageLabel.repaint();
}
public void drawRectangle() {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
g.drawRect(Math.min(startDrag.x, endDrag.x), Math.min(
startDrag.y,endDrag.y), Math.abs(startDrag.x -endDrag.x),
Math.abs(startDrag.y - endDrag.y));
this.imageLabel.repaint();
}
public void eraser(Point point) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
int n = 0;
g.clearRect(point.x, point.y, point.x+n, point.y+n);
g.dispose();
this.imageLabel.repaint();
}
public void oval() {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
// g.setStroke(stroke);
int n = 0;
// g.clearRect(x1,y1,x2,y2);
g.dispose();
this.imageLabel.repaint();
}
class ImageMouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent arg0) {
if(activeTool==ImageEdit.TEXT_TOOL) {
// TODO
text(arg0.getPoint());
}else if(activeTool==ImageEdit.ERASER_TOOL) {
// TODO
eraser(arg0.getPoint());
}else if(activeTool==ImageEdit.ERASER_TOOL) {
// TODO
draw(arg0.getPoint());
}else{
startDrag = new Point(arg0.getX(), arg0.getY());
endDrag = startDrag;
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
if(activeTool==ImageEdit.RECTANGLE_TOOL) {
endDrag = new Point( arg0.getX(), arg0.getY());
drawRectangle();
}
}
}
class ImageMouseMotionListener implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent arg0) {
reportPositionAndColor(arg0);
endDrag = new Point( arg0.getX(), arg0.getY());
if(activeTool==ImageEdit.DRAW_TOOL) {
draw(arg0.getPoint());
}else if(activeTool==ImageEdit.RECTANGLE_TOOL) {
endDrag = new Point( arg0.getX(), arg0.getY());
}else if(activeTool==ImageEdit.OVAL_TOOL) {
oval();
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
reportPositionAndColor(arg0);
}
}
private void reportPositionAndColor(MouseEvent me) {
String text = "";
if(activeTool==ImageEdit.RECTANGLE_TOOL) {
text += "Selection (X,Y:WxH): " +
(int)selection.getX() +
"," +
(int)selection.getY() +
":" +
(int)selection.getWidth() +
"x" +
(int)selection.getHeight();
}else{
text += "X,Y: " + (me.getPoint().x+1) + "," +
(me.getPoint().y+1);
}
output.setText(text);
}
}
How to modify this program to show rectangle on mouse drag.
You can check out Custom Painting Approaches.
Both approaches draw a temporary Rectangle as you hold down the mouse and drag it. Basically you need to handle mousePressed to track the starting point, mouseDragged to get the current mouse point (and to a repaint()) and mouseReleased to save the actual Rectangle.
How to provide eraser for this program to erase only the shapes while preserving the background image.
You would probably want to use the Draw On Component approach from the above link. Then you would iterated through the List of shapes to determine if the mouse point is contained by the shape. If so, then you would remove the shapes from the List. So this will only permit erasure of entire shapes.
I am making a Java program which is able to draw a curve on JPanel on mouse events.
Now I want to ask after drawing that curve, how can I edit that curve?
This is my Java program:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.QuadCurve2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
public class MouseTestHovercraft extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final int MAX_CLR = 5;
private static final Color CURRENT_LIST_COLOR = new Color(190, 190, 255);
private List<Color> colors = new ArrayList<Color>();
private boolean tracking = false;
private List<Point> currentList = null;
private BufferedImage bufferedImage = new BufferedImage(PREF_W, PREF_H,
BufferedImage.TYPE_INT_ARGB);
private Random random = new Random();
This contructor is used to change the color of the curve as soon as mouse is released.
public MouseTestHovercraft() {
for (int redIndex = 0; redIndex < MAX_CLR; redIndex++) {
int r = (redIndex * 256) / (MAX_CLR - 1);
r = (r == 256) ? 255 : r;
for (int greenIndex = 0; greenIndex < MAX_CLR; greenIndex++) {
int g = (greenIndex * 256) / (MAX_CLR - 1);
g = (g == 256) ? 255 : g;
for (int blueIndex = 0; blueIndex < MAX_CLR; blueIndex++) {
int b = (blueIndex * 256) / (MAX_CLR - 1);
b = (b == 256) ? 255 : b;
Color c = new Color(r, g, b);
colors.add(c);
}
}
}
add(new JToggleButton(new AbstractAction("TrackMouse") {
public void actionPerformed(ActionEvent ae) {
trackMouse(ae);
}
}));
add(new JButton(new AbstractAction("Clear Image") {
public void actionPerformed(ActionEvent e) {
bufferedImage = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
repaint();
}
}));
MyMouseAdapter myMA = new MyMouseAdapter();
addMouseListener(myMA);
addMouseMotionListener(myMA);
}
This is used to listen the event of tracking button.
private void trackMouse(ActionEvent ae) {
JToggleButton toggleBtn = (JToggleButton) ae.getSource();
tracking = toggleBtn.isSelected();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void msg(String message) {
System.out.println(message);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bufferedImage, 0, 0, null);
if (currentList != null) {
drawList(g, currentList, CURRENT_LIST_COLOR, 1f);
}
}
This will draw a curve on jpanel using quadcurve
private void drawList(Graphics g, List<Point> ptList, Color color,
float strokeWidth) {
if (ptList.size() > 1) {
Graphics2D g2 = (Graphics2D) g.create();
// Graphics2D g2 = (Graphics2D) g;
g2.setColor(color);
// g2.setStroke(new BasicStroke(strokeWidth));
QuadCurve2D selectedCurve = null;
for (int j = 0; j < ptList.size() - 1; j++) {
int x1 = ptList.get(j).x;
int y1 = ptList.get(j).y;
int x2 = ptList.get(j + 1).x;
int y2 = ptList.get(j + 1).y;
selectedCurve =new QuadCurve2D.Float(x1, y1, 5, 5, x2,y2);
g2.draw(selectedCurve);
}
g2.dispose();
}
}
On mouse press this code will first add the starting point into currentlist list and after that till mouse released all the points are added into currentlist.
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
if (tracking && e.getButton() == MouseEvent.BUTTON1) {
currentList = new ArrayList<Point>();
currentList.add(e.getPoint());
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (tracking && e.getButton() == MouseEvent.BUTTON1) {
currentList.add(e.getPoint());
Graphics2D g2 = bufferedImage.createGraphics();
Color color = colors.get(random.nextInt(colors.size()));
drawList(g2, currentList, color, 3f);
currentList = null;
repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (tracking && currentList != null) {
currentList.add(e.getPoint());
repaint();
}
}
}
private static void createAndShowGui() {
MouseTestHovercraft mainPanel = new MouseTestHovercraft();
JFrame frame = new JFrame("MouseMotion Eg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I am using per-pixel transparency using AWTUtilities.setWindowOpaque() on JFrame, that contains JScrollPane. When transparency is on, the scrolling in that pane is very slow and laggy, without it is not. Trying this on Windows 7 and JDK 6.
public class MainFrame extends JFrame {
super();
setUndecorated(true);
AWTUtilities.setWindowOpaque(this, false); //this turns JScrollPane inside of this JFrame slow and laggy
}
Have anyone issued this? Thanks!
I can't see any scrolling issue, nor to create testing scenario for code that is based on good Swing rules, this code is quite too hard for processor(s) and GPU, Java6, Win7 64b
from code
import com.sun.awt.AWTUtilities;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.*;
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 GradientViewPortOriginal tableViewPort;
private static boolean loggerOpacity;
private JPanel panel = new JPanel();
private static JButton button;
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);
button = new JButton("Change Opacity for Java6 / Win7");
button.setBounds(100, 100, 50, 50);
button.setVisible(true);
panel.add(button);
loggerOpacity = true;
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == button && loggerOpacity) {
AWTUtilities.setWindowOpacity(frame, 0.80f);
}
}
});
frame.add(panel, BorderLayout.SOUTH);
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);
}
}
but I'm able to demonstrating lazy scrolling for JScrollPane contains others JComponents as is JTable or JList or JTextArea or JTextPane
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
public class ListPanel extends JFrame {
private static final long serialVersionUID = 1L;
public ListPanel() {
setLayout(new GridLayout(0, 2, 10, 10));
DefaultListModel model = new DefaultListModel();
model.addElement(createButtons("one"));
model.addElement(createButtons("two"));
model.addElement(createButtons("three"));
model.addElement(createButtons("four"));
model.addElement(createButtons("five"));
model.addElement(createButtons("six"));
model.addElement(createButtons("seven"));
model.addElement(createButtons("eight"));
model.addElement(createButtons("nine"));
model.addElement(createButtons("ten"));
model.addElement(createButtons("eleven"));
model.addElement(createButtons("twelwe"));
JList list = new JList(model);
list.setCellRenderer(new PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
add(scroll1);
JScrollPane scroll2 = new JScrollPane(createPanel());
add(scroll2);
final JScrollBar scrollBar1 = scroll2.getVerticalScrollBar();
scrollBar1.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar1.getValue());
}
});
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
panel.add(createButtons("one"));
panel.add(createButtons("two"));
panel.add(createButtons("three"));
panel.add(createButtons("four"));
panel.add(createButtons("five"));
panel.add(createButtons("six"));
panel.add(createButtons("seven"));
panel.add(createButtons("eight"));
panel.add(createButtons("nine"));
panel.add(createButtons("ten"));
panel.add(createButtons("eleven"));
panel.add(createButtons("twelwe"));
return panel;
}
public static JButton createButtons(String text) {
JButton button = new JButton(text);
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ListPanel frame = new ListPanel();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(270, 200);
frame.setVisible(true);
}
});
}
class PanelRenderer implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
}
How can I make the JButton visible?
1) When no progressive background is turned on: JButton is showing
2) When no progressive background is turned on, JButton is pressed still showing no flicker:
3) When progressive background is turned on, JButton is invisible and on pressing in this I see flicker and JButton() appears and again hides auto. << Problem is here, so how can I fix it?
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class ButtonTest extends JWindow implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private SoftJButton softButton1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonTest j = new ButtonTest();
j.createAndShowGUI();
}
});
}
public void createAndShowGUI() {
softButton1 = new SoftJButton("Transparent Button");
softButton1.setBackground(Color.GREEN);
softButton1.setAlpha(0.5f);
softButton1.setDoubleBuffered(true);
this.setLayout(new BorderLayout());
this.setBounds(100, 30, 200, 100);
this.setBackground(new Color(0, 0, 0, 255));
this.setVisible(true);
add(softButton1);
}
#Override
public void paint(Graphics g) {
super.paint(g);
}
public void mouseDragged(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static class SoftJButton extends JButton {
private static final JButton lafDeterminer = new JButton();
private static final long serialVersionUID = 1L;
private boolean rectangularLAF;
private float alpha = 1f;
public SoftJButton() {
this(null, null);
}
public SoftJButton(String text) {
this(text, null);
}
public SoftJButton(String text, Icon icon) {
super(text, icon);
setOpaque(false);
setFocusPainted(false);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
#Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
}
#Override
public void updateUI() {
super.updateUI();
lafDeterminer.updateUI();
rectangularLAF = lafDeterminer.isOpaque();
}
}
}
It's not clear how your video source works, but it appears to be incompatible with Swing due to Mixing Heavyweight and Lightweight Components. Although awt components aren't transparent, you can always draw your own translucent text on the Frame and do manual hit testing, as suggested below. You might also check to see if your video source API supports Double Buffering and Page Flipping.
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
/** #see http://stackoverflow.com/questions/6725618 */
public class AlphaFrame extends Frame {
private static final Font font = new Font("Dialog", Font.BOLD, 24);
private float alpha = 1f;
private Rectangle rect = new Rectangle();
public static void main(String[] args) {
AlphaFrame af = new AlphaFrame();
af.setTitle("Translucent Button");
af.setAlpha(0.5f);
af.setForeground(Color.green);
af.setBackground(Color.black);
af.setVisible(true);
}
public AlphaFrame() {
this.setSize(320, 240);
this.setLocationRelativeTo(null);
this.setBackground(Color.white);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (rect.contains(e.getPoint())) {
System.out.println("Pressed.");
}
}
});
repaint();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha));
g2.setColor(getForeground());
g2.setFont(font);
FontMetrics fm = g2.getFontMetrics();
String s = getTitle();
Insets i = getInsets();
int dx = i.left + 10;
int dy = i.top + fm.getHeight() + 10;
Rectangle2D bounds = fm.getStringBounds(s, g);
rect.x = dx + (int) bounds.getX() - 1;
rect.y = dy + (int) bounds.getY() - 1;
rect.width = (int) bounds.getWidth() + 1;
rect.height = (int) bounds.getHeight() + 1;
System.out.println(i + " \n" + bounds + "\n" + rect);
g2.drawRect(rect.x, rect.y, rect.width, rect.height);
g2.drawString(s, dx, dy);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
}
}
import java.awt.event.*;
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class ButtonTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private JFrame frame;
private SoftJButton softButton1;
public void createAndShowGUI() {
softButton1 = new SoftJButton("Transparent Button");
softButton1.setPreferredSize(new Dimension(800, 600));
frame = new JFrame();
frame.add(softButton1);
frame.setLocation(150, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Timer alphaChanger = new Timer(30, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(5500, new ActionListener() {
private LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
public static class SoftJButton extends JButton {
private static final JButton lafDeterminer = new JButton();
private static final long serialVersionUID = 1L;
private boolean rectangularLAF;
private float alpha = 1f;
public SoftJButton() {
this(null, null);
}
public SoftJButton(String text) {
this(text, null);
}
public SoftJButton(String text, Icon icon) {
super(text, icon);
setOpaque(false);
setFocusPainted(false);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
#Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
}
#Override
public void updateUI() {
super.updateUI();
lafDeterminer.updateUI();
rectangularLAF = lafDeterminer.isOpaque();
}
}
}