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?
Related
I want to create a simple stand-alone application that will take some input from user (some numbers and mathematical functions f(x,y...)) and write them to a file. Then with the help of this file I will run a command.
Basic ingredients that I need:
-- JTextArea for users input.
-- ButtonHandler/ActionListener and writing of the input to a (txt) file
-- ButtonHandler/ActionLister to execute a command
What is the best way to do it?
A current running code that I have (basically a toy) - which does not write anything, just executes - is:
import java.applet.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dialog;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.util.*;
import java.io.BufferedWriter;
public class Runcommand3
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//JApplet applet = new JApplet();
//applet.init();
final JFrame frame = new JFrame("Change Backlight");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JButton button = new JButton("Click me to Run");
button.setBounds(55,100,160,30);
panel.add(button);
frame.setSize(260,180);
frame.setVisible(true);
//This is an Action Listener which reacts to clicking on the button
button.addActionListener(new ButtonHandler());
}
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
double value = Double.parseDouble(
JOptionPane.showInputDialog("please enter backlight value"));
//File theFile = new File("thisfile.txt");
//theFile.write(value);
String command = "xbacklight -set " + value;
try{Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);}
catch(IOException t){t.printStackTrace();}
}
}
In the above example how can I write 'value' to a file? Then, how can I add more input (more textfields)? Can I do it in the same class or I need more?
My confusion comes (mainly but not only) from the fact that inside the ButtonHandler class I can NOT define any other objects (ie, open and write files etc).
This is the way I would write to a file. I will let you convert this code into your GUI for practice. See more on BufferedWriter and FileWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Files {
public static void main(String args[]){
System.out.print("Enter Text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine();
writer.close();
System.err.println("Your input of " + text.length() + " characters was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
}
For your second question, you may like to consider having a JTextField on your JFrame for the user to enter lines into instead of a JOptionPane. It's just a simple text box, and you can add the box's contents to the file every time the button is pressed:
public static void main(String[] args) {
JTextField myTextField = new JTextField();
// Your code, set size and position of textfield
panel.add(myTextField);
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String text = myTextField.getText();
myTextField.setText("");
new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close();
// the rest of your code
}
}
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");
}
}
}
I am trying to make a save button but I don't know how to do it. I will explain a little bit about my program. When someone start the program it shows a JOptionPane and the user need to write a nickname and then when he clicks on OK button it saves his nickname in a text.file. This is a part from my code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
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.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.event.*;
public class SummerExamProject extends JFrame {
JButton Exit, About, Question1, Question2, Question3, Question4;
JPanel panel, panel2, panel3, panel4 ;
public SummerExamProject(){
initUI();
}
public void initUI(){
setTitle("Java");
setSize(500, 450);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JFrame frame = new JFrame();
JFrame frame1 = new JFrame("");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(0,3,8,9));
String code = JOptionPane.showInputDialog(frame1, " Enter a nickname ", "Nickname needed", JOptionPane.WARNING_MESSAGE);
If you want to store nickname to file you can use PrintWriter. Lets say you saved the nickname in String variable called nickname:
String nickname = "myAwesomeNickname";
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("c:/nicknames.txt", true)));
out.println(nickname);
out.close();
} catch (IOException e) {
//exception handling
}
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("text.txt"));
out.print(code); // your String here
} catch (IOException e) {
} finally {
if (out != null)
out.close();
}
text.txt can also be a full path like new FileOutputStream("D:/folder/text.txt")
There are a few more options to write to files, though.
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
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.