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
Related
So I have to take a string input from GUI using Textfield and make it show up in a pdf document, when I use ActionListener :
b1[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0)
{
s=tf1[0].getText();
}
});
When I run the gui and type in the tf1 and press b1, it should save it in s right? But it isn't doing that, however if I just hardcode s="string" it shows up in the pdf. Any ideas?
Forgot to mention I am using iText so the only problem i am having is that the String s is not getting saved from the TextField
Also the code for the actionlistener class if you want it:
public class GUI {
public static String s;
public static void gui(){
{
try{
String File_Name="C:/Users/Ray/Desktop/test.txt";
ReadFile rf=new ReadFile(File_Name);
JFrame f1=new JFrame("Maintest");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
final String[] aryLines=rf.OpenFile();
final JTextField tf1[]=new JTextField[22];
JButton []b1=new JButton[6];
String bNames="OK";
final JTextField tf2[]=new JTextField[aryLines.length];
f1.setSize(200,450);
JLabel l1[]=new JLabel[20];
for ( int i=0; i < aryLines.length; i++ )
{
b1[i]=new JButton(bNames);
l1[i]=new JLabel("Enter Serial# for "+ aryLines[i]);
p1.add(l1[i]);p1.add(tf1[i] = new JTextField());p1.add(b1[i]);
}
p1.setLayout(new BoxLayout(p1,BoxLayout.PAGE_AXIS));
f1.add(p1,BorderLayout.WEST);
b1[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0)
{
s=""+tf1[0].getText();
System.out.println(s);
}
});
f1.show();
}
catch(Exception e)
{
System.out.print(e);
}
}
}
}
Sorry that I can't answer in more detail, but you could check if the tf1[0].getText() works. Just put a System.out.println("Text: "tf1[0].getText()); into your ActionListener. I'm pretty sure it will be null or "Text: ". For further help you'll have to provide more code.
Please take a look at this link
Ok, so here is a problem: I have main class which generates a window and two buttons:
...
public MainWindow()
{
...
b_read.addActionListener(new ReadStudents());
b_open_all.addActionListener(new OpenStudents());
...
In ReadStudents.java class I load data from a file with JFileChooser and print it on the screen. Sample of code thats load file:
#Override
public void actionPerformed(ActionEvent e) {
...
JFileChooser fc = new JFileChooser(".");
...
int rez = fc.showOpenDialog(fc);
if (rez == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
...
So now in my ReadStudents.java class variable "file" has my loaded information.
How do i pass this variable with containing information in it to a class that prints Students on the screen (second button OpenStudents.java) ?
Edit:1) I can not initialize an object of ReadStudents.java in OpenStudents.java class because in the new object variable "file" will be empty. Something is loaded to a "file" only when a button b_read is pressed.
One option would be to implement the action listener on your MainWindow class and the call a method in the ReadStudents/OpenStudents that return the list of files.
For example:
/**
* Main window class.
*/
public static void main(String args[]) {
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.setSize(100, 100);
final StudentReader student = new StudentReader();
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Make the call here. Take note!
// Look at the return type!
List<String> strings = student.fileNames();
for (String s : strings) {
System.out.println(s);
}
}
});
mainFrame.add(button);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public class StudentReader {
public List<String> fileNames() {
// Do your magic here :)
// Open a dialog. Get the files.
// Return it as a list
return Arrays.asList(new String[]{"Filename"});
}
}
I Hope this helps!
I know I'm missing something very simplem but for the life of me I can't see it. All I want to do is get "Paris" from the combo box, and when the button is pressed, show that "Paris" is selected.
public class assignment2try2 implements ActionListener {
private JComboBox HolidayLocation;
private JComboBox HolidayDuration;
private JButton PriceCheck;
public static void main(String[] args) {
JLabel Location = new JLabel(" Where do you want to go ? ");
String[] HolidayLocations = {" ","Paris", "Crete", "Croatia"};
JComboBox<String> LocationBox = new JComboBox<String>(HolidayLocations);
LocationBox.setEditable(false);
LocationBox.setPreferredSize(new Dimension( 160, 20 ));
//LocationBox.setSelectedIndex(4);
LocationBox.addActionListener(LocationBox);
JButton PriceCheck = new JButton("Check Availability");
PriceCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("button works");
//if(LocationBox.getSelectedItem().equals(HolidayLocations))
{
//System.out.println("paris selected");
}
}
});
}
}
EDIT: I just now noticed that your class implements ActionListener. With the below solution, you can remove the implements-statement from your code.
To fix your issues with the String having to be final, make a private class:
private class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println(locationBox.getSelectedItem() + " selected.");
}
}
Then, replace
PriceCheck.addActionListener(new ActionListener() { ... });
with
PriceCheck.addActionListener(new MyListener());
This should be able to print out the selected value after the button is pressed.
Note: I changed your variable name from LocationBox to locationBox to comply with naming conventions.
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