How to make a high quality screenshot? - java

I capture screenshots using the BufferedImage but when I get the picture it showed in a bad quality.
Here's my code:
Rectangle screenShot=new Rectangle(graphPanel.getX()+this.getX()+5,
graphPanel.getY()+this.getY()+navPanel.getHeight()+4,
graphPanel.getWidth(), graphPanel.getHeight());
BufferedImage capture=new Robot().createScreenCapture(screenShot);
ImageIO.write(capture, "jpg",new File("./PDFs/test"+"Graph"+".png"));

ImageIO.write(capture, "jpg",new File("./PDFs/test"+"Graph"+".png"));
Should be:
ImageIO.write(capture, "png",new File("./PDFs/test"+"Graph"+".png"));
Calling an image a PNG in the file extension won't make it a PNG. It also needs to be encoded as a PNG.
[I] did [change] it, but no result
What output do you get for this code? Here I get:
type: jpg Color difference: 926283 or 0.7852198282877604%.
type: png Color difference: 0 or 0.0%.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
import java.io.*;
import java.net.*;
public class ImageSave {
private JComponent ui = null;
public final static String[] types = {"jpg","png"};
private final JComboBox<String> typesBox = new JComboBox<>(types);
BufferedImage image;
BufferedImage imageCoded;
JLabel imageLabel = new JLabel();
JLabel imageCodedLabel = new JLabel();
JLabel output = new JLabel("Output appears here..");
ImageSave() {
try {
initUI();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public final void initUI() throws Exception {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
URL url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
image = ImageIO.read(url);
imageLabel.setIcon(new ImageIcon(image));
JPanel picsPanel = new JPanel(new GridLayout(1, 0, 4, 4));
ui.add(picsPanel);
picsPanel.add(imageLabel);
picsPanel.add(imageCodedLabel);
JToolBar toolBar = new JToolBar();
ui.add(toolBar, BorderLayout.PAGE_START);
toolBar.setLayout(new FlowLayout(FlowLayout.LEADING));
toolBar.add(typesBox);
ActionListener refreshListener = (ActionEvent e) -> {
try {
updateGUI();
} catch (Exception ex) {
ex.printStackTrace();
}
};
typesBox.addActionListener(refreshListener);
toolBar.add(output);
updateGUI();
}
private void updateGUI() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String type = typesBox.getSelectedItem().toString();
ImageIO.write(image, type, baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
imageCoded = ImageIO.read(bais);
imageCodedLabel.setIcon(new ImageIcon(imageCoded));
int diff = compareImages();
int max = image.getWidth()*image.getHeight()*256*3;
double percent = 100d*(double)diff/(double)max;
String s = "type: " + type + " Color difference: " + diff +
" or " + percent + "%.";
System.out.println(s);
output.setText(s);
}
private int compareImages() {
int diff = 0;
for (int xx=0; xx<image.getWidth(); xx++) {
for (int yy=0; yy<image.getHeight(); yy++) {
Color rgb1 = new Color(image.getRGB(xx, yy));
Color rgb2 = new Color(imageCoded.getRGB(xx, yy));
int r1 = rgb1.getRed();
int g1 = rgb1.getGreen();
int b1 = rgb1.getBlue();
int r2 = rgb2.getRed();
int g2 = rgb2.getGreen();
int b2 = rgb2.getBlue();
diff += Math.abs(r1-r2);
diff += Math.abs(g1-g2);
diff += Math.abs(b1-b2);
}
}
return diff;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ImageSave o = new ImageSave();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}

Related

Get the text in a JTextField

I have a swing application where the user inputs a number into two of the three fields, and my application does Pythagoras Theorem on those two numbers, and sets the answer field with the answer. However, the three fields (hypotenuse, short side 1, short side 2) are all returning 0 (shorter side 1 and shorter side 2 are different fields, forgot to add the : there), and 0 is the default value. This is not the case for other windows, this is only the case for the Maths tab. My question is, what is the problem?
Here is a screenshot of the error:
And here is the code:
Entry.java
package Entry;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuBar;
import Settings.SettingsLoader;
import Window.ErrorWindow;
import Window.SmallLinkWindow;
import Window.Window;
import Window.WindowEntry;
public class Entry {
public static JFrame frame;
public static File file;
public static JInternalFrame currentframe;
public static void main(String[] args){
file = new File("settings.txt");
frame = new JFrame("GUI_Base");
JMenuBar menu = new JMenuBar();
JMenuBar bottom = new JMenuBar();
SmallLinkWindow[] smallwindows = WindowEntry.getSmallWindows();
for(int i = 0; i < smallwindows.length; i++){
SmallLinkWindow window = smallwindows[i];
JButton button = window.getButton(); //ActionListener already added at this point.
button.addActionListener(getActionListener(window));
bottom.add(button);
}
List<String> data = readAllData();
SettingsLoader loader = new SettingsLoader(data);
loader.obtainSettings();
Window[] windows = WindowEntry.getAllWindows();
for(int i = 0; i < windows.length; i++){
Window window = windows[i];
JButton item = new JButton(window.getName());
item.addActionListener(getActionListener(window));
menu.add(item);
}
currentframe = windows[0].getInsideFrame();
menu.add(getRefresh(), BorderLayout.EAST);
frame.setSize(2000, 1000);
frame.add(menu, BorderLayout.NORTH);
frame.add(bottom, BorderLayout.SOUTH);
frame.getRootPane().setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("Loaded!");
}
private static JButton getRefresh() {
try {
BufferedImage image = ImageIO.read(new File("refresh.png"));
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
image = resizeImage(image, type, 25, 25);
ImageIcon icon = new ImageIcon(image);
JButton label = new JButton(icon);
label.addActionListener(getActionListener());
return label;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static ActionListener getActionListener() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
frame.repaint();
}
};
}
//Copied from http://www.mkyong.com/java/how-to-resize-an-image-in-java/
public static BufferedImage resizeImage(BufferedImage originalImage, int type, int width, int height){
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
private static ActionListener getActionListener(SmallLinkWindow window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static ActionListener getActionListener(Window window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static List<String> readAllData() {
try {
return Files.readAllLines(file.toPath());
} catch (IOException e) {
ErrorWindow.forException(e);
}
ErrorWindow.forException(new RuntimeException("Unable to read file!"));
System.exit(1);
return null;
}
}
MathWindow.java
package Window;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import Math.Pythagoras;
import Math.Trig;
import Math.TrigValue;
import Math.TrigonometryException;
import Settings.GUISetting;
public class MathWindow implements Window {
private Color colour;
private JSplitPane splitPane;
#Override
public String getName() {
return "Maths";
}
#Override
public JInternalFrame getInsideFrame() {
JInternalFrame frame = new JInternalFrame();
JSplitPane pane = new JSplitPane();
pane.setDividerLocation(300);
JPanel panel = new JPanel();
panel.setSize(300, 925);
JButton pyth = new JButton();
JButton trig = new JButton();
pyth.setText("Pythagoars theorem");
trig.setText("Trigonometry");
pyth.setSize(300, 200);
trig.setSize(300, 200);
pyth.addActionListener(getActionListenerForPythagoras());
trig.addActionListener(getActionListenerForTrignomotry());
panel.setLayout(new GridLayout(0,1));
panel.add(pyth);
panel.add(trig);
pane.setLeftComponent(panel);
splitPane = pane;
frame.getContentPane().add(pane);
return frame;
}
private ActionListener getActionListenerForPythagoras() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Small side 1");
bLabel.setText("Small side 2");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForPythagorasFinal(hypField.getText(), aField.getText(), bField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
protected ActionListener getActionListenerForPythagorasFinal(String hyp, String s1, String s2, JTextField field) {
return new ActionListener(){
private Pythagoras p = new Pythagoras();
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hypotenuse: " + hyp);
System.out.println("Shorter side 1" + s1);
System.out.println("Shorter side 2" + s2);
if(hyp.equals("0")){
double a = Double.parseDouble(s1);
double b = Double.parseDouble(s2);
if(a == 3 && b == 4 || a == 4 && b == 3) System.out.println("The result should be 5!");
field.setText(String.valueOf(p.getHypotenuse(a, b)));
}else if(s1.equals("0")){
double c = Double.parseDouble(hyp);
double b = Double.parseDouble(s2);
field.setText(String.valueOf(p.getShorterSide(b, c)));
}else if(s2.equals("0")){
double c = Double.parseDouble(hyp);
double a = Double.parseDouble(s1);
field.setText(String.valueOf(p.getShorterSide(a, c)));
}else throw new IllegalArgumentException("All of the fields have stuff in them!");
}
};
}
private ActionListener getActionListenerForTrignomotry(){
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JTextField anField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JLabel anLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Opposite");
bLabel.setText("Adjacent");
anLabel.setText("Angle size");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
anLabel.setSize(400, anLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
anField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
anField.setSize(400, anLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForTrigonomotryFinal(hypField.getText(), aField.getText(), bField.getText(), anField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(anLabel, BorderLayout.CENTER);
overseePanel.add(anField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
//a == opposite, b == adjacent
protected ActionListener getActionListenerForTrigonomotryFinal(String hyp,
String a, String b, String an, JTextField field) {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Trig trigonometry = new Trig();
double value = 0.000;
if(an == "0"){
if(hyp == "0"){
int shorta = Integer.parseInt(a);
int shortb = Integer.parseInt(b);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tA, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shortb = Integer.parseInt(b);
try {
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tH, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
value = trigonometry.getAngleSize(tA, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}else{
int angle = Integer.parseInt(an);
if(angle >= 90) throw new IllegalArgumentException("Angle is bigger than 90");
if(hyp.equals("0")){
if(a.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
value = trigonometry.getSideLength(tB, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
value = trigonometry.getSideLength(tA, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(a.equals("0")){
if(hyp.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tB, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(b.equals("0")){
if(hyp.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tA, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}
}
field.setText(String.valueOf(value));
}
};
}
#Override
public GUISetting[] getSettings() {
GUISetting setting = new GUISetting("Show working", "Maths");
GUISetting setting2 = new GUISetting("Round", "Maths");
return new GUISetting[]{setting, setting2};
}
#Override
public void setColour(Color c) {
colour = c;
}
#Override
public Color getCurrentColour() {
return colour;
}
}
If I need to add anything else please add a comment.
You create a new instance of JTextField, you then pass it's text property to the getActionListenerForPythagorasFinal method, so it no longer has what "will" be entered into the fields, only what it's initial value is (""), thus it's completely unable to perform the calculation on the fields in question
You could try passing the fields themselves to the method instead, but as a general piece of advice, I would create a custom class which contains the fields and associated actions which you can create whenever you need it, making significantly easier to manage and maintain

No output in JLabel when trying to retrieve blob image from JLabel

I am trying to retrieve a Blob(Image) file from database and want to show it in a JLabel . But it doesnt show up in JLabel . Why ? one More query if there any to know if my Byte array Contains valid data ? Here is my code
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ImageObserver;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Show extends JFrame {
private JPanel contentPane;
private JTextField id;
//BufferedImage bufImg = null;
JLabel img=null;
// InputStream in=null;
ImageIcon imgs=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Show frame = new Show();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection con=null;
public Show() {
con=dB.Connect();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 664, 499);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
id = new JTextField();
id.setBounds(158, 23, 86, 20);
contentPane.add(id);
id.setColumns(10);
JButton show = new JButton("New button");
show.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String q="select * from showme where id='"+id.getText()+"'";
PreparedStatement ps=con.prepareStatement(q);
ResultSet rs=ps.executeQuery();
InputStream in = rs.getBinaryStream("image");
ByteArrayOutputStream out = new ByteArrayOutputStream();
while(rs.next()){
byte[] buffer = new byte[1024];
int bytesRead = in.read(buffer);
while (bytesRead > -1)
{
out.write(buffer);
bytesRead = in.read(buffer);
}
byte[] picture = out.toByteArray();
ImageIcon mage = new ImageIcon(picture);
Image im = mage.getImage();
ImageIcon newImage = new ImageIcon(im);
//Image myImg = im.getScaledInstance(img.getWidth(),img.getWidth(),ImageObserver.WIDTH);
//ImageIcon newImage = new ImageIcon(myImg);
img.setIcon(newImage);
JOptionPane.showMessageDialog(null, "Done");
/*//I Also used this method . Still No Result in Jlabel
while(rs.next()){
byte[] imgss = rs.getBytes("image");
//Resize The ImageIcon
ImageIcon mage = new ImageIcon(imgss);
Image im = mage.getImage();
//Image myImg = im.getScaledInstance(imgss.length, imgss.length,imgss.length);
//ImageIcon newImage = new ImageIcon(im);
img.setIcon(new ImageIcon(im));
JOptionPane.showMessageDialog(null, "Done");
}
*/
in.close();
rs.close();
ps.close();
}
}catch(Exception c)
{
c.printStackTrace();
}
}
});
show.setBounds(302, 22, 89, 23);
contentPane.add(show);
img = new JLabel("");
img.setBounds(114, 54, 269, 171);
contentPane.add(img);
}
}
This is the code for inserting the image
import java.awt.EventQueue;
public class ImgC1 {
private JFrame frame;
private JLabel image;
private File images;
DataBufferByte data;
String s;
WritableRaster raster;
ImageIcon photo;
private static final int IMG_WIDTH = 120;
private static final int IMG_HEIGHT = 120;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImgC1 window = new ImgC1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ImgC1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
Connection con=null;
private JTextField id;
public ImageIcon ResizeImage(String imgPath){
ImageIcon MyImage = new ImageIcon(imgPath);
Image img = MyImage.getImage();
Image newImage = img.getScaledInstance(image.getWidth(), image.getHeight(),Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImage);
return image;
}
private static BufferedImage resizeImage(BufferedImage originalImage, int type) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
public Image toImage(BufferedImage bufferedImage) {
return Toolkit.getDefaultToolkit().createImage(bufferedImage.getSource());
}
private void initialize() {
con=dB.Connect();
frame = new JFrame();
frame.setBounds(100, 100, 643, 444);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton browse = new JButton("Browse");
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser chooser;
FileNameExtensionFilter filter;
chooser = new JFileChooser();
chooser.setCurrentDirectory(images);
filter = new FileNameExtensionFilter("jpeg, gif and png files", "jpg", "gif", "png");
chooser.addChoosableFileFilter(filter);
int i = chooser.showSaveDialog(null);
if (i == JFileChooser.APPROVE_OPTION) {
images = chooser.getSelectedFile();
image.setText(images.getAbsolutePath());
try {
BufferedImage originalImage = ImageIO.read(images);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
photo=new ImageIcon();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
photo = new ImageIcon(toImage(resizeImageJpg));
raster = resizeImageJpg.getRaster();
data = (DataBufferByte) raster.getDataBuffer();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
});
browse.setBounds(270, 282, 89, 23);
frame.getContentPane().add(browse);
JButton save = new JButton("Save");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
PreparedStatement ps = con.prepareStatement("insert into showme(id,image) values (?,?)");
//InputStream is = new FileInputStream(new File(s));
byte[] bt=data.getData();
ps.setString(1, id.getText());
ps.setBytes(2,bt);
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Inserted");
ps.close();
}catch(Exception c)
{
c.printStackTrace();
}
}
});
save.setBounds(270, 316, 89, 23);
frame.getContentPane().add(save);
image = new JLabel("New label");
image.setBounds(236, 141, 168, 130);
frame.getContentPane().add(image);
id = new JTextField();
id.setBounds(206, 60, 232, 23);
frame.getContentPane().add(id);
id.setColumns(10);
}
}

The Image size saved on the disk is different than what is being displayed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The code is being modified a bit . I added a button to the Jpanel whose action event save the image on the disk .
Source Code
package ImageResize;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.RenderedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
import java.io.*;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import java.util.Locale;
import javax.swing.filechooser.FileNameExtensionFilter;
class ImageCompressionDemo {
private BufferedImage originalImage;
private BufferedImage textImage;
private JPanel gui;
private JCheckBox antialiasing;
private
JCheckBox rendering;
private JCheckBox fractionalMetrics;
private JCheckBox strokeControl;
private JCheckBox colorRendering;
private JCheckBox dithering;
private JComboBox textAntialiasing;
private JComboBox textLcdContrast;
private JLabel jpegLabel;
private JLabel pngLabel;
private JTextArea output;
private JSlider quality;
private JButton saveButton;
private int pngSize;
private int jpgSize;
final static Object[] VALUES_TEXT_ANTIALIASING = {
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB
};
final static Object[] VALUES_TEXT_LCD_CONTRAST = {
new Integer(100),
new Integer(150),
new Integer(200),
new Integer(250)
};
ImageCompressionDemo(BufferedImage inputImage) {
int width = 280;
int height = 100;
gui = new JPanel(new BorderLayout(3,4));
gui.setPreferredSize(new Dimension(400, 600));
quality = new JSlider(JSlider.VERTICAL, 0, 100, 50);
quality.setSnapToTicks(true);
quality.setPaintTicks(true);
quality.setPaintLabels(true);
quality.setMajorTickSpacing(10);
quality.setMinorTickSpacing(1);
quality.addChangeListener( new ChangeListener(){
public void stateChanged(ChangeEvent ce) {
updateImages();
}
} );
gui.add(quality, BorderLayout.WEST);
originalImage = inputImage;
textImage =inputImage;
JPanel controls = new JPanel(new GridLayout(0,1,0,0));
antialiasing = new JCheckBox("Anti-aliasing", false);
rendering = new JCheckBox("Rendering - Quality", true);
fractionalMetrics = new JCheckBox("Fractional Metrics", true);
strokeControl = new JCheckBox("Stroke Control - Pure", false);
colorRendering = new JCheckBox("Color Rendering - Quality", true);
dithering = new JCheckBox("Dithering", false);
saveButton =new JButton("Save Image");
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
BufferedImage img = (BufferedImage)getJpegCompressedImage(originalImage);
File outputfile = new File("C:/Users/uday/Desktop/newImage.jpg");
ImageIO.write(img, "jpg", outputfile);
} catch (IOException ex) {
Logger.getLogger(ImageCompressionDemo.class.getName()).log(Level.SEVERE, null, ex);
}
} });
controls.add(antialiasing);
controls.add(fractionalMetrics);
textLcdContrast = new JComboBox(VALUES_TEXT_LCD_CONTRAST);
JPanel lcdContrastPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
lcdContrastPanel.add(textLcdContrast);
lcdContrastPanel.add(new JLabel("Text LCD Contrast"));
controls.add(lcdContrastPanel);
textAntialiasing = new JComboBox(VALUES_TEXT_ANTIALIASING);
controls.add(textAntialiasing);
controls.add(dithering);
controls.add(rendering);
controls.add(colorRendering);
controls.add(strokeControl);
ItemListener itemListener = new ItemListener(){
public void itemStateChanged(ItemEvent e) {
updateImages();
}
};
antialiasing.addItemListener(itemListener);
rendering.addItemListener(itemListener);
fractionalMetrics.addItemListener(itemListener);
strokeControl.addItemListener(itemListener);
colorRendering.addItemListener(itemListener);
dithering.addItemListener(itemListener);
textAntialiasing.addItemListener(itemListener);
textLcdContrast.addItemListener(itemListener);
Graphics2D g2d = originalImage.createGraphics();
gui.add(controls, BorderLayout.EAST);
gui.add(saveButton,BorderLayout.BEFORE_FIRST_LINE);
JPanel images = new JPanel(new GridLayout(0,1,2,2));
images.add(new JLabel(new ImageIcon(textImage)));
try {
pngLabel = new JLabel(new ImageIcon(getPngCompressedImage(textImage)));
images.add(pngLabel);
jpegLabel = new JLabel(new ImageIcon(getJpegCompressedImage(textImage)));
images.add(jpegLabel);
} catch(IOException ioe) {
}
gui.add(images, BorderLayout.CENTER);
output = new JTextArea(4,40);
output.setEditable(false);
gui.add(new JScrollPane(output), BorderLayout.SOUTH);
updateImages();
JOptionPane.showMessageDialog(null, gui);
}
private Image getPngCompressedImage(BufferedImage image) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageIO.write( image, "png", outStream );
pngSize = outStream.toByteArray().length;
BufferedImage compressedImage =
ImageIO.read(new ByteArrayInputStream(outStream.toByteArray()));
return compressedImage;
}
private Image getJpegCompressedImage(BufferedImage image) throws IOException {
float qualityFloat = (float)quality.getValue()/100f;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName( "jpg" ).next();
ImageOutputStream ioStream = ImageIO.createImageOutputStream( outStream );
imgWriter.setOutput( ioStream );
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam( Locale.getDefault() );
jpegParams.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
jpegParams.setCompressionQuality( qualityFloat );
imgWriter.write( null, new IIOImage( image, null, null ), jpegParams );
ioStream.flush();
ioStream.close();
imgWriter.dispose();
jpgSize = outStream.toByteArray().length;
BufferedImage compressedImage = ImageIO.read(new ByteArrayInputStream(outStream.toByteArray()));
return compressedImage;
}
private void updateText() {
StringBuilder builder = new StringBuilder();
builder.append("Fractional Metrics: \t");
builder.append( fractionalMetrics.isSelected() );
builder.append("\n");
builder.append( textAntialiasing.getSelectedItem() );
builder.append("\nPNG size: \t");
builder.append(pngSize);
builder.append(" bytes\n");
builder.append("JPG size: \t");
builder.append(jpgSize);
builder.append(" bytes \tquality: ");
builder.append(quality.getValue());
output.setText(builder.toString());
}
private void updateImages() {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
Graphics2D g2dText = textImage.createGraphics();
if (antialiasing.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
if (rendering.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_SPEED);
}
if (fractionalMetrics.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
}
if (strokeControl.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_NORMALIZE);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_PURE);
}
if (dithering.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_ENABLE);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_DISABLE);
}
if (colorRendering.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_SPEED);
}
g2dText.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST,
textLcdContrast.getSelectedItem());
g2dText.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
textAntialiasing.getSelectedItem());
g2dText.drawImage(originalImage, 0,0, null);
try {
jpegLabel.setIcon(new ImageIcon(getJpegCompressedImage(textImage)));
pngLabel.setIcon(new ImageIcon(getPngCompressedImage(textImage)));
} catch(IOException ioe) {
}
gui.repaint();
updateText();
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
try {
FileNameExtensionFilter filter = new FileNameExtensionFilter("Pictures","jpg","png");
JFileChooser fc = new JFileChooser();
fc.setFileFilter(filter);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String Path = file.getPath();
BufferedImage originalImage = ImageIO.read(new File(Path));
ImageCompressionDemo iwt = new ImageCompressionDemo(originalImage);
}
} catch (IOException ex) {
Logger.getLogger(ImageCompressionDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
} );
}
}
Here the Image size displayed in jpegLabel label variable is different from what is being saved on the disk . I want the size of the image saved on the disk to be of same size which is being displayed .
Reference to the Question : Need Java function that takes image and imagesize(in Kb) as input and return an image
The problem is here:
BufferedImage img = (BufferedImage)getJpegCompressedImage(originalImage);
File outputfile = new File("C:/Users/uday/Desktop/newImage.jpg");
ImageIO.write(img, "jpg", outputfile);
..when using the ImageIO class that way, it ignores whatever compression has been applied to the image and saves it using standard compression! The trick to saving the compressed image is to change the getJpegCompressedImage method to saveJpegCompressedImage, and instead of returning an Image it should declare void and save the byte[] directly to disk (using standard I/O).
E.G. as seen in this example:
Original image (unknown compression)
As seen in Example images for code and mark-up Q&As.
Saved as quality .2 (6,327 bytes)
Saved as quality .8 (18,702 bytes)
Code
import java.awt.Desktop;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Locale;
import javax.imageio.*;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
public class CompressImage {
/** TODO: This method has terrible handling of I/O.
Rewrite for production use. BNI. */
static public void saveJpegCompressedImage(
BufferedImage image,
float quality,
File file) throws Exception {
OutputStream outStream = new FileOutputStream(
new File(file, "Image-" + quality + ".jpg"));
ImageWriter imgWriter = ImageIO.
getImageWritersByFormatName("jpg").next();
ImageOutputStream ioStream =
ImageIO.createImageOutputStream(outStream);
imgWriter.setOutput(ioStream);
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(
Locale.getDefault());
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
imgWriter.write(null, new IIOImage(image, null, null), jpegParams);
ioStream.flush();
ioStream.close();
imgWriter.dispose();
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.stack.imgur.com/7bI1Y.jpg");
File f = new File(System.getProperty("user.home"));
BufferedImage bi = ImageIO.read(url);
for (float q = 0.2f; q < .9f; q += .2f) {
saveJpegCompressedImage(bi, q, f);
}
Desktop.getDesktop().open(f);
}
}

Keeping the correct style on text retrieval

I am making an application similar to a chat. For that purpose I have two JTextPanes, one where I'm writing and one that displays messages. This is the code that handles the transferring of text from input to display :
String input = textPane.getText();
if(!input.endsWith("\n")){
input+="\n";
}
StyledDocument doc = displayPane.getStyledDocument();
int offset = displayPane.getCaretPosition();
textPane.setText("");
try {
doc.insertString(offset, input, set);
} catch (BadLocationException ex) {
Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is that if i have colour on some words of the input text , the output is all coloured . So the colour is applied to all of the text when moved to display(while displayed correctly on input). Any suggestions on how i can move text properly?
Notice that same happens with other format as bold , italic etc
The text is already formatted on the input JTextPane . What i need to do
is transfer it as it is on a different JTextPane without having to check
the different style options
example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Fonts implements Runnable {
private String[] fnt;
private JFrame frm;
private JScrollPane jsp;
private JTextPane jta;
private int width = 450;
private int height = 300;
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private StyledDocument doc;
private MutableAttributeSet mas;
private int cp = 0;
private Highlighter.HighlightPainter cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
private Highlighter.HighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
private Highlighter.HighlightPainter whitePainter = new DefaultHighlighter.DefaultHighlightPainter(Color.white);
private int _count = 0;
private int _lenght = 0;
public Fonts() {
jta = new JTextPane();
doc = jta.getStyledDocument();
jsp = new JScrollPane(jta);
jsp.setPreferredSize(new Dimension(height, width));
frm = new JFrame("awesome");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(new BorderLayout());
frm.add(jsp, BorderLayout.CENTER);
frm.setLocation(100, 100);
frm.pack();
frm.setVisible(true);
jta.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
fnt = ge.getAvailableFontFamilyNames();
mas = jta.getInputAttributes();
new Thread(this).start();
}
#Override
public void run() {
for (int i = 0; i < fnt.length; i++) {
StyleConstants.setBold(mas, false);
StyleConstants.setItalic(mas, false);
StyleConstants.setFontFamily(mas, fnt[i]);
StyleConstants.setFontSize(mas, 16);
dis(fnt[i]);
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, true);
dis(fnt[i] + " Bold");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setItalic(mas, true);
dis(fnt[i] + " Bold & Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, false);
dis(fnt[i] + " Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
}
jta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void dis(String s) {
_count++;
_lenght = jta.getText().length();
try {
doc.insertString(cp, s, mas);
doc.insertString(cp, "\n", mas);
} catch (Exception bla_bla_bla_bla) {
bla_bla_bla_bla.printStackTrace();
}
if (_count % 2 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, cyanPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else if (_count % 3 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, redPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, whitePainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Fonts fs = new Fonts();
}
});
}
}
In the absence of a good SSCCE, I really don't know how you adding colour to the text on your JTextPane, but hopefully this method might sort things out for you :
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
private void appendToTextPane(String name, Color c, String f)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, f);
int len = Client.nPane.getDocument().getLength();
textPane.setCaretPosition(len);
textPane.setCharacterAttributes(aset, true);
textPane.replaceSelection(name);
}
With this you can give a different Color and Font to each String literal that will be added to your JTextPane.
Hope this new Code might help you in some way :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame
{
private JPanel topPanel;
private JPanel bottomPanel;
private JTextPane tPane1;
private JTextPane tPane2;
private JButton button;
public TextPaneTest()
{
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
bottomPanel = new JPanel();
bottomPanel.setBackground(Color.BLACK);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLUE);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
tPane1 = new JTextPane();
tPane1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
tPane1.setCharacterAttributes(aset, false); // Add these settings to the other JTextPane also
tPane2 = new JTextPane();
tPane2.setCharacterAttributes(aset, false); // Mimic what the other JTextPane has
button = new JButton("ADD TO THE TOP JTEXTPANE");
button.setBackground(Color.DARK_GRAY);
button.setForeground(Color.WHITE);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tPane1.setText(tPane2.getText());
}
});
add(topPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
topPanel.add(tPane1);
topPanel.add(tPane2);
bottomPanel.add(button);
pack();
tPane2.requestFocusInWindow();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextPaneTest();
}
});
}
}
Regards
This has been solved by merging the document models of the two panes. The solution is in this question: Keeping the format on text retrieval

Creating a selectable jpanel of jpanels containing images

After saving some images from a site into an ArrayList i am trying to create a jpanel which will display all these images in seperate jpanels with a scrollpane so that i can add action events to each. The user will then be able to select a jpanel with the relevant picture and click a "copy" button to save this image to the clipboard.
The following code works fine to add one picture:
picHolder = new JPanel();
picHolder.setSize(50,450);
picHolder.setBackground(Color.white);
Icon testicon = new ImageIcon(imageList.get(0));
JPanel test = new JPanel();
JLabel testLabel = new JLabel();
testLabel.setIcon(testicon);
test.add(testLabel);
picHolder.add(test);
however when i try to create panels within panels by using the following loop:
panelArray = new JPanel[imageList.size()];
labelArray = new JLabel[imageList.size()];
imageArray = new ImageIcon[imageList.size()];
for (int x=0; x>imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
panelArray[x] = new JPanel();
panelArray[x].setBackground(Color.red);
labelArray[x] = new JLabel();
labelArray[x].setIcon(imageArray[x]);
panelArray[x].setLayout(new FlowLayout());
panelArray[x].add(labelArray[x]);
picHolder.add(panelArray[x]);
picHolder.validate();
picHolder.repaint();
}
I get only a blank screen. I have tried moving various elements around however i cannot see what i am doing wrong. If anyone has any suggestions or perhaps an alternative way of achieving my objective it would be greatly appreciated.
Edit
SSCCE
package scrollbartester;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.select.Selector;
import java.net.*;
import javax.imageio.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.Event;
import javax.swing.*;
public class ScrollBarTester {
ArrayList<Image> imageList = new ArrayList<Image>() ;
URL url;
public ArrayList ripPics() {
String fullST = "http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords=fish&x=0&y=0";
try {
Document doc = Jsoup.connect(fullST).timeout(10*1000).get();
Elements jpgs = doc.select("img[src$=.jpg]");
Element pictest = jpgs.get((jpgs.size()-1));
System.out.println(pictest);
for (int countPics = 0; countPics < jpgs.size(); countPics++) {
Element currentPic = jpgs.get(countPics);
String currentPicString = currentPic.toString();
System.out.println(currentPicString);
int startofAddress = currentPicString.indexOf("http:");
int endofAddress = (currentPicString.indexOf(".jpg") + 4);
String urlOfImage = currentPicString.substring(startofAddress, endofAddress);
url = new URL(urlOfImage);
Image currentImage = ImageIO.read(url);
imageList.add(currentImage);
}
}catch (MalformedURLException e) {
} catch (Exception e) {
e.printStackTrace();
}
return imageList;
}
public static void main(String[] args) {
PicRipper ripper = new PicRipper();
ArrayList<Image> imageList = ripper.ripPics();
System.out.println(imageList.size());
JScrollPane scrollPane;
JFrame main = new JFrame();
main.setSize(50, 500);
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
JPanel picHolder = new JPanel();
picHolder.setSize(450,450);
picHolder.setBackground(Color.white);
//Icon testicon = new ImageIcon(imageList.get(0));
//JPanel test = new JPanel();
//JLabel testLabel = new JLabel();
//testLabel.setIcon(testicon);
//test.add(testLabel);
//picHolder.add(test);
JPanel [] panelArray = new JPanel[imageList.size()];
JLabel [] labelArray = new JLabel[imageList.size()];
ImageIcon [] imageArray = new ImageIcon[imageList.size()];
for (int x=0; x>imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
panelArray[x] = new JPanel();
panelArray[x].setBackground(Color.red);
labelArray[x] = new JLabel();
labelArray[x].setIcon(imageArray[x]);
panelArray[x].setLayout(new FlowLayout());
panelArray[x].add(labelArray[x]);
picHolder.add(panelArray[x]);
picHolder.validate();
picHolder.repaint();
}
scrollPane = new JScrollPane(picHolder);
main.getContentPane().add(BorderLayout.CENTER, scrollPane);
main.setVisible(true);
}
}
For example a SSCCE that uses a JList -- which can hold ImageIcons:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class PicStrip extends JPanel {
public static final String[] IMAGE_URLS = {
"http://upload.wikimedia.org/wikipedia/commons/6/63/Lagavulin_-_entrance.JPG",
"http://upload.wikimedia.org/wikipedia/commons/1/1d/Parliament-Ottawa_edit1.jpg",
"http://upload.wikimedia.org/wikipedia/commons/b/b0/100OLYMP1.jpg",
"http://upload.wikimedia.org/wikipedia/commons/1/17/Arpino_panorama.jpg",
"http://upload.wikimedia.org/wikipedia/commons/a/ad/Cegonha_alsaciana.jpg",
"http://upload.wikimedia.org/wikipedia/commons/1/18/Eau_transparente_naturelle.JPG",
"http://upload.wikimedia.org/wikipedia/commons/4/4d/FA-18F_Breaking_SoundBarrier.jpg",
"http://upload.wikimedia.org/wikipedia/commons/5/58/PuntadelEste.jpg",
"http://upload.wikimedia.org/wikipedia/commons/3/3c/Punta_Gorda_Belize-gm.jpg",
"http://upload.wikimedia.org/wikipedia/commons/6/64/Yungangshiku.JPG",
"http://upload.wikimedia.org/wikipedia/commons/e/e2/Wheel_of_Konark%2C_Orissa%2C_India.JPG",
"http://upload.wikimedia.org/wikipedia/commons/1/16/Muretto_a_secco.jpg",
"http://upload.wikimedia.org/wikipedia/commons/3/31/Mercedes_AMG_CLS_55_-_Demonstration_of_drifting_1a_1280x960.jpg",
"http://upload.wikimedia.org/wikipedia/commons/d/d3/Cascade_carieul_1280x960.jpg",
"http://upload.wikimedia.org/wikipedia/commons/1/17/Bobbahn_ep.jpg"
};
private ImageIcon[] icons = new ImageIcon[IMAGE_URLS.length];
private DefaultListModel iconListModel = new DefaultListModel();
private JList iconList = new JList(iconListModel);
private ImagePanel imagePanel = new ImagePanel();
public PicStrip() {
setLayout(new BorderLayout());
add(new JScrollPane(iconList), BorderLayout.LINE_START);
add(imagePanel, BorderLayout.CENTER);
new SwingWorker<Void, ImageIcon>() {
#Override
protected Void doInBackground() throws Exception {
for (String imageUrl : IMAGE_URLS) {
BufferedImage img = ImageIO.read(new URL(imageUrl));
img = ImageUtil.createScaledImage(img);
ImageIcon icon = new ImageIcon(img, imageUrl);
publish(icon);
}
return null;
}
protected void process(java.util.List<ImageIcon> chunks) {
for (ImageIcon icon : chunks) {
iconListModel.addElement(icon);
}
};
protected void done() {
Window win = SwingUtilities.getWindowAncestor(PicStrip.this);
win.pack();
};
}.execute();
iconList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
iconList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
ImageIcon icon = (ImageIcon)iconList.getSelectedValue();
final String imageUrl = icon.getDescription();
new SwingWorker<BufferedImage, Void>() {
protected BufferedImage doInBackground() throws Exception {
return ImageIO.read(new URL(imageUrl));
};
#Override
protected void done() {
try {
imagePanel.setImage(get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}.execute();
}
});
}
private static void createAndShowGui() {
PicStrip mainPanel = new PicStrip();
JFrame frame = new JFrame("PicStrip");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class ImagePanel extends JPanel {
private static final int PREF_W = (3 * 1280) / 4;
private static final int PREF_H = (3 * 960) / 4;
private BufferedImage img = null;
public void setImage(BufferedImage img) {
this.img = img;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img == null) {
return;
}
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, PREF_W, PREF_H, null);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
}
class ImageUtil {
public static final int DEST_WIDTH = 100;
public static final int DEST_HEIGHT = 75;
public static final double ASPECT_RATIO = (double) DEST_WIDTH / DEST_HEIGHT;
public static BufferedImage createScaledImage(BufferedImage original) {
double origAspectRatio = (double) original.getWidth()
/ original.getHeight();
double scale = origAspectRatio > ASPECT_RATIO ?
(double) DEST_WIDTH / original.getWidth() :
(double) DEST_HEIGHT / original.getHeight();
int newW = (int) (original.getWidth() * scale);
int newH = (int) (original.getHeight() * scale);
BufferedImage img = new BufferedImage(DEST_WIDTH, DEST_HEIGHT,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(original, 0, 0, newW, newH, null);
g2.dispose();
return img;
}
}
Edit 1
I've checked your SSCCE -- thanks for posting it, and one problem I found was a faulty for-loop. Try changing this:
for (int x = 0; x > imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
//....
}
to this:
for (int x = 0; x < imageList.size(); x++) {
imageArray[x] = new ImageIcon(imageList.get(x));
//....
}
I'm not sure if this is a bug in your actual program or if it's just a bug in the SSCCE, but it is critical.

Categories