I am quite new to Java and started learning on YouTube. To practice GUI Programs, I decided to make my own and am now trying to resize an image to add to a button in my aplication. I searched how to resize images and found some source code online which I decided to test and put in my own program, but when I call the method I get an unreported exception java.io.IOException; must be caught or declared to be thrown error and the IntelliJ IDE says Unhandled exception: java.io.IOException. I have the try-catch blocks in my code, but this still comes up. How can I fix this? Here is some of my code:
Images.java (class with the resizer method I found online) the try-catch I put in myself.
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Images {
//Image resizer method for scaling images
void resizeImage(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight) throws IOException {
//reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
//creates output image
BufferedImage outputImage = new BufferedImagee(scaledWidth, scaledHeight, inputImage.getType());
//scales the inputImage to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1);
//writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
try {
inputFile = null;
inputImage = ImageIO.read(inputFile);
}
catch(IOException e){
e.printStackTrace();
System.out.println("image file path is null");
}
}
}
GUI.java (where the error appears when I try to call the method). The error appears at plus.resizeImage.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.company.Images;
public class GUI extends JFrame {
//This will be used for dimensions of the window
private int height, width;
GUI(int w, int h) {
super("OS Control");
setWidth(w);
setHeight(h);
setSize(getWidth(), getHeight());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setContent();
setVisible(true);
}
//Gets and sets for height and width of window
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public void setWidth(int width) {
this.width = width;
}
public int getWidth() {
return width;
}
////////////////////////////////////////////////
/*Method with the actual contents of the aplication
i.e buttons, text fields, etc.
*/
void setContent() {
//variables used in the methods for ease of changing if needed
int buttonWidth, buttonHeight;
int searchBarWidth, searchBarHeight;
buttonWidth = 200;
buttonHeight = 100;
searchBarWidth = 350;
searchBarHeight = 25;
//Panel for the two center buttons
JPanel buttons = new JPanel();
//flow layout to center horizontally
buttons.setLayout(new FlowLayout());
buttons.setBackground(Color.decode("#9E9E9E"));
JButton mechanicButton = new JButton("Mecanicos");
mechanicButton.setPreferredSize(new Dimension(buttonWidth, buttonHeight));
mechanicButton.setFocusable(false);
mechanicButton.addActionListener(new MechanicButtonEventHandling());
buttons.add(mechanicButton);
JButton osButton = new JButton("Ordens de Servico");
osButton.setPreferredSize(new Dimension(buttonWidth, buttonHeight));
osButton.setFocusable(false);
osButton.addActionListener(new OSButtonEventHandling());
buttons.add(osButton);
JPanel center = new JPanel();
//gridbag layout to center vertically
center.setLayout(new GridBagLayout());
center.setBackground(Color.decode("#9E9E9E"));
//combine the two to center horizontally and vertically
center.add(buttons);
JPanel search = new JPanel();
search.setLayout(new FlowLayout());
search.setBackground(Color.decode("#9E9E9E"));
search.setSize(new Dimension(getWidth(), searchBarHeight));
JTextField searchBar = new JTextField("Pesquisar: ");
searchBar.setPreferredSize(new Dimension(searchBarWidth, searchBarHeight));
searchBar.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 10));
search.add(searchBar);
JPanel plusPanel = new JPanel();
plusPanel.setLayout(new BorderLayout());
plusPanel.setSize(new Dimension(10, 10));
Images plus = new Images();
plus.resizeImage("plus.png","plusButton.png", 10, 10);
ImageIcon plusButtonImage = new ImageIcon("plusButton.png");
JButton plusButton = new JButton(plusButtonImage);
plusButton.setSize(new Dimension(10, 10));
plusPanel.add(plusButton, BorderLayout.SOUTH);
//add to jframe
add(search);
add(center);
add(plusPanel);
}
private class MechanicButtonEventHandling implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame mechanicList = new JFrame("Lista de Mecanicos");
mechanicList.setSize(getWidth(), getHeight());
mechanicList.setLocation(100, 100);
mechanicList.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
mechanicList.setVisible(true);
}
}
private class OSButtonEventHandling implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame osList = new JFrame("Lista de ordens de servico");
osList.setSize(getWidth(), getHeight());
osList.setLocation(700, 100);
osList.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
osList.setVisible(true);
}
}
}
You need to have a better look at how Java handles exceptions.
Your Images#resizeImage method contains a few operations that throw an IOException this being, the ImageIO#read and ImageIO#write calls.
At the bottom of the method's body you do this:
try {
inputFile = null;
inputImage = ImageIO.read(inputFile);
} catch(IOException e){
e.printStackTrace();
System.out.println("image file path is null");
}
In this code bit you're handling the thrown IOException with a try-catch clause. The
same cannot be said though for these calls:
BufferedImage inputImage = ImageIO.read(inputFile);
ImageIO.write(outputImage, formatName, new File(outputImagePath));
Since both of these thrown an exception which is not handled within the method's scope (i.e with a try-catch clause), you're forcing the method's signature to have a throws declaration for the IOException thrown by these two. Since, IOException is a checked exception, the compiler expects to find a try-catch clause wrapping the call to Images#resizeImage method.
To fix your code you have two possible solutions:
Remove the try-catch clause from the method's body, leaving only the throws declaration forcing callers to handle the exception at the calling point.
Wrap almost all of the method's body or the places where an IOException is thrown in try-catch clauses, thus handling the exception within the method's body (not a good idea since this way you'll not know whether the act of resizing failed or not).
It seems that your understanding of how exceptions work and how you need to handle them is a bit limited, so before doing anything else I would suggest to take a small detour and check on them.
https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
Related
After extensive googling I've found that this issue is generally case-specific. I've tried many of the solutions found and none of them have worked for me, so I felt it was appropriate to create a post on it.
I'm using setJMenuBar and the bar is never appearing, here is my code:
NOTE: I believe the cause is that I update the frame, however the solution is still unknown.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
#SuppressWarnings("serial")
public class testclass extends JFrame {
public int updateRate = 60;
public int screenWidth;
public int screenHeight;
public boolean finishedInitialPaint;
private Graphics bufferGraphics;
private BufferStrategy bufferStrategy;
public int gridSize = 10;
JMenuBar engineBar;
JMenu fileMenu, editMenu, createMenu, toolsMenu, panelsMenu;
JMenuItem fileNewScene, fileOpenScene, fileSaveScene, fileExit;
JMenuItem editPreferences, editEngine;
JMenuItem createEmpty, createStandard;
JMenuItem toolsDebug;
JMenuItem panelView2D, panelEditor2D, panelHierarchy, panelInspector, panelExplorer;
public static void main(String[] args) {
testclass testClassv = new testclass ();
}
public testclass () {
Start ();
while(true) {
Update ();
ClearBackBuffer ();
try {
Thread.sleep(1000 / updateRate);
} catch (InterruptedException e) {
}
}
}
private void Start () {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = screenSize.width;
screenHeight = screenSize.height;
CreateDefaultEngineMenu ();
setTitle("Test Window");
setSize(Math.round(screenWidth * 0.99f), Math.round(screenHeight * 0.9f));
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void CreateDefaultEngineMenu () {
engineBar = new JMenuBar ();
/*
* Building initial menus
*/
// Build the file menu
fileMenu = new JMenu("File");
engineBar.add(fileMenu);
// Build the edit menu
editMenu = new JMenu("Edit");
engineBar.add(editMenu);
// Build the create menu
createMenu = new JMenu("Create");
engineBar.add(createMenu);
// Build the tools menu
toolsMenu = new JMenu("Tools");
engineBar.add(toolsMenu);
// Build the panels menu
panelsMenu = new JMenu("Panels");
engineBar.add(panelsMenu);
/*
* Building menu options
*/
// File menu options
fileNewScene = new JMenuItem("New Scene");
fileMenu.add(fileNewScene);
fileOpenScene = new JMenuItem("Open Scene");
fileMenu.add(fileOpenScene);
fileSaveScene = new JMenuItem("Save Scene");
fileMenu.add(fileSaveScene);
fileExit = new JMenuItem("Exit");
fileMenu.add(fileExit);
// Edit menu options
editPreferences = new JMenuItem ("Preferences");
editMenu.add(editPreferences);
editEngine = new JMenuItem ("Engine Settings");
editMenu.add(editEngine);
// Create menu options
createEmpty = new JMenuItem("New Empty GameObject");
createMenu.add(createEmpty);
createStandard = new JMenuItem("Standard GameObjects");
createMenu.add(createStandard);
// Tools menu options
toolsDebug = new JMenuItem ("Debug");
toolsMenu.add(toolsDebug);
// Panels menu options
panelView2D = new JMenuItem("View 2D");
panelsMenu.add(panelView2D);
panelEditor2D = new JMenuItem("Editor 2D");
panelsMenu.add(panelEditor2D);
panelHierarchy = new JMenuItem("Hierarchy");
panelsMenu.add(panelHierarchy);
panelInspector = new JMenuItem("Inspector");
panelsMenu.add(panelInspector);
panelExplorer = new JMenuItem("Explorer");
panelsMenu.add(panelExplorer);
// Set the frame to use the bar
setJMenuBar(engineBar);
}
private void Update () {
//sceneObjects.activeObjects.get(0).transform.position.x += 0.1f;
initialize ();
ClearBackBuffer ();
repaint ();
DrawBackBufferToScreen ();
}
private void initialize () {
if(bufferStrategy == null) {
this.createBufferStrategy(2);
bufferStrategy = this.getBufferStrategy();
bufferGraphics = bufferStrategy.getDrawGraphics();
}
}
public void paint(Graphics g) {
// Something to go here
}
private void ClearBackBuffer () {
bufferGraphics = bufferStrategy.getDrawGraphics();
try {
bufferGraphics.clearRect(0, 0, this.getSize().width, this.getSize().height);
Graphics2D g2d = (Graphics2D)bufferGraphics;
paint2D(g2d);
} catch (Exception e) {
//Debug.EngineLogError("Engine", "Failed to clear rect for frame buffer (Failed to draw frame) - Exception");
} finally {
bufferGraphics.dispose();
}
}
private void DrawBackBufferToScreen () {
bufferStrategy.show();
Toolkit.getDefaultToolkit().sync();
}
private void paint2D (Graphics2D g2d) {
// Multi-Used Variables
int canvasWidth = Math.round(screenWidth / 2);
int canvasHeight = Math.round(screenHeight / 2);
// Draw panel borders
// View2D
g2d.setColor(Color.black);
g2d.drawRect((canvasWidth) - (canvasWidth / 2) - 1, canvasHeight - (Math.round(canvasHeight / 1.35f)) - 1, canvasWidth + 1, canvasHeight + 1);
}
}
Any and all relevant answers are greatly appreciated.
EDIT: Fixed code to be able to be tested raw
There's a lot wrong in your code, but the biggest problem is here:
public void paint(Graphics g) {
// Something to go here
}
By overriding paint, you're preventing the JFrame from doing its necessary painting of itself, its borders, and relevant to your problem, its child components. So your menu never draws!
You should never draw directly in the JFrame, but if you absolutely must (and you don't), at least call the super's painting method:
public void paint(Graphics g) {
super.paint(g);
// Something to go here
}
Better still-- never override paint but instead draw inside a JPanel's paintComponent method (still calling the super's paintComponent method within) and display that JPanel within your JFrame.
Key links:
Lesson: Performing Custom Painting: introductory tutorial to Swing graphics
Painting in AWT and Swing: advanced tutorial on Swing graphics
I'm not sure what the rest of your code is trying to do, but you've got big threading issues, other painting issues,... do read the tutorials to avoid guessing. Also you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
Hi I am creating a news ticker/ text scroller.
I am using the following method:
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Scroll1 extends JPanel{
private int x;
private int x2;
private int y;
private String text;
final int startX=-100;
public Scroll1(int startX)
{
x2=-650;
x = 20;
y=150;
text= "Some Words and others, and now this must be a longer text that takes up the whole panel/ frame for this test to work ";
}
#Override
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0, 0, 400, 300);
g.setColor(Color.black);
g.drawString(text, x, y);
g.drawString(text, x2, y);
FontMetrics fm= g.getFontMetrics();
System.out.println(fm.stringWidth(text));;
}
public void start() throws InterruptedException{
while(true){
while(x<= 650){
x++;
x2++;
y = getHeight()/2;
repaint();
Thread.sleep(10);
if(x2>650)
x2=-650;
}
if(x>=0)
{
x=-650;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Scrolling Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Scroll1 scrolling = new Scroll1(-100);
frame.getContentPane().add(scrolling);
frame.setSize(400, 300);
frame.setVisible(true);
try {
scrolling.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Basically it has two strings that are being drawn. One starts at the 0 position and the other starts at -650. I got the -650 number by using the font metrics inside of the paint method. The problem is that I had to hard code that number, and if I did a different string that has different metrics, it would not work. I tried making a instance variable called width that stores the font metrics, but it seems that the width is not inputted until the paint method is called. Is there anyway I can get the metrics before it starts drawing it?
Is there anyway I can get the metrics before it starts drawing it?
Just initialize the variable in the first call to paint (or better yet, paintComponent - see below) - you can do this using a boolean flag, or initialize it's value to an extreme and do a check on the value.
int x = Integer.MIN_VALUE;
...
protected void paintComponent(Graphics g){
super.paintComponent(g);
if ( x == Integer.MIN_VALUE ){
x = -g.getFontMetrics().stringWidth(text);
}
...
}
Some other tips:
Use a Swing Timer to perform animation, or be sure to dispatch Swing specific calls to the EDT using SwingUtilities.
Don't override paint, rather override paintComponent (and be sure to call the parent method super.paintComponent(g))
I am trying to design a chat UI with Swing, but I am too dumb to figure out how to do proper indentation for the message portion.
Here's an example of what I'm after:
Here's what I just hacked together (just copy-and-paste it):
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class Scrap {
private static final int NICK_INDENT = 120;
private static final int MESSAGE_INDENT = NICK_INDENT + 10;
private static boolean applyHangingIndent = false;
public static void main(final String args[]) {
StyledDocument doc = new DefaultStyledDocument();
JTextPane pane = new JTextPane(doc) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawLine(NICK_INDENT + 5, 0, NICK_INDENT + 5, getHeight());
}
};
TabStop[] tabs = new TabStop[2];
tabs[0] = new TabStop(NICK_INDENT, TabStop.ALIGN_RIGHT, TabStop.LEAD_NONE);
tabs[1] = new TabStop(MESSAGE_INDENT, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
TabSet tabset = new TabSet(tabs);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset);
pane.setParagraphAttributes(aset, false);
insertString(doc, "\ta nickname:\tthis is the message blaa blaa blaa\n");
if (applyHangingIndent) {
applyHangingIndent(doc);
}
insertString(doc, "\tanother nickname:\there is another message blaa blaa blaablaa, try to resize the window\n");
if (applyHangingIndent) {
applyHangingIndent(doc);
}
insertString(doc, "\ta third nickname:\tnow try to set the applyHangingIndent to true!\n");
if (applyHangingIndent) {
applyHangingIndent(doc);
}
JFrame frame = new JFrame();
frame.setContentPane(new JScrollPane(pane));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void insertString(StyledDocument doc, String str) {
try {
doc.insertString(doc.getLength(), str, null);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
private static void applyHangingIndent(StyledDocument doc) {
SimpleAttributeSet sas = new SimpleAttributeSet();
int indent = MESSAGE_INDENT;
StyleConstants.setFirstLineIndent(sas, -indent);
StyleConstants.setLeftIndent(sas, indent);
doc.setParagraphAttributes(0, doc.getLength(), sas, false);
}
}
Try to resize the window to a smaller size.
Now, try to set the applyHangingIndent to true and resize again.
To my mind the code should be OK, however the negative first line indent property does not seem to work with tabstops.
Anyone have ideas how to make the indentation work properly?
I would recommend another approach - tables based.
See the example http://java-sl.com/JEditorPaneTables.html and this http://java-sl.com/JEditorPaneTablesRowColumnInsert.html
You can define a table with 2 columns and as many rows as you need (for each message).
The first cell contains nickname and the second contains message. You can align content of cells (normal paragraphs in fact) as you wish. Also you can define any desired borders to be rendered or not for the columns/rows.
I encountered a problem while I am trying to display an image after I clicked a button and chose image file within the "Choose File Dialog".
Initially, I was managed to display the chosen image in JLabel, but later I created a separate ActionListener, I think it started to go wrong since then. Whatever image I choose, the JLabel won't display it.
I debugged it, and sure that the file chooser does pass the image to ImageIcon, JLabel does get the value from ImageIcon, but it doesn't display the image even after revalidate() and repaint().
Here I attached my code for your kind reference!
(I trimmed the code for a clean look, so there might be some brackets left not useful)
package com.xxx.LoyalCardManager;
import java.awt.EventQueue;
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.sql.SQLException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
public class LoyalCardManagerMain implements ActionListener{
private JFrame frame;
private DatabaseHandler db = new DatabaseHandler();
private JLabel labelPic;
private JButton buttonPic;
private File picFile = new File("");
private BufferedImage image;
/**
* Launch the application.
* #throws SQLException
* #throws ClassNotFoundException
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoyalCardManagerMain window = new LoyalCardManagerMain();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
/**
* Create the application.
*/
public LoyalCardManagerMain() {
// Database initialisation
initDatabase();
// Draw GUI
frame = new JFrame();
frame.setBounds(100, 100, 619, 487);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
buttonPic = new JButton("Click to Choose Pic");
buttonPic.setBounds(415, 252, 166, 29);
frame.getContentPane().add(buttonPic);
buttonPic.setEnabled(false);
buttonPic.setActionCommand("ChoosePic");
buttonPic.addActionListener(this);
labelPic = new JLabel();
labelPic.setBounds(415, 30, 167, 210);
frame.getContentPane().add(labelPic);
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("ChoosePic")) {
//TODO Label now cannot display images.
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(new FileFilter() {
public boolean accept (File f) {
String extension = Utils.getExtension(f);
if(extension != null) {
if (extension.equals(Utils.gif) ||
extension.equals(Utils.jpeg) ||
extension.equals(Utils.jpg) ||
extension.equals(Utils.png) ||
extension.equals(Utils.tif) ||
extension.equals(Utils.tiff)) {
return true;
}else{
return false;
}
}
return false;
}
public String getDescription() {
return "Image File (*.gif, *.jpeg, *.jpg, *.png, *.tif, *.tiff)";
}
});
int retVal = chooser.showOpenDialog(frame);
if (retVal == JFileChooser.APPROVE_OPTION) {
picFile = chooser.getSelectedFile();
try {
image = ImageIO.read(picFile);
} catch (IOException e) {
e.printStackTrace();
}
// Calculate the pic's ratio and do re-scale
double ratio = (double) labelPic.getWidth() / (double) labelPic.getHeight();
// Do image scale, scaledW is the new Width, and LabelPic.getHeight is the new Height.
int scaledW = (int) (image.getHeight() * ratio);
image = new BufferedImage(scaledW, labelPic.getHeight(), BufferedImage.SCALE_FAST);
ImageIcon icon = new ImageIcon(image);
labelPic.setVisible(true);
labelPic.setIcon(icon);
labelPic.revalidate();
labelPic.repaint();
}
}
}
}
I also referenced other similar questions:
image loading using a JFileChooser into a JFrame
Image won't display in JLabel
Updating an image contained in a JLabel - problems
External Site: JFIleChooser opening image to JLabel
As well as Java Tutorial Docs
How to Use Buttons, Check Boxes, and Radio Buttons
But I still can't figure it out why the JLabel not display the chosen image.
Thanks for your kind help mates!
Ok, I finally figured out what's wrong with the code:
If I intend to use BufferedImage to resize (sorry, in my question I mis-understanding the method scale with resize), I need to use drawImage method to "redraw" the image. Otherwise the image will not be shown.
I made modification here:
double ratio = (double) labelPic.getWidth() / (double) labelPic.getHeight();
// Do image scale, scaledW is the new Width, and LabelPic.getHeight is the new Height.
int scaledW = (int) (image.getHeight() * ratio);
image = new BufferedImage(scaledW, labelPic.getHeight(), BufferedImage.SCALE_FAST);// Edit here
ImageIcon icon = new ImageIcon(image);
labelPic.setVisible(true);
labelPic.setIcon(icon);
labelPic.revalidate();
labelPic.repaint();
From the "Edit Here" mark, I use the following code:
BufferedImage imageTemp = new BufferedImage(resizedW, resizedH, BufferedImage.TYPE_INT_RGB);
imageTemp.getGraphics().drawImage(image,0,0, scaledW, scaledH, null);
image = imageTemp;
And there's difference between first pass the value to imageTemp then pass to image and directly pass the value to image. If I pass the new BufferedImage directly to image, it will display a pure black colour instead of the image you choose.
Try using this to display the image:
JfileChooser getImage = new JFileChooser();
..........
ImageIcon imagePath= new ImageIcon(getImage.getPath());
JLabel imageLabel= new JLabel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imagePath.getImage(), 0, 0, width, height, null);
}
};
imageLabel.setLocation(10, 40);
imageLabel.setBorder(viewAnimalPanelBorder);
imageLabel.setSize(200, newHeight);
panel.add(imageLabel);
Let me know if you require more assistance.
Also, try displaying the picture without using the JFileChooser, maybe hard code the path for a test.
Is there a way for me to get the X and Y values of a window in java? I read that I'll have to use runtime, since java can't mess directly, however I am not so sure of how to do this. Can anyone point me some links/tips on how to get this?
To get the x and y position of "any other unrelated application" you're going to have to query the OS and that means likely using either JNI, JNA or some other scripting utility such as AutoIt (if Windows). I recommend either JNA or the scripting utility since both are much easier to use than JNI (in my limited experience), but to use them you'll need to download some code and integrate it with your Java application.
EDIT 1
I'm no JNA expert, but I do fiddle around with it some, and this is what I got to get the window coordinates for some named window:
import java.util.Arrays;
import com.sun.jna.*;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.*;
public class GetWindowRect {
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
W32APIOptions.DEFAULT_OPTIONS);
HWND FindWindow(String lpClassName, String lpWindowName);
int GetWindowRect(HWND handle, int[] rect);
}
public static int[] getRect(String windowName) throws WindowNotFoundException,
GetWindowRectException {
HWND hwnd = User32.INSTANCE.FindWindow(null, windowName);
if (hwnd == null) {
throw new WindowNotFoundException("", windowName);
}
int[] rect = {0, 0, 0, 0};
int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
if (result == 0) {
throw new GetWindowRectException(windowName);
}
return rect;
}
#SuppressWarnings("serial")
public static class WindowNotFoundException extends Exception {
public WindowNotFoundException(String className, String windowName) {
super(String.format("Window null for className: %s; windowName: %s",
className, windowName));
}
}
#SuppressWarnings("serial")
public static class GetWindowRectException extends Exception {
public GetWindowRectException(String windowName) {
super("Window Rect not found for " + windowName);
}
}
public static void main(String[] args) {
String windowName = "Document - WordPad";
int[] rect;
try {
rect = GetWindowRect.getRect(windowName);
System.out.printf("The corner locations for the window \"%s\" are %s",
windowName, Arrays.toString(rect));
} catch (GetWindowRect.WindowNotFoundException e) {
e.printStackTrace();
} catch (GetWindowRect.GetWindowRectException e) {
e.printStackTrace();
}
}
}
Of course for this to work, the JNA libraries would need to be downloaded and placed on the Java classpath or in your IDE's build path.
This is easy to do with the help of the end user. Just get them to click on a point in a screen shot.
E.G.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
/** Getting a point of interest on the screen.
Requires the MotivatedEndUser API - sold separately. */
class GetScreenPoint {
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
final Dimension screenSize = Toolkit.getDefaultToolkit().
getScreenSize();
final BufferedImage screen = robot.createScreenCapture(
new Rectangle(screenSize));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel screenLabel = new JLabel(new ImageIcon(screen));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension(
(int)(screenSize.getWidth()/2),
(int)(screenSize.getHeight()/2)));
final Point pointOfInterest = new Point();
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel pointLabel = new JLabel(
"Click on any point in the screen shot!");
panel.add(pointLabel, BorderLayout.SOUTH);
screenLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
pointOfInterest.setLocation(me.getPoint());
pointLabel.setText(
"Point: " +
pointOfInterest.getX() +
"x" +
pointOfInterest.getY());
}
});
JOptionPane.showMessageDialog(null, panel);
System.out.println("Point of interest: " + pointOfInterest);
}
});
}
}
Typical output
Point of interest: java.awt.Point[x=342,y=43]
Press any key to continue . . .
A little late to the party here but will add this to potentially save others a little time. If you are using a more recent version of JNA then WindowUtils.getAllWindows() will make this much easier to accomplish.
I am using the most recent stable versions as of this post from the following maven locations:
JNA Platform - net.java.dev.jna:jna-platform:5.2.0
JNA Core - net.java.dev.jna:jna:5.2.0
Java 8 Lambda (Edit: rect is a placeholder and will need to be final or effectively final to work in a lambda)
//Find IntelliJ IDEA Window
//import java.awt.Rectangle;
final Rectangle rect = new Rectangle(0, 0, 0, 0); //needs to be final or effectively final for lambda
WindowUtils.getAllWindows(true).forEach(desktopWindow -> {
if (desktopWindow.getTitle().contains("IDEA")) {
rect.setRect(desktopWindow.getLocAndSize());
}
});
Other Java
//Find IntelliJ IDEA Window
Rectangle rect = null;
for (DesktopWindow desktopWindow : WindowUtils.getAllWindows(true)) {
if (desktopWindow.getTitle().contains("IDEA")) {
rect = desktopWindow.getLocAndSize();
}
}
Then within a JPanel you can draw a captured image to fit (Will stretch image if different aspect ratios).
//import java.awt.Robot;
g2d.drawImage(new Robot().createScreenCapture(rect), 0, 0, getWidth(), getHeight(), this);