Extend JTextField to InputStream and action from Button - java

I have some problems with my code and i would need some help if you can please(and explain it a bit so i can understand in the future:)), so this is my code and what i need is that my JButton to action a shutdown command and the shutdown command to be delayed from the seconds i input in my JTextfield.
So my code so far is :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Shutdown extends JFrame{
InputStream text1;
JButton start;
String shutdownCmd;
public Shutdown() {
this.setTitle("Shutdown When you want");
setSize(300, 150);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel desc1 = new JLabel("Time until shutdown : ");
desc1.setBounds(95, 25, 125, 25);
add(desc1);
JTextField text1 = new JTextField();
text1.setBounds(95, 45, 120, 25);
text1.setForeground(Color.BLACK);
text1.setToolTipText("Introdu textu aici");
add(text1);
JButton start = new JButton("Start Shudown");
start.setBounds(95, 75, 120, 25);
add(start);
ActionListener eventstart = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionstart = arg0.getActionCommand();
if(actionstart.equals("Start Shudown")){
try {
ShutdownCmd();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
start.addActionListener(eventstart);
}
public void ShutdownCmd() throws IOException{
Runtime runtime = Runtime.getRuntime();
BufferedReader br=new BufferedReader(new InputStreamReader(text1));
long a=Long.parseLong(br.readLine());
Process proc = runtime.exec("shutdown -s -t "+a);
System.exit(0);
}
}
Thank you or the help in advanced !!! :D

Lots of things jump out at me here, but...
Redeclare text1 as JTextField instead of an InputStream...
//InputStream text1;
private JTextField text1;
This will allow you to access the field and it's value from anywhere in the class.
Make sure you aren't shadowing the variables when you create the text field...
//JTextField text1 = new JTextField();
text1 = new JTextField(10);
Make use of ProcessBuilder instead of Runtime.getRuntime(). It will make your life easier to deals with parameters much better
ProcessBuilder pb = new ProcessBuilder("shutdown", "-s", "-t", text1.getText());
pb.redirectError();
Process p = pb.start();
The action command will always be null as you never set, so the following will cause you a NullPointerException
String actionstart = arg0.getActionCommand();
if(actionstart.equals("Start Shudown")){
When you create your button, you need to set the action command...
JButton start = new JButton("Start Shudown");
start.setActionCommand("Start Shudown");
Additional suggestions...
Make use of appropriate layout managers. Even across the same OS, it's possible your application will need to deal with different screen resolutions, DPI, fonts etc...
Avoid extending directly from top level containers like JFrame. Instead, base you application on something like JPanel. It makes your application for flexible and re-usable.

All you need to do is make the JTextField a field:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Shutdown extends JFrame{
JTextField text1;
JButton start;
String shutdownCmd;
public Shutdown() {
this.setTitle("Shutdown When you want");
setSize(300, 150);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel desc1 = new JLabel("Time until shutdown : ");
desc1.setBounds(95, 25, 125, 25);
add(desc1);
text1 = new JTextField();
text1.setBounds(95, 45, 120, 25);
text1.setForeground(Color.BLACK);
text1.setToolTipText("Introdu textu aici");
add(text1);
JButton start = new JButton("Start Shudown");
start.setBounds(95, 75, 120, 25);
add(start);
ActionListener eventstart = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionstart = arg0.getActionCommand();
if(actionstart.equals("Start Shudown")){
try {
ShutdownCmd();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
start.addActionListener(eventstart);
}
public void ShutdownCmd() throws IOException{
Runtime runtime = Runtime.getRuntime();
long a=Long.parseLong(text1.getText());
Process proc = runtime.exec("shutdown -s -t "+a);
System.exit(0);
}
}
If it's global, you can use it in any of this object's functions, so you can get the Text from the textField from anywhere you want inside your JFrame Object.
I hope this is what you want to do. If its not explained well enough, please tell me. ;)

Related

How to get string from JTextField and save it in variable?

I am making a simple kid game that will ask the user to enter his/her name in a JTextField and that name will shown in other class after ending the game.
I made new object and used it to call the method getName but when I call the method it return null
I want it to return the name that the user entered.
This is the code:
package learn_englishTest;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Home extends JFrame{
JTextArea welcome_txt,userName_txt;
JTextField user_name;
JLabel Background_lbl;
JButton exit_btn,start_btn;
JPanel panel;
Icon Background_icon;
String name;
Font userName_font,welcome_font;
public Home(){
super("Easy Fun Learning");
Container c =getContentPane();
c.setLayout(new BorderLayout());
panel =new JPanel(null);
panel.setPreferredSize(new Dimension(650,470));
welcome_txt=new JTextArea("Welcom to Easy Fun Learning ");
welcome_txt.setEditable(false);
welcome_font = new Font("Verdana", Font.BOLD, 30);
welcome_txt.setFont(welcome_font);
welcome_txt.setForeground(Color.pink);
welcome_txt.setBounds(80, 60, 500, 50);
userName_font=new Font("Verdana",Font.BOLD,20);
userName_txt=new JTextArea("Enter Your Name");
userName_txt.setEditable(false);
userName_txt.setFont(userName_font);
userName_txt.setForeground(Color.BLUE);
userName_txt.setBounds(350, 200, 200, 40);
user_name=new JTextField(10);
user_name.setBounds(400, 240, 100, 30);
start_btn=new JButton("Start");
start_btn.setBounds(480, 360, 100, 20);
exit_btn=new JButton("Exit");
exit_btn.setBounds(480, 390, 100, 20);
Background_icon=new ImageIcon(getClass().getResource("art.png"));
Background_lbl=new JLabel(Background_icon);
Background_lbl.setBounds(0, 80, 450, 450);
panel.add(welcome_txt);
panel.add(userName_txt);
panel.add(user_name);
panel.add(exit_btn);
panel.add(start_btn);
panel.add(Background_lbl);
panel.setBackground(Color.WHITE);
c.add(panel,BorderLayout.BEFORE_FIRST_LINE);
ButtonHandler handler=new ButtonHandler();
exit_btn.addActionListener(handler);
start_btn.addActionListener(handler);
}
private class ButtonHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==exit_btn)
System.exit(0);
if(e.getSource()==start_btn){
name=user_name.getText();
List list=new List();
list.setSize(700, 700);
list.setVisible(true);
list.setDefaultCloseOperation(EXIT_ON_CLOSE);
Home.this.setVisible(false);
}
}
}
#Override
public String getName(){
return name;
}
}
You forgot to add an ActionListener.
user_name.addActionListener(handler);
I strongly suggest you to follow the Java naming conventions as well.
So user_name should be userName.
To get a string from a JTextField, you simply need the following:
String var = jTextFieldName.getText();
This will save whatever is in the JTextField into the var variable.
The getText() is simply a method belonging to the JTextField class and returns whatever text is in it.
try something like:
JTextArea userName_txt = new JTextArea("Enter Your Name");
userName_txt.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(final DocumentEvent paramDocumentEvent) {
name = userName_txt.getText();
}
#Override
public void insertUpdate(final DocumentEvent paramDocumentEvent) {
name = userName_txt.getText();
}
#Override
public void changedUpdate(final DocumentEvent paramDocumentEvent) {
name = userName_txt.getText();
}
});
or rewrite getName() to something like:
public String getName() {
return userName_txt.getText();
}
But you basically overwrote Component.getName() in your code which makes no sense at all, better rename your method to getUsername().

Java text to speech I can't get it to talk

I have been trying to make a text to speech program i'm on a windows pc just for reference. I can't get my program to say what i've told it to. If someone can help me fix this or point me to a resource that will help me fix it, it will be much appreciated
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class javatalker extends JFrame{
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
JTextField textfield = new JTextField(35);
JButton button = new JButton("Push To Talk");
JCheckBox checkbox1 = new JCheckBox("Normal");
JCheckBox checkbox2 = new JCheckBox("Blitzcrank");
public javatalker() {
panel.add(textfield);
panel.add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
if(textfield.getText().equalsIgnoreCase("")){
System.out.println("Typle in a string");
} else{
Runtime rt = Runtime.getRuntime();
try{
if(checkbox1.isSelected() == true){
Process p = rt.exec("say" + textfield.getText());
}
if(checkbox2.isSelected() == true){
Process p = rt.exec("say -v Cellos" + textfield.getText());
} else{
System.out.println("Please select a voice");
}
}catch(Exception ex) {
ex.getStackTrace();
}
}
}
});
panel.add(checkbox1);
panel.add(checkbox2);
panel.setBackground(Color.black);
add(panel);
setTitle("Voicip");
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String args[]){
new javatalker();
}
}
say command does not exist on windows.
You could create a script
#echo off
echo Dim Speak >> %HOMEPATH%\speak.vbs
echo Set Speak=CreateObject("sapi.spvoice") >>
%HOMEPATH%\speak.vbs
echo Speak.Speak "%1">> %HOMEPATH%\speak.vbs
%HOMEPATH%\speak.vbs
del %HOMEPATH%\speak.vbs
pasted from https://superuser.com/questions/223913/os-x-say-command-for-windows
Name the script speak.bat and put it in C:\Windows\system32
Then modify
Process p = rt.exec("say" + textfield.getText());
to
Process p = rt.exec("speak" + textfield.getText());
You might also have a look at espeak which is open-source.

I need a Jlist to popup when a file with integers is either entered or selected from JFileChooser

I am using WindowBuilder in Eclipse to aid in my GUI design. I am trying to make a Jlist popup after the user either enters in a text file with integers in it or, if they enter a file that doesn't exist, they select a file with integers in it from JFileChooser. My problem I am having now is that when the file is selected, nothing happens. The program also doesn't seem to recognize when I do enter in a file that exists, it just defaults to the JFileChooser. Any ideas as to what I'm doing wrong and/or how to make the Jlist appear after an appropriate file is entered?
Here is the code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GUI {
private JFrame frame;
private JTextField txtEnterFileName;
private JTextField textField;
private JFileChooser fileChooser;
private JList list;
private JList list_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtEnterFileName = new JTextField();
txtEnterFileName.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtEnterFileName.setEditable(false);
txtEnterFileName.setText("Enter File Name Below and Press Button");
txtEnterFileName.setBounds(72, 11, 304, 41);
frame.getContentPane().add(txtEnterFileName);
txtEnterFileName.setColumns(10);
textField = new JTextField();
textField.setBounds(113, 63, 221, 25);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int number;
boolean endOfFile = false;
File userF;
userF = new File(textField.getText());
if(!userF.exists()){
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + "/desktop"));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(userF.exists()){
try {
Scanner inFile = new Scanner(userF);
if(inFile.hasNextLine()){
inFile.close();
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(inFile.hasNextInt()){
String label[] = {"Smallest Number", "Largest Number", "Count", "Average", "Median", "Quit"};
list = new JList(label);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
btnNewButton.setBounds(174, 99, 89, 23);
frame.getContentPane().add(btnNewButton);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
Scanner#nextLine always seems to return true so long as there some text on the first line.
So a file in the format of ...
1 2 3 4 5 6
Will have Scanner#nextLine return true. Instead, you should check for hasNextInt first and then skip over to showing the JFileChooser
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

No writing to file from application

This is my code and below the code is the problem i have :
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
public class Write extends JFrame {
JTextArea text;
public Write(){
this.setTitle("Lista Carti!");
setSize(400, 200);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel lbltitlu = new JLabel("Titlu");
lbltitlu.setBounds(85, 5, 120, 25);
this.add(lbltitlu);
JTextArea text = new JTextArea();
text.setSize(199,199);
text.setBounds(85, 65, 120, 25);
add(text);
JButton btn = new JButton("Adauga text");
btn.setSize(99,99);
btn.setBounds(125, 125, 120, 25);
add(btn);
ActionListener listenerbtn = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionbtn = arg0.getActionCommand();
if (actionbtn.equals("Adauga")) {
Adauga();
}
}
};
btn.addActionListener(listenerbtn);
}
public void Adauga(){
String filename = "test.txt";
FileWriter writer = null;
try {
writer = new FileWriter(filename);
text.write(writer);
} catch (IOException exception) {
System.err.println("Save oops");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
}
This is my code to write into a file,but it does autowrite when i hover the button and when i reenter the application it won't write again in the same file, any help please? ----- Old request
New request - >
I have edited my code,implemented actionListener but it dosen't input anything to the external file as it should. Can please some one tell me why or where did i done my mistake,i'm a noob programmer by the way? :D
Thank you!
To append to the file , use the constructor File(filename,append).
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
FileWriter fw = new FileWriter(filename,true);

Getting rid of Dialog Boxes and replacing with JLabel

I am currently working on an applet and am having a bit of trouble finishing it off. My code works just fine however I need to change the final portion from a JOptionDialog Message Dialog into just a JLabel that gets added to the applet. I've tried every way I can think of and am still coming up short. My current code looks as followed:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
JOptionPane.showMessageDialog(null, "Access Granted");
return
}
else {
JOptionPane.showMessageDialog(null, "Access Denied");
}
}
}
}
Please help!
Try this one:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
JLabel message = new JLabel();
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.add(message);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
message.setText("Access Granted");
return;
}
else {
message.setText("Access Denied");
}
}
}
}
Its sample code so no alignment is done it will show message next to button. You can change alignment as you wish ;)

Categories