Java : Any way to save a string input into pdf - java

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

Related

Java: Saving TextField to a string used in another class

public void actionPerformed(ActionEvent e) {
s = tf1[0].getText();
}
I want to save the text input i get from tf1[0].getText(); to String s and call s in my main , or in another class, but I get null back instead. Is there a way to call s in another class?
this is the rest of the code:
public class GUI {
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[];
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(){
private String s2;
public void actionPerformed(ActionEvent e)
{
s=tf1[0].getText();
System.out.print(s);
}
});
f1.show();
}
catch(Exception e)
{
System.out.print(e);
}
}
}
}
There are a couple solutions to this. You can make "s" a class based variable that can be retrieved from the object instance like this:
public String getS(){
return this.s;
}
And here:
public void actionPerformed(ActionEvent e) {
this.s = tf1[0].getText();
}
Then in your other class needing s, you should instantiate the Class containing s and call:
String s2 = instantiatedObject.getS();
If you feel getting a little risky, you can make "s" a static variable and you can just call it anywhere you instantiate the class containing "s":
String s2 = instantiatedObject.s;

Create a Folder Structure from User input

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.

Terminal class called from JFrame class don't have user inputs for a reason

Here is my code
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Login
{
static BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
static String a, b, c;
static int d, z, f, g, h, i, k;
public static void Login()
{
JFrame frame = new JFrame("Login");
JButton button1 = new JButton("Login");
JLabel label1 = new JLabel("Username: ");
JLabel label2 = new JLabel("Pin: ");
JTextField txt1 = new JTextField(8);
JPasswordField pass1 = new JPasswordField(8);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel FormPanel = new JPanel();
txt1.setBackground(Color.white);
pass1.setBackground(Color.white);
panel1.add(label1);
panel1.add(txt1);
panel2.add(label2);
panel2.add(pass1);
FormPanel.setLayout(new GridLayout(3,8));
FormPanel.add(panel1);
FormPanel.add(panel2);
FormPanel.add(button1);
pass1.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
changed();
}
public void removeUpdate(DocumentEvent e)
{
changed();
}
public void insertUpdate(DocumentEvent e)
{
changed();
}
public void changed()
{
if (pass1.getText().equals(""))
{
button1.setEnabled(false);
}
else
{
button1.setEnabled(true);
}
}
});
txt1.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
changed();
}
public void removeUpdate(DocumentEvent e)
{
changed();
}
public void insertUpdate(DocumentEvent e)
{
changed();
}
public void changed()
{
if (txt1.getText().equals(""))
{
button1.setEnabled(false);
}
else
{
button1.setEnabled(true);
}
}
});
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.hide();
Body a = new Body();
a.Body();
}
});
button1.setActionCommand("Open");
frame.setContentPane(FormPanel);
frame.setSize(8,9);
frame.pack();
frame.show();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
and my Body.java is
try
{
do
{
System.out.print("Working time (hours): ");
a=dataIn.readLine();
e=Integer.parseInt(a);
k=e;
if(k<8)
{
System.out.print("\nYou have worked undertime");
g=e * 30;
h=g * 500;
i=h-200;
System.out.print("\nYour payment (per month) is: " +i);
}
if(k>8)
{
System.out.print("\nYou have worked overtime");
g=e*30;
h=g*500;
i=h+200;
System.out.print("\nYour payment (per month) is: " +i);
}
if(k==8)
{
System.out.print("\nYou have worked ontime");
g=e*30;
h=g*500;
System.out.print("\nYour payment (per month) is: " +h);
}
System.out.print("\n\nPress 0 to logout: ");
c=dataIn.readLine();
d=Integer.parseInt(c);
}while(d!=0);
}
catch(Exception j)
{
System.out.print("\nYou probably need to work for more than an hour to start earning");
}
of course I have import java.io.*; and BufferedReader dataIn = new BufferedReader(<arguments>); but when ever I call the body.java that opens in terminal it won't ask for user inputs, but when I try to execute the body.java it asks for user inputs...
I need help right now...
You ask:
okay.. then please tell me how can I do some simple calculations in full GUI?
Again you'll want to avoid trying to mix GUI with console programs since they interact with the user in two very dissimilar ways, and the console can lock up the GUI if you're not careful. Instead consider going all console or all GUI.
If you go all GUI, one possible solution is to create a GUI that is similar to what you're already doing with user name and PIN number:
Give your GUI JTextFields for the user to input his data.
Add a "Calculate" JButton
In the button's ActionListener, extract the data from the JTextFields, convert any Strings to numbers that need converting, calculate your value and display it in another JTextField or JLabel.
Other side recommendations:
Don't call deprecated methods since they're deprecated for a good reason. Instead the Java API will usually tell you what alternatives to use.
Avoid over-use of static variables and methods, since this leads to rigid code that is difficult to test or enhance.
Try to give your variables names that have meaning so that your code becomes "self-commenting".
Your log-in window should be a modal dialog of some type, such as a modal JDialog, not a JFrame, since
Closing it will not close the entire GUI
It will prevent interacting with the main GUI until it has been fully dealt with.

Event call doesn't work with key bind or click - what's the logical error?

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

Java cant write in a .txt

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

Categories