I have a jTextArea that is filled with information that the program gives out, however, when i call the .print(); method, it prints 2 blank pages, it displays the popup and everything as other information shows on in the internet, I assume it does "see" the data in the text area since it wants to print two pages, but the problem is the pages just come out blank, any ideas what i'm doing wrong?
try {
boolean complete = txaMainOutput.print();
if(complete)
{
JOptionPane.showMessageDialog(null, "Done Printing", "Information", JOptionPane.INFORMATION_MESSAGE);
} else
{
JOptionPane.showMessageDialog(null, "Printing", "Printer", JOptionPane.ERROR_MESSAGE);
}
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(null, "An Error has occured, looks like we could not print");
}
https://gyazo.com/376958811a5fd9c5356843d8bf83c36f
After Playing around with the code, I found that creating a new JTextArea, saving all the Origianal TextArea data to a string then setting the new TextArea to that string, and then printing it will resolve the problem of blank pages.
String YourString = "Line 1 \nLine 2 \nLine 3" //define and set contents of your string - remember about formating with \n if you want to have it split on lines
JTextArea YourTextArea = new JTextArea(); //define new Swing JtextArea
YourTextArea.setLineWrap(true); //set line wrap for YourTextArea - this will prevent too long lines to be cut - they will be wrapaed to next line
YourTextArea.append(YourString); //append YourString to YourTextArea
YourTextArea.print(); //this will display print dialog that will lead you to print contents of YourTextArea so in efect contents of YourString
Related
I am new to Java
I created a conversion software for metric units and now I want to create new window for logging the output of converted units from one Window text areas into one text area in another window Picture of the application
Both Windows are one application
What code would I need to put in there to display this in another window text area
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double numCM,sumCM;
double numKM,sumKM;
double numMIL,sumMIL;
try {
//startCM//
numCM = Double.parseDouble(textFieldenter.getText());
sumCM = numCM*100;
textFieldcm.setText(Double.toString(sumCM));
//endCM//
//startKILOMETERS//
numKM = Double.parseDouble(textFieldenter.getText());
sumKM = numKM*0.001;
textFieldkm.setText(Double.toString(sumKM));
//endKILOMETERS//
//startMILES//
numMIL = Double.parseDouble(textFieldenter.getText());
sumMIL = numMIL*0.000621;
textFieldmil.setText(Double.toString(sumMIL));
//endMILES//
}
catch (Exception e1) {
JOptionPane.showInternalMessageDialog(btnConvert, "Value etered is incorrect");
}
}
});
You can use the method JTextField.getText() over your JTextFields and store its value into a String variable, then pass it to the JTextArea using the method append(String str) and put a line break at the end with /n
Read the API for these classes to learn more about its methods and how to use them Java API
It would be something like this
String record = "";
record = textFieldcm.getText()+" "+textFieldkm.getText()+" "+textFieldmil.getText();
JTextArea.append(record+"\n");
I am trying to create a console like function for some software. I have the output formatted as I want but only for console output using System.out.println. I am trying to get some form of text in the jtextarea. I have tried using .setText() and .append() yet had no lucky with either. I was wondering if anyone could help me spot why it's not working? My application uses 2 forms, Any help is appreciated as always..
Form2 f2 = new Form2();
f2.openMe(comboOne.getSelectedItem().toString());
form2 code is as follows:
public void openMe(String message) {
System.out.println("Console Output");
System.out.println("---------------------------");
System.out.println("Printer selected: "+ message);
System.out.println("\n");
//ta.setText(message);
ta.append("hi");
}
i am working on a project where i have to display a set of records then the user can select 1 or more of these records to move them to another set.
i think the most appropiate componenet to use is Checkboxes. my probelm is that i cant add the check boxes to the frame automatically while reading the file. i added a panel, and added the check box but it still doesnt appear after using paint, or updateUI.
this is my code:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8"));
String line = reader.readLine();
String text = "";
while (line != null) {
text += line;
line = reader.readLine();
}
ArrayList<String> records = new ArrayList<String>(Arrays.asList(text.split("")));
for(String rec: records){
resPanal.add(new JCheckBox(rec));
}
resPanal.updateUI();
the number of records is not constant, so i need a way to add the components = to the number of records found.
i am open to other suggestions that can help other than check boxes
for anyone interested:
i tried what #TerryStorm suggested in a small program with only a button, and each time the button is clicked a box is added
private void addCBActionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox box=new JCheckBox("add");
box.setVisible(true);
jPanel1.add(box);
jPanel1.updateUI();
}
I have a problem about creating a textfile with the name I want.
I want to create a textfile named : 'username' Subjects.
private void saveSubjects(){
RegisterFrame r = new RegisterFrame();
String username = r.txtUser.getText();;
try{
FileWriter f = new FileWriter(username + "" + "Subjects" + ".txt", true);
String subjects[] = lstSubjects.getItems();
for(int i = 0; i<subjects.length; i++){
f.write(subjects[i] + "\r\n");
}
f.close();
JOptionPane.showMessageDialog(null, "Data saved!", "Data Saved", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Nothing Inputted!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
I want to get the username from RegisterFrame as it is inputted there but it's not working.
I know it's a simple thing but I'm still a beginner in this. How can I solve this?
Thanks in advance
try this:
String username = r.txtUser.getText();
System.out.println("The loaded username is: " + username);
then you will see where your problem is : writing into the file OR getting the username text.
If the problem is in getting the text, consider other way of getting it or modify the question by removing the file write part and specifiing the username getting part.
Otherwise, IDK where the error is.
BTW: how is it not working? the file is not created at all? do you see any errors? the file has wrong name? please specify
Your code for writing the file seems to be fine. Based on your code I tried this which worked perfectly:
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("Subjects.txt", true);
String subjects[] = {"subject1", "subject2"};
for (String subject : subjects) {
f.write(subject + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(f);
}
}
I'd say your problem is elsewhere.
Please note that best practice dictates that Closeable objects such as FileWriter should be closed in a finally block
Assuming new RegisterFrame() starts up a GUI window, the issue is your code runs before you have a chance to type in your name. Instead you need to use event listeners to capture the contents of text fields, otherwise the code to get the name runs immediately after the window opens, long before you have a chance to type anything in.
The timeline is like this:
RegisterFrame starts a new thread to display the GUI without blocking your code
Your code immediately pulls "" from txtUser, which is of course empty
Now you type your name in
Nothing happens, because nothing in your code is paying attention to that action
Instead, it should be:
RegisterFrame starts a new thread to display the GUI without blocking your code
The method returns, or starts doing work that isn't dependent on the GUI
Now you type your name in
An event listener is triggered from the new thread, and the associated action to get the name and write to a file is executed
You have to decide what sort of listener makes sense for your use case, for instance you might want to wait until the user clicks a button (that says "Submit" or "Write File" for instance) and register an ActionListener on that button. Then you put your username polling and file writing behavior in that action* and you're golden!
*I should add that in truth you want to do as little as possible in ActionListeners, and it would be better to check if the username is not empty, then pass the actual work off to another thread, for instance with a SwingWorker, but for your purposes I suspect it will be alright to not worry about that.
I have created a text file in which to store some variables which are taken from text fields. But in order to submit new variables to this text file, I need to close my program and reopen it. The dispose(); command closes the JFrame taking me to my main menu but upon opening the menu again and submitting different values, the values from the previous time have been resubmitted. Is there a simple way to amend this?
Here is my write to .txt code:
public class writeto {
static String data = AddProperty.inputdata;
BufferedWriter out;
public writeto(){
try{
out = new BufferedWriter(new FileWriter("writeto.txt", true));
out.write(data);
out.newLine();
out.close();
}catch(IOException e){
System.out.println("you have an error" + e);
}
}
}
and where the method is called in my addproperty class
submitproperty.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
housenumber1 = houseNumber.getText();
streetname1 = streetName.getText();
town1 = town.getText();
postcode1 = postcode.getText();
beds1 = beds.getText();
price1 = price.getText();
type1 = type.getText();
inputdata = housenumber1 + " " + streetname1 + " " + town1 + " " +
postcode1 +" " + beds1 + " " + price1 + " " + type1;
writeto write = new writeto();
dispose();
}
});
}
From your menu you should always create a new JFrame with new widgets (like text fields). A new text field has no content, if you show a text field again, it will still display it's previous content.
Additional remarks:
Please use standard naming conventions - not only when you show code to others. In your case: class names shall start with a capital letter, camel-case notation is preferred (writeto -> WriteTo)
The writeto class abuses the constructor. The code in your constructor does not create an writeto object but dumps some strings to a file. Put this kind of code to a method, not to a constructor.
The BufferedWriter will not be closed if an exception occurs. Look around at stackoverflow, a lot of questions/answers show the correct io-closeing pattern
disposing the jframe is a risk - the code is executed after pressing a button (correct?), inside a method on a button that is displayed on the frame (correct?). In that case the button may be disposed while a method on the button object is still executed.. Try setVisible(false) if you just want to hide the JFrame (like "close the dialog")
You would benefit greatly from using a database as opposed to a text file. Further your question displays a fundamental lack of knowledge of not only Swing, but basic CRUD (Create, Read, Update, Delete) functionality.
To answer your question you can clear your text field with textField1.setText("");
I would read up on using a database for storing data. It will make life much easier for you.