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);
Related
I'm using JTextPane and StyledDocument for styling message and I want to clear the messages or clear only the oldest message.
I can easily clear all by using:
textPane.setText("");
But if I want to clear all, except some lines, then not sure if/how it can be done.
I tried
textPane.setText(textPane.getText().substring(0, Math.min(200, textPane.getText().length())));
but the issue is that it remove the content styling.
Here is simple demo that shows the issue.
Is there an easy way to do it?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class TestJTextPane {
private JTextPane infoTextPane = new JTextPane();
private StyledDocument styledDocument;
private SimpleAttributeSet attributeSet = new SimpleAttributeSet();
private JButton addText;
private JButton clearText;
public static void main(String[] argv) {
new TestJTextPane();
}
public TestJTextPane(){
addText = new JButton("add");
addText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
StyleConstants.setForeground(attributeSet, Color.GREEN);
StyleConstants.setBackground(attributeSet, Color.BLACK);
StyleConstants.setBold(attributeSet, true);
StyleConstants.setFontSize(attributeSet, 20);
styledDocument.insertString(styledDocument.getLength(), "sample text message to add\n", attributeSet);
infoTextPane.setCaretPosition(infoTextPane.getDocument().getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
clearText = new JButton("clear");
clearText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//infoTextPane.setText("");
infoTextPane.setText(infoTextPane.getText().substring(0, Math.min(200, infoTextPane.getText().length())));
}
});
styledDocument = infoTextPane.getStyledDocument();
JPanel p = new JPanel();
p.add(addText);
p.add(clearText);
p.add(infoTextPane);
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(p);
f.setPreferredSize(new Dimension(400, 400));
f.pack();
f.setVisible(true);
}
}
Figure how to do it with Element. For example, the below code will keep only the latest 2 messages.
Element root = infoTextPane.getDocument().getDefaultRootElement();
try {
while(root.getElementCount() > 3){
Element first = root.getElement(0);
infoTextPane.getStyledDocument().remove(root.getStartOffset(), first.getEndOffset());
}
} catch (BadLocationException e1) {
// FIXME Auto-generated catch block
e1.printStackTrace();
}
I am still pretty new to Java and for my class, we have to make a web browser without JEditor. I just need to figure out how to use the socket when a user types in the JTextField and then make it go to that website. Also, I am only supposed to use http:// not https:// if that makes a difference. Anything helps! Thanks!
import javax.swing.*;
import java.awt.*;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.Socket;
import java.io.*;
public class WebPanel extends JPanel{
PrintWriter pw;
JTextField text = new JTextField("http://www.");
public WebPanel(){
//trying to connect to the website
try {
Socket s = new Socket(text, 80); //<<<---where the error is thrown
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os, true);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
//set layout
setLayout(null);
ButtonHandler bh = new ButtonHandler();
text.addActionListener(bh);
text.setBounds(185, 10, 315, 25);
add(text);
//buttons
JButton goButton = new JButton("GO");
goButton.addActionListener(bh);
add(goButton);
goButton.setBounds(500, 10, 75, 25);
JButton backButton = new JButton("BACK");
backButton.addActionListener(bh);
add(backButton);
backButton.setBounds(2, 10, 75, 25);
JButton forwardButton = new JButton("FORWARD");
forwardButton.addActionListener(bh);
add(forwardButton);
forwardButton.setBounds(80, 10, 100, 25);
}
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//buttons for later
if(e.getActionCommand().equals("GO")){
String input = text.getText();
System.out.println("You searched for: " + input);
pw.flush();
}else if(e.getActionCommand().equals("BACK")){
System.out.println("you pressed the back button");
pw.flush();
} else if(e.getActionCommand().equals("FORWARD")){
System.out.println("You pressed the forward button");
pw.flush();
}
}
}
}
}
For simple cases you don't need to use Sockets. You can use URL class like this:
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class URLReadTest {
public static void main(String[] args) throws Exception {
InputStream is = new URL("http://stackoverflow.com/").openStream();
String html = IOUtils.toString(is);
is.close();
System.out.println(html); // Parse HTML here
}
}
And then you have to parse returned HTML by yourself before you can visualize it of course.
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
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {
JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});
So, in this function, I want to read some text files within a mentioned directory/folder by input. User selects the directories/folder using JFILECHOOSER method and the output will be listed in a textbox [Directory]. Lets say that fileName is the text field where users input the name of the file, after users input their file name, they click on a start button. The start button functions on whereby it will look into the given directory/folder [the textbox] and search for text files and output the text files' name using system.out.printIn. I have not tried the code for directory/folder path because I'm not sure how to code for it. Any help or guide to this problem? I have only created one class and I'm new to JAVA GUI
The full code is as below:
package com.directory.file;
import java.awt.BorderLayout;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.TextArea;
import java.awt.TextComponent;
import java.awt.Event.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;
import javax.lang.model.element.VariableElement;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Component;
import java.sql.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JSplitPane;
import javax.swing.JLayeredPane;
import javax.swing.JDesktopPane;
import javax.swing.JComboBox;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SpinnerDateModel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.text.JTextComponent;
import java.awt.Color;
import javax.swing.SwingConstants;
import java.awt.ComponentOrientation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import com.toedter.calendar.JDateChooser;
import javax.swing.JSpinner;
import org.eclipse.wb.swing.FocusTraversalOnArray;
public class Directory extends JFrame {
private JPanel contentPane;
private JTextField txtKeyword;
private JTextField fileName;
private JTextArea jTextArea1;
private JDateChooser dateChooser;
private JSpinner spinner_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Directory frame = new Directory();
frame.setVisible(true);
frame.setSize(450,630);
frame.fileName.requestFocus();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Directory() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 436, 631);
contentPane = new JPanel();
contentPane.setAlignmentX(Component.LEFT_ALIGNMENT);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDirectory = new JLabel("Directory:");
lblDirectory.setBounds(20, 29, 55, 24);
contentPane.add(lblDirectory);
JLabel lblDate = new JLabel("Date:");
lblDate.setBounds(37, 141, 55, 24);
contentPane.add(lblDate);
txtKeyword = new JTextField();
txtKeyword.setHorizontalAlignment(SwingConstants.CENTER);
txtKeyword.setToolTipText("");
txtKeyword.setColumns(10);
txtKeyword.setBounds(85, 193, 229, 20);
contentPane.add(txtKeyword);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setDateFormatString("YYYMMd");
dateChooser.setBounds(85, 141, 229, 20);
contentPane.add(dateChooser);
JLabel lblKeyword = new JLabel("Keyword:");
lblKeyword.setBounds(20, 191, 55, 24);
contentPane.add(lblKeyword);
JSeparator separator = new JSeparator();
separator.setBounds(148, 204, -113, 34);
contentPane.add(separator);
JButton btnExport = new JButton("Export");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnExport.setBounds(324, 556, 89, 23);
contentPane.add(btnExport);
final JLabel Directory = new JLabel("");
Directory.setBorder(new LineBorder(new Color(0, 0, 0)));
Directory.setBounds(85, 30, 290, 22);
contentPane.add(Directory);
int min = 0;
int max = 23;
int step = 1;
int initValue = 0;
SpinnerModel sm = new SpinnerNumberModel(initValue, min, max, step);
final JSpinner spinner_1 = new JSpinner(new SpinnerNumberModel(0, 0, 23-1, 1));
spinner_1.setBounds(324, 143, 89, 20);
contentPane.add(spinner_1);
JButton btnNewButton = new JButton("...");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename =f.getAbsolutePath();
Directory.setText(filename);
});
btnNewButton.setBounds(377, 30, 36, 23);
contentPane.add(btnNewButton);
final JTextArea jTextArea1 = new JTextArea();
jTextArea1.setRows(15);
jTextArea1.setColumns(15);
jTextArea1.setBounds(42, 249, 351, 294);
jTextArea1.setLineWrap(true);
jTextArea1.setWrapStyleWord(true);
contentPane.add(jTextArea1);
jTextArea1.setEditable(false);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {
JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});
btnStart.setBounds(324, 215, 89, 23);
contentPane.add(btnStart);
JLabel lblFileName_1 = new JLabel("File Name:");
lblFileName_1.setBounds(20, 79, 75, 24);
contentPane.add(lblFileName_1);
fileName = new JTextField();
fileName.setToolTipText("");
fileName.setHorizontalAlignment(SwingConstants.CENTER);
fileName.setColumns(10);
fileName.setBounds(85, 81, 290, 20);
contentPane.add(fileName);
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{fileName, lblDirectory, lblDate, txtKeyword, btnStart, lblKeyword, separator, btnExport, Directory, dateChooser, dateChooser.getCalendarButton(), spinner_1, btnNewButton, jTextArea1, lblFileName_1}));
}
}
Problem #1
You only ever use the fileName value when trying to open the file...
FileReader fr = new FileReader(filename);
A file is a catenation of the directory and the name, for example...
FileReader fr = new FileReader(new File(Directory.getText(), filename));
Problem #2
You're doing some kind of pre-emptive read on the file which is not required...
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
You should just start reading the file, otherwise you've lost the first line of text
Problem #3
You're not closing the streams in the event of some kind of exception...
try {
FileReader fr = new FileReader(new File(Directory.getText(), filename));
BufferedReader br = new BufferedReader(fr);
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
}
If, for some reason, an exception occurs while you are opening or reading the streams, they can never be closed...at least not until the JVM closes
Instead, you should either be using try-with-resources if you're using Java 7+ or a finally block to ensure the streams are closed, for example...
BufferedReader br = null;
try {
String filename = fileName.getText();
br = new BufferedReader(new FileReader(new File(Directory.getText(), filename)));
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {
try {
br.close();
} catch (Exception e) {
}
}
It would also be of more help to you if you at least dumped the stack trace of the actual exception or logged it some how...
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {
Problem #4
null layout. Pixel perfect layouts are an illusion in modern UI design, you have no control over fonts, DPI, rendering pipelines or other factors that will change the way that you components will be rendered on the screen.
Swing was designed to work with layout managers to overcome these issues. If you insist on ignoring these features and work against the API design, be prepared for a lot of headaches and never ending hard work...
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. ;)