I have created a AWT frame which accepts text input in textarea and can count the number of words and characters or it could save its content to "trial.txt" file.
This is the whole code for reference:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class trial extends Frame
{
static TextArea ta=new TextArea("Welcome");
static Label l1=new Label("Words:");
static Label l2=new Label("Characters:");
static Button b=new Button("Count");
static Button save=new Button("Save");
static BufferedOutputStream bos;
trial()
{
//Setting position
ta.setBounds(300,300,300,300);
l1.setBounds(50,50,100,100);
l2.setBounds(50,200,100,100);
b.setBounds(650,300,50,50);
save.setBounds(650,400,50,50);
//Setting up file for saving
try {
bos=new BufferedOutputStream(new FileOutputStream("C:\\trial.txt"));
} catch (Exception e) {
e.printStackTrace();
}
save.addActionListener(new Save());
//Adding the components
this.add(ta);
this.add(l1);
this.add(l2);
this.add(b);
this.add(save);
//adding actionlistener to button
b.addActionListener(new actionlistener());
//setting up frame
this.setSize(1000,1000);
this.setLayout(null);
this.setVisible(true);
}
public static class actionlistener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
String words[]=text.split("\\s");
l1.setText("Words:"+words.length);
l2.setText("Characters:"+text.length());
}
}
public static class Save implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
byte[] arr=text.getBytes();
try
{
bos.write(arr);
} catch (IOException f)
{
}
}
}
public static void main(String args[])
{
trial ttt=new trial();
}
}
I have copied the right path, it is given above in the code. I have also given permission to java to read and write. But the code shows java.io.FileNotFoundException: C:\trial.txt (Access is denied) .
Oh it was very easy just a silly mistake.
Needed to put file name as parameter and not file path.
It is showing no error now but it is not saving the contents of the file to the txt file.
*Edit:It is working now.Thank you all for your help.
Related
I have made this simple program which opens a frame and in which you can write in the textarea given.You can count the number of words and characters using count button or you could save the text of the textarea to the local file-"trial.txt"
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class trial extends Frame
{
static TextArea ta=new TextArea("Welcome");
static Label l1=new Label("Words:");
static Label l2=new Label("Characters:");
static Button b=new Button("Count");
static Button save=new Button("Save");
static BufferedOutputStream bos;
trial()
{
//Setting position
ta.setBounds(300,300,300,300);
l1.setBounds(50,50,100,100);
l2.setBounds(50,200,100,100);
b.setBounds(650,300,50,50);
save.setBounds(650,400,50,50);
//Setting up file for saving
try {
bos=new BufferedOutputStream(new FileOutputStream("trial.txt"));
} catch (Exception e) {
e.printStackTrace();
}
save.addActionListener(new Save());
//Adding the components
this.add(ta);
this.add(l1);
this.add(l2);
this.add(b);
this.add(save);
//adding actionlistener to button
b.addActionListener(new actionlistener());
//setting up frame
this.setSize(1000,1000);
this.setLayout(null);
this.setVisible(true);
}
public static class actionlistener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
String words[]=text.split("\\s");
l1.setText("Words:"+words.length);
l2.setText("Characters:"+text.length());
}
}
public static class Save implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
byte[] arr=text.getBytes();
try
{
bos.write(arr);
bos.flush();
} catch (IOException f)
{
f.printStackTrace();
}
}
}
public static void main(String args[])
{
trial ttt=new trial();
}
}
But this is not working. The count button is working fine but the save button does not work. I do not understand what the error is. Your help will be greatly appreciated.
*Edit:It is working now.Just moved the location of the txt file to the same as of the location of the java file and it started working.Thanks for your help.
I have created a quick example below. I want to create a folder structure based on the text input of a user. eg:
text field 1 is: 2001
text field 2 is: test
Then the folder structure is c:\2001\test
It's part of a bigger app but this is the bit that has me stuck. Any help appreciated..
import java.io.File;
import javax.swing.*;
public class CreateDirectory extends JFrame {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CreateDirectory().setVisible(true);
}
});
}
public CreateDirectory() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Create New Job App");
panel pan = new panel();
add(pan.panel);
pack();
setVisible(true);
}
}
class panel {
private JButton btn1 = new JButton("Create");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
JPanel panel;
public panel() {
panel = new JPanel();
panel.add(btn1);
panel.add(txt1);
panel.add(txt2);
btn1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn1ActionPerformed(evt);
}
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {
File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
} else {
}
}
}
});
}
}
All what you need is to mentioned the directories to be created like this
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {
File files = new File("c:\\"+txt1.getText()+"\\"+txt2.getText());
if (!files.exists()) {
if (files.mkdirs()) {
} else {
}
}
}
I hope this could help!
I hope you have button , so on its action listener method, get values from both text boxes, validate them , then call a method something like this
private void createDirectories(String textInputOne , String textInputTwo){
String root="";//Your base directory or Drive in your case c:/
String totalPath=root+File.separator+textInputOne+File.separator+textInputTwo;
File folder=new File(totalPath);
if(!folder.exists()){
folder.mkdirs();
}else{
System.out.println("already exists");
}
}
I hope this works , and if you don't have permission in your base folder/drive mkdirs() will return false.
check that too.
Hello I have a class that opens a JFrame and takes in a text. But when I try getting the text it says its null.
Everytime I click the button I want the System.out to print the text I entered in the textArea.
This is my first class :
public class FileReader {
FileBrowser x = new FileBrowser();
private String filePath = x.filePath;
public String getFilePath(){
return this.filePath;
}
public static void main(String[] args) {
FileReader x = new FileReader();
if(x.getFilePath() == null){
System.out.println("String is null.");
}
else
{
System.out.println(x.getFilePath());
}
}
}
This is a JFrame that takes in the input and stores it in a static String.
/*
* This class is used to read the location
* of the file that the user.
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.event.*;
import javax.swing.*;
public class FileBrowser extends JFrame{
private JTextArea textArea;
private JButton button;
public static String filePath;
public FileBrowser(){
super("Enter file path to add");
setLayout(new BorderLayout());
this.textArea = new JTextArea();
this.button = new JButton("Add file");
add(this.textArea, BorderLayout.CENTER);
add(this.button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
System.exit(0);
}
});
}
}
But everytime I run these programs I get
String is null.
You are mistaken by the way how JFrames work. A JFrame does not stall the execution of the code until it is closed. So, basically, your code creates a JFrame and then grabs the filePath variable in that object, before the user could have possibly specified a file.
So, to solve this, move the code that outputs the filepath to stdout to the ActionListener you have. Get rid of the System.exit() call, and use dispose() instead.
Update: You should have this code for the ActionListener:
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
if(filePath == null){
System.out.println("String is null.");
}
else
{
System.out.println(filePath);
}
dispose();
}
});
And as main method:
public static void main(String[] args)
{
FileBrowser x = new FileBrowser();
}
Your main does not wait until the user has specified a text in the textArea. You could prevent this behaviour by looping until the text in the textArea is set or you could place the logic of the main function into the ActionListener to handle the event.
Following the second way the main function only creates a new FileBrowser object.
I'm trying to call this event below; I create the frame with TabBuilder (since is part of my application) then it calls the Search screen which is popping up; but the event of the search with key bind or simple click on the button is not working and of course I'm doing something wrong but I don't know what since I'm a little bit new in Java. Please could anyone help me?
SearchScreen:
public class SearchScreen extends EventSearch{
public static void main (String[] args){
SearchScreen s= new SearchScreen();
}
public void SearchScreen(){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
EventSearch:
public class EventSearch extends TabBuilder{
String userQuery;
String key = "ENTER";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
public EventSearch(){
btSearch.addActionListener(this);
txtSearch.getInputMap().put(keyStroke, key);
txtSearch.getActionMap().put(key, enterAction);
}
Action enterAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
try{
System.out.println("worked");
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "HTTP request failure.");
}
}
};
}
TabBuilder:
public class TabBuilder implements ActionListener {
protected JButton btSearch;
JMenuItem close, search;
protected JTextField txtSearch;
protected JFrame searchFrame = new JFrame();
public void TabBuilder(){
}
public void searchTab(){
JLabel lbSearch;
JPanel searchPane;
btSearch= new JButton("Search");
lbSearch= new JLabel("Type Keywords in english to be searched below:");
lbSearch.setHorizontalAlignment(SwingConstants.CENTER);
txtSearch= new JTextField();
searchPane=new JPanel();
searchPane.setBackground(Color.gray);
searchPane.add(lbSearch);
searchPane.add(txtSearch);
searchPane.add(btSearch);
searchPane.setLayout(new GridLayout(3,3));
btSearch.setEnabled(true);
searchFrame.add(searchPane);
searchFrame.setTitle("SHST");
searchFrame.setSize(400, 400);
searchFrame.setVisible(true);
searchFrame.setDefaultCloseOperation(1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
SearchScreen s = new SearchSreen();
}
}
}
You write this actionListener
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
and you added to btnSearch.addActionListener(this) , your actionListener never would do anything.
And for your KeyBinding happens something similar , you add the action to the txtSearch and then you are asking if the source is the e.getSource()==btSearch
And for KeyBindings you can use Constants to specify when they have to be binded.
JComponent.WHEN_FOCUSED, JComponent.WHEN_IN_FOCUSED_WINDOW , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
For example :
txtSearch.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
How to use KeyBindings
I am using a gui with JTextFields to collect some information and then a JButton that takes that infomration and writes it to a file, sets the gui visibility to false, and then uses Runnable to create an instance of another JFrame from a different class to display a slideshow.
I would like to access some of the information for the JTextFields from the new JFrame slideshow. I have tried creating an object of the previous class with accessor methods, but the values keep coming back null (I know that I have done this correctly).
I'm worried that when the accessor methods go to check what the variables equal the JTextFields appear null to the new JFrame.
Below is the sscce that shows this problem.
package accessmain;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AccessMain extends JFrame implements ActionListener
{
private static final int FRAMEWIDTH = 800;
private static final int FRAMEHEIGHT = 300;
private JPanel mainPanel;
private PrintWriter outputStream = null;
private JTextField subjectNumberText;
private String subjectNumberString;
public static void main(String[] args)
{
AccessMain gui = new AccessMain();
gui.setVisible(true);
}
public AccessMain()
{
super("Self Paced Slideshow");
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//Begin Main Content Panel
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(0,10,0,10));
mainPanel.setLayout(new GridLayout(7, 2));
mainPanel.setBackground(Color.WHITE);
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(new JLabel("Subject Number: "));
subjectNumberText = new JTextField(30);
mainPanel.add(subjectNumberText);
mainPanel.add(new JLabel(""));
JButton launch = new JButton("Begin Slideshow");
launch.addActionListener(this);
mainPanel.add(launch);
//End Main Content Panel
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Begin Slideshow"))
{
subjectNumberString = subjectNumberText.getText();
if(!(subjectNumberString.equals("")))
{
System.out.println(getSubjectNumber());
this.setVisible(false);
writeFile();
outputStream.println("Subject Number:\t" + subjectNumberString);
outputStream.close();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass();
testClass.setVisible(true);
}
});
}
else
{
//Add warning dialogue here later
}
}
}
private void writeFile()
{
try
{
outputStream = new PrintWriter(new FileOutputStream(subjectNumberString + ".txt", false));
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + subjectNumberString + ".txt or it could not be opened.");
System.exit(0);
}
}
public String getSubjectNumber()
{
return subjectNumberString;
}
}
And then creating a barebones class to show the loss of data:
package accessmain;
import javax.swing.*;
import java.awt.*;
public class AccessClass extends JFrame
{
AccessMain experiment = new AccessMain();
String subjectNumber = experiment.getSubjectNumber();
public AccessClass()
{
System.out.println(subjectNumber);
}
}
Hardcoding the accessor method with "test" like this:
public String getSubjectNumber()
{
return "test";
}
Running this method as below in the new JFrame:
SelfPaceMain experiment = new SelfPaceMain();
private String subjectNumber = experiment.getSubjectNumber();
System.out.println(subjectNumber);
Does cause the system to print "test". So the accessor methods seem to be working. However, trying to access the values from the JTextFields doesn't seem to work.
I would read the information from the file I create, but without being able to pass the subjectNumber (which is used as the name of the file), I can't tell the new class what file to open.
Is there a good way to pass data from JTextFields to other classes?
pass the argument 'AccessMain' or 'JTextField' to the second class:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass(AccessMain.this); //fixed this
testClass.setVisible(true);
}
});
Then reading the value of 'subjectNumber'(JTextField value) from the 'AccessMain' or 'JTextField' in the second class:
public class AccessClass extends JFrame
{
final AccessMain experiment;
public AccessClass(AccessMain experiment)
{
this.experiment = experiment;
}
public String getSubjectNumber(){
return experiment.getSubjectNumber();
}
}
Also, you should try Observer pattern.
A simple demo of Observalbe and Observer
Observable and Observer Objects