I'm trying to call GoogleCloudVision to get the image labels into an array. I don't know what to do for the ObjectLabel method which seems to be the problem. The program is meant to take an image file and run it through googles cloud vision and get an array of labels for the image, then based on the array determine what is the image.
this is the error I'm getting.
java.nio.file.NoSuchFileException: C:\Users\DELL Laptop\Downloads\Exam3Starter\src
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsDirectoryStream.<init>(WindowsDirectoryStream.java:86)
at java.base/sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream(WindowsFileSystemProvider.java:533)
at java.base/java.nio.file.Files.newDirectoryStream(Files.java:544)
at GoogleCloudVision.findJsonCredentialsFile(GoogleCloudVision.java:51)
at GoogleCloudVision.detectImageLabels(GoogleCloudVision.java:80)
at SeeFood.labelImage(SeeFood.java:57)
at SeeFood.main(SeeFood.java:83)
Code:
public static void labelImage(String filename) throws IOException, InterruptedException {
// TODO: replace with your implementation
String userFile = filename;
JFrame img = new JFrame();
ImageIcon icon = new ImageIcon(userFile);
JLabel label = new JLabel(icon);
img.add(label);
img.pack();
img.setVisible(true);
ArrayList<ObjectLabel> labels = GoogleCloudVision.detectImageLabels(userFile);
JOptionPane.showMessageDialog(null, labels);
} // end labelImage
public class ObjectLabel {
String Label = "";
float confidence = 2.0F;
public ObjectLabel(String description, float score) {
}
}
Related
I'm trying to get the image file path or file name of an ImageIcon. I've created a screen in my Java gui app, which contains properties for a custom JButton (extends JButton). From that screen I'm setting some of the main button properties, as if it is enabled, focusable and its ImageIcon. The problem is that as if now, whenever I use this button class, which is in every screen btw, I'm loading all possible images for ImageIcons when the exdened JButton class is used. That causes the screen to freeze before any of the components are shown, while the images are loaded from classpath. In order to change that, in the settings screen, where I hava a JComboBox, containing all images for icons, there, at least that's what I can think of, should be a way to get only the name of the chosen ImageIcon- image path.
The buttons properties are stored in a properties file and that's where I intend to store the .png images names if I can get to them. The idea is to set the image name and when the button is loaded to the screen to look for and load only the image it's supposed to.
Here is a snipet of the button class now; The images are way more, but for demo purposes, I think those are enough. I'd be very grateful if anyone can help with this matter.
public class CustomButton extends JButton {
static Properties FieldProp;
public CustomButton (String text, String name) {
FieldProp = new LoadProperties().loadMainProp();
this.setText(text);
this.setName(name);
Image imgdel=null;
Image imgsmbl=null;
Image imgsmrd=null;
Image imgsmgr=null;
Image imgadd=null;
Image imgauto=null;
Image imgauto1=null;
Image imgavail=null;
Image imgbarc=null;
Image imgdb=null;
Image imgdoc=null;
Image imgexc=null;
Image imgexc1=null;
try {
imgdel = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/delete.png")));
imgsmbl = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_blue.png")));
imgsmrd = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_red.png")));
imgsmgr = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_green.png")));
imgadd = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/add_plus.png")));
imgauto = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/automation.png")));
imgauto1 = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/automation1.png")));
imgavail = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/available.png")));
imgbarc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/barcode.png")));
imgdb = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/db.png")));
imgdoc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/doc.png")));
imgexc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/excel.png")));
imgexc1 = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/import.png")));
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
}catch (Exception e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
}
ImageIcon delIcon = new ImageIcon(imgdel);
ImageIcon blIcon = new ImageIcon(imgsmbl);
ImageIcon rdIcon = new ImageIcon(imgsmrd);
ImageIcon grIcon = new ImageIcon(imgsmgr);
ImageIcon addIcon = new ImageIcon(imgadd);
ImageIcon autoIcon = new ImageIcon(imgauto);
ImageIcon autoIcon1 = new ImageIcon(imgauto1);
ImageIcon availIcon = new ImageIcon(imgavail);
ImageIcon barcIcon = new ImageIcon(imgbarc);
ImageIcon dbIcon = new ImageIcon(imgdb);
ImageIcon docIcon = new ImageIcon(imgdoc);
ImageIcon excIcon = new ImageIcon(imgexc);
ImageIcon excIcon1 = new ImageIcon(imgexc1);
Object[] items =
{
noIcon,
delIcon,
blIcon,
rdIcon,
grIcon,
addIcon,
autoIcon,
autoIcon1,
availIcon,
barcIcon,
dbIcon,
docIcon,
excIcon,
excIcon1
};
try {
int iconPosition = Integer.parseInt(FieldProp.getProperty(this.getName() + "Icon"));
String iconProp = FieldProp.getProperty(this.getName() + "Icon");
if (!iconProp.equals("0")) {
this.setIcon((ImageIcon) items[iconPosition]);
}
}catch (Exception e){
e.printStackTrace();
}
try {
this.setEnabled((Boolean.parseBoolean(FieldProp.getProperty(this.getName() + "Enabled"))));
this.setFocusable((Boolean.parseBoolean(FieldProp.getProperty(this.getName() + "Focusable"))));
}catch(Exception e){}
I'm new to libGDX I've been trying to follow tutorials on how to create buttons and add textures to them however I am really struggling with it. How would I add textures to the continue and back buttons? I only have the png image and a .pack file for the textures
Also if anyone would be able to suggest some ways I can change the font of the labels I have for my buttons e.g. lbl_ip
Any help would be really appreciated.
public class MenuScreen implements Screen {
private Viewport viewport;
private Stage stage;
#SuppressWarnings("unused")
private MainGame game;
private Label lbl_ip;
private Label lbl_name;
private Label lbl_back;
private LabelStyle lbl_style;
private Skin txt_skin;
private TextButtonStyle btn_style;
private TextField txt_ip;
private TextField txt_name;
//private TextField txt_back;
private Button btn_confirm;
private Button btn_back;
public static String ip = "localhost"; // change with user input
public static String name = "Player 1";
public static String back = "<---";
public MenuScreen(MainGame game) {
this.game = game;
viewport = new FitViewport(MainGame.V_WIDTH/6, MainGame.V_HEIGHT/6, new OrthographicCamera());
stage = new Stage(viewport, ((MainGame) game).batch);
lbl_style = new Label.LabelStyle();
lbl_style.font = new BitmapFont();
txt_skin = new Skin(Gdx.files.internal("uiskin.json"));
btn_style = new TextButton.TextButtonStyle();
btn_style.font = new BitmapFont();
Table table = new Table();
table.top();
table.setFillParent(true);
lbl_ip = new Label("please enter an IP address:" , lbl_style);
lbl_name = new Label("enter your name: " , lbl_style);
lbl_back = new Label("Return to Main Menue", lbl_style);
txt_ip = new TextField(ip, txt_skin);
txt_name = new TextField(name, txt_skin);
//txt_back = new TextField(back, txt_skin);
btn_confirm = new TextButton("confirm", btn_style);
btn_back = new TextButton("<--", btn_style);
table.add(lbl_ip).expandX();
table.add(txt_ip).width(200);
table.row();
table.add(lbl_name).expandX();
table.add(txt_name).width(200);
table.row();
//table.add(lbl_back).expandX();
table.add(btn_back);
//table.add(txt_back).width(200);
table.row();
table.add(btn_confirm);
table.row();
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
private void buttonHandler() {
if(Gdx.input.isKeyPressed(Input.Keys.ENTER)) {
/*
game.setScreen(new PlayScreen(game));
*/
txt_ip.setTextFieldListener(new TextField.TextFieldListener() {
#Override
public void keyTyped(TextField textField, char c) {
ip = textField.getText();
}
});
txt_name.setTextFieldListener(new TextField.TextFieldListener() {
#Override
public void keyTyped(TextField textField, char c) {
name = textField.getText();
}
});
new MPClient(txt_ip.getText(), txt_name.getText(), game);
dispose();
}
}
#Override
public void show() {
// TODO Auto-generated method stub
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0 , 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw();
stage.act(delta);
buttonHandler();
}
#Override
public void dispose() {
stage.dispose();
}
}
You need to use ImageTextButton for that. You need to provide it with ImageTextButtonStyle, which is easy to create (you need to assign its imageUp property, other properties can be null).
As far as label font goes, you need to create a new LabelStyle and assign it a new BitmapFont. An example:
Label lab = new Label("This is the text", new LabelStyle(myFont, Color.RED));
"myfont" is a BitmapFont.
Here is a real-world example how to create a BitmapFont:
FreeTypeFontGenerator generator;
FreeTypeFontParameter parameter;
generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/nidsans-webfont.ttf"));
parameter = new FreeTypeFontParameter();
parameter.size = 12;
parameter.minFilter = TextureFilter.Linear;
parameter.magFilter = TextureFilter.Linear;
myfont = generator.generateFont(parameter);
You need to change the -style- associated with the widget. And you may want to make a new style per widget rather than sharing a style across all (because that would update all widgets with the new background)
LabelStyle newLabelStyle = new LabelStyle(originalLabel.getStyle());
tobeChangedLabel.setStyle(newLabelStyle);
newLabelStyle.background = new Image( //however you like to make the image
Changing the font is somewhat tricky... as the fonts are baked into the style as bitmaps (for rendering speed). You may find that given you don't like the background of your style, or even the font, that you might want to use a different skin. You can make your own or use one from here.
https://github.com/czyzby/gdx-skins
If you have to dynamically choose font you can dynamically build your bitmaps of rendered fonts with gdx-freetype-font-manager
https://jitpack.io/p/1nt3g3r/gdx-freetype-font-manager
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
I'm trying to display an SVG Image on my swing application,
since i don't have an SVG file but a path i'm converting the path to a valid svg document with:
private static Document buildSVGDocument(Color svgColor, /*double svgWidth, double svgHeight,*/ String svgPath) {
DOMImplementation svgDocumentImplementation = SVGDOMImplementation.getDOMImplementation();
Document svgDocument = svgDocumentImplementation.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null);
Element svgDocumentElement = svgDocument.getDocumentElement();
//svgDocumentElement.setAttribute("height", String.valueOf(svgHeight));
//svgDocumentElement.setAttribute("width", String.valueOf(svgWidth));
Element svgDocumentPath = svgDocument.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "path");
svgDocumentPath.setAttribute("style", String.format("fill:rgb(%s, %s, %s);", svgColor.getRed(), svgColor.getGreen(), svgColor.getBlue()));
svgDocumentPath.setAttribute("d", svgPath);
svgDocumentElement.appendChild(svgDocumentPath);
return svgDocument;
}
Then I display the SVG Document on a Batik Canvas:
JSVGCanvas panel = new JSVGCanvas();
panel.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
panel.setDisableInteractions(true);
panel.setDocument(buildSVGDocument(/*etc*/));
container.add(panel, BorderLayout.WEST);
Now my question is: how do I resize the svg to the panel size keeping the aspect-ratio?
I figured out how to do it!,
Browsing the source I found the method used to calculate the image scale, it's:
calculateViewingTransform
Then I've implemented a simple class to scale the image to the container
public class SVGCanvas extends JSVGCanvas {
private static final long serialVersionUID = 1L;
/**
* The type of scale
*/
private short svgScale;
/**
* Image padding
*/
private int svgPadding;
public SVGCanvas() {
this.svgScale = SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_XMIDYMAX;
this.svgPadding = 5;
}
#Override
protected AffineTransform calculateViewingTransform(String svgElementIdentifier, SVGSVGElement svgElement) {
SVGRect svgElementBounds = svgElement.getBBox();
float[] svgElementBoundsVector = new float[] {
svgElementBounds.getX(),
svgElementBounds.getY(),
svgElementBounds.getWidth(),
svgElementBounds.getHeight()
};
float svgEemenetScaleToHeight = getHeight() - svgPadding;
float svgElementScaleToWidth = getWidth() - svgPadding;
return ViewBox.getPreserveAspectRatioTransform(
svgElementBoundsVector, svgScale, true,
svgElementScaleToWidth,
svgEemenetScaleToHeight
);
}
public void setSvgScale(short svgScale) {
this.svgScale = svgScale;
}
public void setSvgPadding(int svgPadding) {
this.svgPadding = svgPadding;
}
}
I'm making a chessboard for a project and I have to use JButtons. I'm trying to just set the board up with a blank image I have for each tile, this is the code I have:
Driver
public class Driver
{
public static void main (String[] args)
{
new ChessBoard();
}
}
ChessSquare
import javax.swing.*;
import java.awt.*;
public class ChessSquare
{
public ImageIcon pieceImage;
/** The square's location */
private int xCoord;
private int yCoord;
/** Constructor for the squares */
public ChessSquare(ImageIcon thePieceImage, int theXCoord, int theYCoord)
{
pieceImage = thePieceImage;
xCoord = theXCoord;
yCoord = theYCoord;
}
public int getXCoord()
{
return xCoord;
}
public int getYCoord()
{
return yCoord;
}
}
ChessBoard
public class ChessBoard
{
public ChessBoard()
{
JFrame board = new JFrame();
board.setTitle("Chess Board!");
board.setSize(500,500);
board.setLayout(new GridLayout(8,8));
JPanel grid[][] = new JPanel[8][8];
ImageIcon empty = new ImageIcon("/pieces/EmptySquare.jpg");
for(int x = 0; x<8; x++)
{
for(int y = 0; y<8; y++)
{
ChessSquare s = new ChessSquare(empty, x, y);
JButton square = new JButton(s.pieceImage);
grid[x][y].add(square);
board.setContentPane(grid[x][y]);
}
}
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board.setVisible(true);
}
}
My code compiles fine but when I run it I get this error:
Exception in thread "main" java.lang.NullPointerException at
ChessBoard.(ChessBoard.java:23) at Driver.main(Driver.java:8)
I don't know what to do to fix this error. Thanks for any help :)
One of the likely causes is ImageIcon empty = new ImageIcon("/pieces/EmptySquare.jpg");...
The path of the image suggest that you are using embedded resources, but ImageIcon(String) treats the value as if it were a file, you can't do this with embedded resources, they aren't files.
Instead, you need to use something more like ImageIcon empty = new ImageIcon(getClass().getResource("/pieces/EmptySquare.jpg"));.
Personally, I'd recommend that you should be using ImageIO.read(getClass().getResource("/pieces/EmptySquare.jpg")) as this will throw an exception if the resource can not be loaded from some reason, rather then failing silently.
grid[x][y].add(square); also won't work, as you've not assigned anything to grid[x][y]
grid[x][y] = new JPanel();
grid[x][y].add(square);
Might work better, but I don't know why you're doing this, when doing something like...
JButton grid[][] = new JButton[8][8];
//...
grid[x][y] = square;
Would seem to be more logical for what you are trying to achieve...
Updated...
Instead of board.setContentPane(grid[x][y]); you should be using board.add(grid[x][y]);, other wise you will replace the content pane with the button...since there can only be a single content pane, you'll only get one button...
In grid[x][y].add(square); you are actually calling JPanel.add(), because each element in the array is a JPanel.
So the error is because grid[x][y] is still null you will get a NullPointerException if you call a method on it, like add() in this case.
You want to assign the value since you are using an array
grid[x][y] = square;