Running a jar file that has an image - java

I'm trying to run a jar file but have got 2 problems:
I can only run it from cmd and not by double clicking on it - Have exported it as a runnable jar file from Eclipse and I've installed java runtime enviroment. When I double click on it nothing happens
The image I've imported in eclipse isn't exported the project
The jar file has to ask for a username/password and then open an image but it can't.
Code:
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class OpenImage {
public static void main(String[] args){
String un;
int pass;
Image image = null;
System.out.println("Welcome, please enter the username and password to open the image");
Scanner scan = new Scanner(System.in);
System.out.println("Username?:");
un = scan.nextLine();
System.out.println("Password?:");
pass = scan.nextInt();
if(un.equals("Hudhud") && pass==123){
System.out.println("");
System.out.println("Here you got the picture");
try{
File sourceimage = new File("index.jpg");
image = ImageIO.read(sourceimage);
}
catch (IOException e){
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setSize(300, 300);
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.setVisible(true);
}
else{
System.out.println("You ain't the boss");
}
}
}
This is my project:
http://www.filedropper.com/capture

Why do you want to create a new ImageIcon from an existing one? KISS!
Furthermore no try/catch is required by Class.getResource.
So:
import java.net.URL;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class OpenImage {
private static final String IMG_FILE_PATH = "index.jpg";
private static final String USERNAME = "Hudhud";
private static final int PASSWORD = 123;
public static void main(String[] args){
String un;
int pass;
System.out.println("Welcome, please enter the username and password to open the image");
Scanner scan = new Scanner(System.in);
System.out.println("Username?:");
un = scan.nextLine();
System.out.println("Password?:");
pass = scan.nextInt();
if(un.equals(USERNAME) && pass==PASSWORD){
System.out.println();
System.out.println("Here you got the picture");
URL url = OpenImage.class.getResource(IMG_FILE_PATH);
ImageIcon icon = new ImageIcon(url);
JFrame frame = new JFrame();
frame.setSize(300, 300);
JLabel label = new JLabel(icon);
frame.add(label);
frame.setVisible(true);
}
else{
System.out.println("You ain't the boss");
}
}
}

Related

Block input while JDialog is open

I've a program that, when I open an image with JDialog, the consoles freezes, as expected, but if I write on the console while frozen, the scanner will catch what I typed, after I close the image, the scanner will give me what I typed earlier. I tried to reset the scanner but it didn't work.
Here's an example:
import java.util.Scanner;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Program
{
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
File file = new File("example.png");
try{
BufferedImage img = ImageIO.read(file);
ImageIcon icon=new ImageIcon(img);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
JFrame frame=new JFrame();
JDialog jdialog = new JDialog(frame, name, true);
jdialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
jdialog.setSize(img.getWidth(), img.getHeight());
jdialog.setModal(true);
jdialog.add(lbl);
jdialog.setVisible(true);
}
catch (IOException e){
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
e.printStackTrace();
}
System.out.print("Type something: ");
String line = stdin.nextLine();
System.out.println("You typed "+line+", right?");
}
}
What I wanted to do:
(Show image)
User type: hello
(User closes image)
Type something:
User type: bye
You typed bye, right?
What happens:
(Show image)
User type: hello
(User closes image)
Type something: hello
You typed hello, right?

Arrayindex out of bound exception in java with loginform

This program uses a user input file( users.txt) and gets the username and password. If the user enters the form with the correct username and password, it should display login successful.
For some reason when i test the program with users.txt, I am getting an Arrayindex out of bound exception.
LoginFrame.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package emptyframeviewer;
/**
*
* #author ACER
*/
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/*Business P11.26 Write a program with a graphical interface that implements a login window with text
fields for the user name and password. When the login is successful, hide the login
window and open a new window with a welcome message. Follow these rules for
validating the password:
1. The user name is not case sensitive.
2. The password is case sensitive.
3. The user has three opportunities to enter valid credentials.
Otherwise, display an error message and terminate the program. When the program
starts, read the file users.txt . Each line in that file contains a username and password,
separated by a space. You should make a users.txt file for testing your program.
Business P11.27 In Exercise P11.26, the password is shown as it is typed. Browse the Swing documentation
to find an appropriate component for entering a password. Improve the
solution of Exercise P11.26 by using this component instead of a text field. Each
time the user types a letter, show a ■ character.*/
#SuppressWarnings("serial")
public class LoginFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private HashMap<String, String> usernamesAndPasswords;
private JTextField usernameField;
private JTextField passwordField;
private JButton loginButton;
private JPanel loginPanel;
private JPanel welcomePanel;
private JPanel mainPanel;
private CardLayout cardLayout;
public LoginFrame() {
this.createComponents();
super.setTitle("Login Panel");
super.setSize(FRAME_WIDTH, FRAME_HEIGHT);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setVisible(true);
}
private void createComponents() {
this.mainPanel = new JPanel(new CardLayout());
this.createHashMap();
this.loginPanel = this.createLoginPanel();
this.welcomePanel = this.createWelcomePanel();
this.mainPanel.add(this.loginPanel, "LoginPanel");
this.mainPanel.add(this.welcomePanel, "WelcomePanel");
this.cardLayout = (CardLayout) this.mainPanel.getLayout();
this.cardLayout.show(this.mainPanel, "LoginPanel");
super.add(this.mainPanel);
}
private JPanel createLoginPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2));
this.loginButton = new JButton("Login");
final int TEXT_FIELD_SIZE = 10;
this.usernameField = new JTextField(TEXT_FIELD_SIZE);
this.passwordField = new JPasswordField(TEXT_FIELD_SIZE);
this.loginButton.addActionListener(new ActionListener() {
private int loginAttempts = 3;
#Override
public void actionPerformed(ActionEvent arg0) {
boolean loggedIn = false;
String inputUsername = usernameField.getText().toLowerCase();
String inputPassword = passwordField.getText();
if (this.loginAttempts == 1) {
JOptionPane.showMessageDialog(null, "Number of login attemtps exceeded. Exitting...");
System.exit(1);
}
for (Map.Entry<String, String> validUser : usernamesAndPasswords.entrySet()) {
if (inputUsername.equals(validUser.getKey().toLowerCase())) {
if (inputPassword.equals(validUser.getValue())) {
System.out.println("Login successful!");
cardLayout.show(mainPanel, "WelcomePanel");
loggedIn = true;
}
}
}
if (!loggedIn) {
this.loginAttempts -= 1;
String message = String.format("Invalid username/password. %d %s remaining", this.loginAttempts,
(this.loginAttempts > 1) ? "attempts" : "attempt");
JOptionPane.showMessageDialog(null, message, "LOGIN FAILED", JOptionPane.INFORMATION_MESSAGE);
}
}
});
panel.add(new JLabel("Username"));
panel.add(this.usernameField);
panel.add(new JLabel("Password"));
panel.add(this.passwordField);
panel.add(this.loginButton);
return panel;
}
private JPanel createWelcomePanel() {
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(new JLabel("Welcome"));
panel.add(new JButton("Change password"));
JButton logoutBtn = new JButton("Logout");
logoutBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
panel.add(logoutBtn);
return panel;
}
private void createHashMap() {
this.usernamesAndPasswords = new HashMap<String, String>();
try {
Scanner fileScanner = new Scanner(new File("usersff.txt"));
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split(" ");
this.usernamesAndPasswords.put(line[0], line[1]);
System.out.println(line[0] + " " + line[1]);
}
fileScanner.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null,
"Error: no users.txt file found. No users/passwords available to read.", "USERS.TXT NOT FOUND!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame testFrame = new LoginFrame();
}
}
test file: users.txt
John 234 Peter abc
If that is the only content in the file, please check the end of file for new line. You may also add small check.
Based on the only noticeable Array in the snippet
String[] line = fileScanner.nextLine().split(" ");
if(line.length == 2)
{
this.usernamesAndPasswords.put(line[0], line[1]);
System.out.println(line[0] + " " + line[1]);
}
There are many possibilities...

How to use a Java program while running in background

I am writing a program to capture a screenshot of the screen when I press a particular button on my keyboard. The problem that I have is that the program won't take my screenshot if its in the background. The screenshot will only capture if my program is in the foreground.
I'm using the robot class to capture and save the screenshot. I have my program below...
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.AWTException;
import java.awt.DefaultKeyboardFocusManager;
import java.awt.KeyEventDispatcher;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
public class FullScreenCaptureExample{
private static int num = 1;
public static void main(String[] args) throws AWTException{
final File file = new File("C:\\screenshots");
final Robot rbt = new Robot();
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setBounds(100, 100, 190, 73);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
if(!file.exists()){
file.mkdir();
}
KeyEventDispatcher dispatcher = new KeyEventDispatcher(){
public boolean dispatchKeyEvent(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_5){
try {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenshot = rbt.createScreenCapture(screenRect);
ImageIO.write(screenshot, "jpg", new File(file + "/" + num + ".jpg"));
num++;
System.out.println("screenshot taken");
} catch (Exception e1) {
e1.printStackTrace();
}
}
return false;
}
};
DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
}
I'm wondering if there is a java class or some other way to get user input without having the program run in the foreground.
Thank you

How do I check the item selected in a ComboBox and use that item as a parameter for another method?

I am creating a program which allows the user to enter data and then click a button to view said data. On the first frame I want the user to select an item from a ComboBox and when they click a button it takes the selected item from the ComboBox and enters it as a parameter for another method which will bring up data from a file (this method isn't yet complete).
The code I have so far is as follows:
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SpringLayout;
public class Main implements ActionListener{
static JButton ViewData = new JButton("View Data");
static JButton AddItem = new JButton("Add Item");
String Item = null;
public static void main(String[]args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new Main();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public Main() throws IOException{
//Populating ComboBox
String FilePath = "C:/Users/Harry/AS Computing/CWTreasurers/src/ItemList";
BufferedReader input = new BufferedReader(new FileReader(FilePath));
ArrayList<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}//End While
}//End Try
catch (FileNotFoundException e) {
System.err.println("Error, file " + FilePath + " didn't exist.");
}//End catch
finally {
input.close();
}//end Finally
String[] lineArray = strings.toArray(new String[]{});
JComboBox ChooseItems = new JComboBox(lineArray);
//End populating ComboBox
JFrame frame = new JFrame("CharityWeekTreasury");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//Sets Default properties of the window
Container ContentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
ContentPane.setLayout(layout);
//Defines the container for all objects and the layout
ContentPane.add(ChooseItems);
ContentPane.add(ViewData);
ContentPane.add(AddItem);
ViewData.addActionListener(this);
AddItem.addActionListener(this);
//Adds Objects to window
layout.putConstraint(SpringLayout.WEST,ChooseItems,5,SpringLayout.WEST,ContentPane);
layout.putConstraint(SpringLayout.NORTH,ChooseItems,5,SpringLayout.NORTH,ContentPane);
layout.putConstraint(SpringLayout.WEST,ViewData,5,SpringLayout.EAST,ChooseItems);
layout.putConstraint(SpringLayout.NORTH,ViewData,5,SpringLayout.NORTH,ContentPane);
layout.putConstraint(SpringLayout.WEST,AddItem,5,SpringLayout.EAST,ViewData);
layout.putConstraint(SpringLayout.NORTH,AddItem,5,SpringLayout.NORTH,ContentPane);
layout.putConstraint(SpringLayout.EAST,ContentPane,5,SpringLayout.EAST,AddItem);
layout.putConstraint(SpringLayout.SOUTH,ContentPane,5,SpringLayout.SOUTH,ChooseItems);
//Sets Positioning of objects relative to each other
frame.pack();
frame.setVisible(true);
//Makes frame visible
}//End Window
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
if(b.equals(ViewData)){
Item = ChooseItems.getSelectedItem();
ViewData view = new ViewData(Item);
}else if(b.equals(AddItem)){
new AddItem();
}
}
}
ViewData is both a button and the name of another class in the project, the main error is that the line
Item = ChooseItems.getSelectedItem();
Doesn't seem to work, I believe this to be due to the positioning of where ChooseItems is declared, this meaning that there is no ChooseItems to get a selected item of.
Any help is much appreciated. Thanks.

image as component issue

I am trying to do my final project for my java class. I am attempting to take a .png picture and use it as a component that I can add to my JFrame. However, when I try to do this it throws an exception and does what is in the catch statement. I do not understand why it would do this. I have the .png file in the same folder as my .java files.
package InventoryApp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
/**
*
* #author Curtis
*/
public class FinalProject extends DFrame
{
//main method
public static void main(String[] args)
{
start();
}
//building splash screen
public static void start()
{ DFrame splashFrame = new DFrame();
try
{
BufferedImage myPicture = ImageIO.read(new File("logo.png"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
splashFrame.add(picLabel);
}
catch(IOException g)
{
JLabel error = new JLabel("Picture Could Not Be Found");
splashFrame.add(error);
}
JButton create = new JButton("Click to Create Item List");
JButton view = new JButton("Click to View Item List");
splashFrame.add(create);
splashFrame.add(view);
}
}
When you create a File object with no path specified, it assumes the directory the program was launched from, not the directory the current class file is in. You probably want to instead use FinalProject.class.getResource():
BufferedImage myPicture = ImageIO.read(FinalProject.class.getResource("logo.png"));

Categories

Resources