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.
Related
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.
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 JSlider in my program, and have implemented a ChangeListener for the same.
public void stateChanged(ChangeEvent e)
{
JSlider source=(JSlider) e.getSource();
frame_value.setText(Integer.toString(source.getValue()));
//Condition to change the frame_no only when user has stopped moving the slider
if (!source.getValueIsAdjusting())
{
frame_no=(int) source.getValue()-1;
if(frame_no<0)
frame_no=0;
}
....
}
What is happening is, that whenever the ChangeListener is called, the program just skips the if block, and goes to the code after that. I don't understand why is this happening. I am not able to get the correct value from the JSlider. Please help!!
PS: I don't know if this is the reason, but recently I have set the UI of the JSlider to place the tick where I click it. I don't know if that is responsible for it or not. Here is the code:
slider.setUI(new MetalSliderUI() {
protected void scrollDueToClickInTrack(int direction) {
int value = HEVC_Analyzer.slider.getValue();
value = this.valueForXPosition(HEVC_Analyzer.slider.getMousePosition().x);
HEVC_Analyzer.slider.setValue(value);
}
});
Must be something wrong in your code, since it's working fine in this example :
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderChangeEffect extends JFrame
{
private JSlider slider;
private int count = 0;
private ChangeListener changeListener = new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
JSlider slider = (JSlider) ce.getSource();
if (!slider.getValueIsAdjusting())
System.out.println(slider.getValue());
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
slider = new JSlider(0, 10, 5);
slider.setMajorTickSpacing(2);
slider.setMinorTickSpacing(1);
slider.addChangeListener(changeListener);
contentPane.add(slider);
getContentPane().add(contentPane);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SliderChangeEffect().createAndDisplayGUI();
}
});
}
}
Just use the String.valueOf() and the event.MouseReleased().
private void jSlider1MouseReleased(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
try {
String valueOf = String.valueOf(jSlider1.getValue());
jLabel1.setText(valueOf);
} catch (Exception ex) {
ex.printStackTrace();
}
}
hello i desperately need your help,well i have a jframe with a jcombobox and 3 textfields i want anything i write in the textfields and the choice i make in the combobox to be written in a .txt i tried so many things but nothing , the file is being created as Orders.txt but remains blank :S this is my code i appreciate any help Thanks :)
public class addSalesMan extends JFrame {
private JComboBox namesJComboBox;
private JTextField text1;//gia to poso
private JTextField text2;//thn perigrafh
private JTextField text3;//kai to numero ths paragelias kai ola auta tha egrafontai sto Orders.txt
private JButton okJbutton;
private String names[] = {"Basilis Komnhnos", "Iwanna Papadhmhtriou"};
public String amount,name,description,number;
public addSalesMan() {
super("Προσθήκη παραγγελιών");
setLayout(new FlowLayout());//dialegoume to flowlayout
// TextFieldHandler handler = new TextFieldHandler(); writer.write(string);
//ftiaxonoume to combobox gia tn epilogi tou onomatos
namesJComboBox = new JComboBox(names);//orizmos JCOMBO BOX
namesJComboBox.setMaximumRowCount(2);//na emfanizei 2 grammes
add(namesJComboBox);
namesJComboBox.addItemListener(new ItemListener() {
//xeirozome to simvan edw dhladh tn kataxwrisei ston fakelo
public void itemStateChanged(ItemEvent event) {
//prosdiorizoyme an eina epilegmeno to plaisio elegxou
if (event.getStateChange() == ItemEvent.SELECTED) {
name = (names[namesJComboBox.getSelectedIndex()]);
// writer.newLine();
setVisible(true);
}
}
}); //telos touComboBOx
//dimioutgw pediou keimenou me 10 sthles gia thn kathe epilogh kai veveonomaste oti tha mporoume na ta epe3ergasoume kanontas ta editable
text1 = new JTextField("Amount",10);
add(text1);
text2 = new JTextField("Description",10);
add(text2);
text3 = new JTextField("Order Number",10);
add(text3);
TextFieldHandler handler = new TextFieldHandler();
text1.addActionListener(handler);
text2.addActionListener(handler);
text3.addActionListener(handler);
//private eswterikh clash gia ton xeirismo twn events twn text
//button kataxwrisis
okJbutton=new JButton("Καταχώρηση");
add(okJbutton);
ButtonHandler bhandler=new ButtonHandler();
okJbutton.addActionListener(bhandler);
Order order=new Order(name,amount,description,number);
Order.addOrders(name,amount,description,number);
}
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent bevent ){
JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",bevent.getActionCommand()));
}
}
private class TextFieldHandler implements ActionListener {
//epe3ergasia twn simvantwn me kathe enter t xrhsth
public void actionPerformed(ActionEvent evt) {
String amount,description,number;
amount=text1.getText();
description=text2.getText();
number=text3.getText();
text1.selectAll();
text2.selectAll();
text3.selectAll();
}
if(evt.getSource()==text1 && evt.getSource()==text2 && evt.getSource()==text3){
JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",evt.getActionCommand()));
}
}
//actionperformed telos
//ean o xrhsths patisei enter sthn kathe epilogh antistixi kataxwrisi sto
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addSalesMan().setVisible(true);
}
});
}
}
The writers are in another class. Here is the relevant code:
public static void addOrders(String name,String amount,String description,String o_number){
FileOutputStream fout;
try {
FileWriter fstream = new FileWriter("Orders.txt");
if(name!=null){
BufferedWriter out = new BufferedWriter(fstream);
out.write(name);
out.write(amount);
out.write(description);
out.write(o_number);
out.write("\t\n");
out.close();
}
} catch (IOException e) {
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
It looks like the main problem is that you are calling Order.addOrders() in your constructor. Instead, you should call it when a user chooses to save it's selection. I assume you would like this to happen when the user presses the button. So the code should be added in the button's ActionListener.
What you might need to try is flushing and closing the writer when a user closes your frame.
Add the following to the constructor of your frame:
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
writer.flush();
writer.close();
}
});
The above code will flush and close the writer when a user closes the frame.
Your code is unclear, so I'm not sure where the writer variable is declared, I'm just assuming it is a class level variable.
Also, you need to open your file in 'append' mode if you want to add lines to the file instead of overwriting it every time. This can be achieved through the following:
new FileWriter(yourFilePath, true); // set append to true