Clearing a JTextArea
Ok, here's a problem I couldn't quite find by searching (though I found some sort of connected). In my program here, I have an editable JTextArea. I want to have a clear button on my form, but I just can't get the TextArea to clear. I know there's no setText, just appendText. It seems like it should be simple, I just don't get it, can someone help please? Thanks for your time
--Jon Baumann
Sorry about that last suggestion
It's friday and not all with it,
I never looked at the start properly
I am using TextArea class and not JTextArea which does have the setText() method
But i just looked up the class documentation for JTextArea and does it not inherit the setText() method
from textComponent????
Similar Messages
-
I know this may be something that is very obvious, but for some reason I cannot clear the text I have written to a JTextArea. I have tried removeAll(), I have tried selectAll() and then removeAll(), and some other things, but nothing seems to work. I would appreciate any advice that someone can give me! :) (Thanks in advance).
Sure, do that if you want to induce a compile time error.
Try setText(""); -
How do I clear a JTextArea.
well, as the title says.
The only info I can find in my docs is selectALL but then what do I do with it.
I've got a search result updating the JTextArea and I want to clear it after each search.
cheers ;)now i really feel like an idiot.
cheers.
I won't tell you how long i've been trying to work that out.No need to feel ashamed; I know those situations: after hours and hours of
hacking and trying, you simply have to give up because during those tedious
hours you've developed nothing but a blind spot for the obvious solution ;-)
kind regards,
Jos -
Hi,
I am trying to clear the JTextArea when the user clicks on a button. I could not find a clear command in the JavaDocs but I did try the following:
Is there a better way to do this or a different object.
Thanks,
Steve
String abc = " ";
int xcoord = 0;
int ycoord = 40;
msgout.replaceRange(abc, xcoord, ycoord);use a setText method.
JTextArea.setText(String);
if you wanted to make it blank...
String str = "";
JTextArea.setText(str); -
JTextArea not clearing properly
Hi all,
What is the proper way to clear a JTextArea of all text?
Right now, I am doing
String sendText = currentMessage.getText();But for some reason, a carriage return remains in the JTextArea. I have tried moving the carriage return, etc, but nothing is working. Is this a bug in Java?
I am using JDK 1.4.2_06
MaxFound the solution! The code for processing the key event should go to keyReleased() method instead of keyPressed() methodThe default Action for the Enter key is to insert a new line character into the text area.
If you don't want this Action to occur, then you should replaced the default with your own Action. This is the recommended approach instead of using a KeyListener. For more information see the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings. -
Hi,
I want to clear the JTextArea. I tried it with jtextarea.replaceRange( "",0,?). My Question: how get I the last index? Please help.or as you said
jtextarea.replaceRange("",0,jtextarea.getText().length());
but previous is better -
Hello,
I have a JTextArea with linewrapping. I call setWrapStyleWord (true) to make sure lines won't be wrapped arbitrarily inside words. My JTextArea is Ok and the word aren't cut.
When i call my printing method, i can't keep the JTextArea text format !
I would like to call the print method "g.drawString" for each "line" of the JTexArea but although the JtextArea content is linewrapped there is no method like "jtextarea.getLine()" withc return a string.
a exemple may be most clear :-)
My JTextArea :
Java is cool but
I can't do what I
want :-)
My print result :
Java is cool but I can't do what I want :-)
somebody can help me ?The question is, when the printing of TextArea comes out without break, does it make your print look worse? Why did you want line breaking, by the way?
My understanding is lineWrap in TextArea is purely for viewing purposes, which is totally dependent on the current graphics device. So if Java finds out the whole text can be "viewed" nicely on printer without breaking, then that's what you get. The text breaks when the whole line doesn't fit viewing screen, so if it fits, why bothers?
Otherwise, if there's compelling reason you need line breaking, one (quite easy) way is to implement line breaking yourself by subclassing JTextArea. Then the text lines will be readily available. -
Need a little help with a Jbutton not working out the way I planned
The following code is to fulfill an assignment I am working on. The problem I am having is with the btnCalc. For some reason when the button is used, the results I get is from another button. I think the variables are set right for the program to function properly but I am really hung up on this. Do anyone have any suggestions?
import java.awt.*; //Contains classes for creating GUI
import java.awt.event.*; //For listener events
import javax.swing.*; // Imports the Main Swing Package
import javax.swing.event.*;
import javax.swing.text.*; // Positions text box
import java.text.NumberFormat; // For number format such as currency
import java.text.*; // Imports the Main Text Package
import java.util.*; // Utility Package
public class MPC extends JFrame implements ActionListener //Creates Class for MPC
//double dblLoanAmount, dblInterestRate, dblMonthlyPayment;
TextField txtTotalMort;
//JButton fixRates = new JButton("Choose Fixed Rates");
JLabel lblTotalMort = new JLabel("How much is the loan?"); // Label for dblLoanAmount amount
JTextField txtYears = new JTextField(10);
JLabel lblPayment = new JLabel("Your monthly payment is "); // Label for Payment
JTextField txtPayment = new JTextField(10);
JLabel lblYears = new JLabel("How many years?");
// add(lblYears);
JTextField txtYearsInput = new JTextField(10);
//a dd(txtYears);
JLabel lblInterestRate = new JLabel("What is the interest rate?");
//add(lblInterestRate);
JTextField txtInterestRate = new JTextField(10);
//add(txtInterestRate);
//JLabel lblPayment = new JLabel("Your monthly payment is:");
//add(lblPayment);
//JTextField txtPayment = new JTextField(10);
//txtPayment.setEditable(false);
//add(txtPayment);
JButton btnCalc = new JButton("Calculate");
//add(btnCalc);
//btnCalc.addActionListener(this);
JButton year7InterestRateBtn = new JButton("7 years at 5.35%"); // Mortgage Term and Interest Rate
JButton year15InterestRateBtn = new JButton("15 years at 5.50%");
JButton year30InterestRateBtn = new JButton("30 years at 5.75%");
JButton reset = new JButton("Clear All");
JTextArea boxSpace = new JTextArea(100,200); // Morgtage table size
JScrollPane scroll = new JScrollPane(boxSpace); // ScrollPane
public MPC() // Method
super("MPC"); // Frame Title
JMenuBar mb = new JMenuBar(); // Menu Bar
setJMenuBar(mb);
setSize(325, 500); // Frame Size
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); //Grid box configuration
Container grid = getContentPane();
grid.setLayout(new GridLayout(8,2,8,8)); // Grid Layout
pane.add(grid); // Adds grid
pane.add(scroll); // Adds scrollPane
grid.setBackground(Color.white);
Setting color of text and backgrounds
txtYears.setBackground(Color.white);
txtYears.setForeground(Color.black);
txtYears.setFont(new Font("Arial", Font.PLAIN, 10));
txtPayment.setBackground(Color.white);
txtPayment.setForeground(Color.black);
txtPayment.setFont(new Font("Arial", Font.PLAIN, 10));
boxSpace.setBackground(Color.white);
boxSpace.setForeground(Color.black);
boxSpace.setFont(new Font("Arial", Font.PLAIN, 10));
grid.add(lblYears);
grid.add(txtYearsInput);
grid.add(lblInterestRate);
grid.add (txtInterestRate);
grid.add(lblTotalMort); // Adds the Mortgage Amount Label
grid.add(txtYears); // Adds the Mortgage Amount Text Field
grid.add(lblPayment); // Adds the Payment Label
grid.add(txtPayment); // Adds the Monthly Payment Text Field
txtPayment.setEditable(false); // Disables editing in this Text Field
grid.add(btnCalc);
grid.add(year7InterestRateBtn); // Adds 1st Loan and Rate Button
grid.add(year15InterestRateBtn); // Adds 2nd Loan and Rate Button
grid.add(year30InterestRateBtn); // Adds the Exit Button
grid.add(reset); // Adds the New Calc Button
setContentPane(pane); // Enables the Content Pane
setVisible(true); // Sets JPanel to be Visable
reset.addActionListener(this); // Adds Action Listener to the New Calc Button
txtYearsInput.addActionListener(this);
txtInterestRate.addActionListener(this);
btnCalc.addActionListener(this);
year7InterestRateBtn.addActionListener(this); // Adds Action Listener to the 1st loan Button
year15InterestRateBtn.addActionListener(this); // Adds Action Listener to the 2nd loan Button
year30InterestRateBtn.addActionListener(this); // Adds Action Listener to the 3rd loan Button
txtYears.addActionListener(this); // Adds Action Listener to the Mortgage Amount Text Field
txtPayment.addActionListener(this); // Adds Action Listener to the Monthly payment Text Field
public void actionPerformed(ActionEvent e) // Tests to Verify Which Button is Pressed
Object command = e.getSource(); // Enables command to get data
int intYears = 0; // Declares intYears
double dblLoanAmount, dblInterestRate, interestRate, intRate;
if (command == year7InterestRateBtn) // Activates the 1st Loan Button
intYears = 0; // Sets 1st value of Array
if (command == year15InterestRateBtn) // Activates the 2nd Loan Button
intYears = 1; // Sets 2nd value of Array
if (command == year30InterestRateBtn) // Activates the 3rd Loan Button
intYears = 2; // Sets 3rd value of Array
if (command == btnCalc)
//dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
//interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
//int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
int months = Integer.parseInt(txtYearsInput.getText() )* 12;
dblLoanAmount = 0; // Declares and Initializes dblLoanAmount
dblInterestRate = 0; // Declares and Initializes dblInterestRate
double [][] dblTrmLoanRate = {{7, 5.35}, {15, 5.50}, {30, 5.75},}; // Array Data for Calculation
try
dblLoanAmount = Double.parseDouble(txtYears.getText()); // Gets user input from txtYears Text Field
catch (NumberFormatException nfe) // Checks for correct user input
JOptionPane.showMessageDialog(null, "You must enter a valid number.", "MPC", JOptionPane.INFORMATION_MESSAGE);
return;
interestRate = dblTrmLoanRate [intYears][1];
//dblInterestRate=interestRate;
intRate = (interestRate / 100) / 12; // Calculates Interst Rate
double intYearsMonths = dblTrmLoanRate [intYears] [0]; // Calculates Loan Term in Months
int months = (int)intYearsMonths * 12; // Devides by months
double interestRateMonthly = (intRate / 12); // Devides Rate
double payment = dblLoanAmount * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculates monthly payment
double dblRmnLoan = dblLoanAmount; //Left over balance
double txtPaymentInterest = 0; // Payment
double txtPaymentPrincipal = 0; // Payment of principal
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US); // Curreny format
txtPayment.setText(currency.format(payment));
boxSpace.setText("Month\tPrincipal\tInterest\tBalance Left\n");
for (;months > 0 ; months -- )
txtPaymentInterest = (dblRmnLoan * intRate);
txtPaymentPrincipal = (payment - txtPaymentInterest); // Calculates monthly payment
dblRmnLoan = (dblRmnLoan - txtPaymentPrincipal);
boxSpace.setCaret (new DefaultCaret()); // Scroll position
boxSpace.append(String.valueOf(months) + "\t" + // Table data
currency.format(txtPaymentPrincipal) + "\t" +
currency.format(txtPaymentInterest) + "\t" +
currency.format(dblRmnLoan) + "\n");
if(command == reset)
Clears fields
txtYearsInput.setText(null);
txtInterestRate.setText(null);
txtYears.setText(null);
txtPayment.setText(null);
boxSpace.setText(null);
public static void main(String[] args) //This is the signature of the entry point of all the desktop apps
new MPC();
}This portion to be exact. All the buttons work for me except this one. I need to calculate user input and also use the fixed data that can be found in the dblTrmLoanRate array. When I choos to use user input instead, the program either crashes or for some reason uses the year7InterestRateBtn instead.
if (command == btnCalc)
//dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
//interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
//int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
int months = Integer.parseInt(txtYearsInput.getText() )* 12;
I was going to leave out the remed portion but thought it might help you with the navigation. I am sorry I did not use code tags, but I am going to go find out what those are and use them in the future. -
Accessing string from other classes
Sorry if this seems simple to you, but i'm having problems accessing four string that are declared and used in my public class from another class.
I've tried declaring the strings public but it still says 'cannot resolve symbol' when i try to compile.
Help much appreciated.
fightspamYep, heres my code(sorry if it's a bit untidy):
//Zimmerman M3 email client.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class where extends JFrame implements ActionListener
private JLabel path;
private JTextField pathText;
private String pathFile;
private JButton save;
File outputFile = new File(pathFile);
public where()
super("Save Email");
Container f=getContentPane();
f.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
f.setBackground(Color.lightGray);
path = new JLabel("Path: ");
f.add(path);
pathText = new JTextField(20);
f.add(pathText);
save = new JButton("Save");
f.add(save);
this.setSize(300, 100);
public void actionPerformed(ActionEvent q)
pathFile = pathText.getText();
try
FileWriter out = new FileWriter(outputFile);
out.write(zimmernorm.toFile);
out.write(zimmernorm.fromFile);
out.write(zimmernorm.subjectFile);
out.write(zimmernorm.bodyFile);
out.close();
catch(IOException err)
System.exit(0);
class about extends JFrame
private JLabel title;
public about()
super("About Zimmerman M3");
Container d=getContentPane();
d.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
d.setBackground(Color.lightGray);
title = new JLabel("Zimmerman M3 by Louis Goddard, 2003");
d.add(title);
this.setSize(246, 62);
class newmail extends JFrame implements ActionListener
public static String toFile, fromFile, subjectFile, bodyFile;
public JTextField To, From, Subject;
private String toBuffer, fromBuffer, subjectBuffer, bodyBuffer;
private JButton send, clear;
private JTextArea Body;
private JLabel toLabel, fromLabel, subjectLabel;
private JMenuBar mb;
private JMenu File, Edit;
private JMenuItem New, Sender, Copy, Paste, About;
public newmail()
super("New Email");
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
c.setBackground(Color.lightGray);
//<MENU STUFF!!!>
mb = new JMenuBar();
File = new JMenu("File");
Edit = new JMenu("Edit");
New = new JMenuItem("New");
Sender = new JMenuItem("Save");
Copy = new JMenuItem("Copy");
Paste = new JMenuItem("Paste");
File.add(New);
New.addActionListener(this);
New.setActionCommand("1");
File.add(Sender);
Sender.addActionListener(this);
Sender.setActionCommand("2");
Edit.add(Copy);
Copy.addActionListener(this);
Copy.setActionCommand("3");
Edit.add(Paste);
Paste.addActionListener(this);
Paste.setActionCommand("4");
mb.add(File);
mb.add(Edit);
setJMenuBar(mb);
//</MENU STUFF!!!>
toLabel = new JLabel("To: ");
c.add(toLabel);
To = new JTextField(35);
c.add(To);
fromLabel = new JLabel("From: ");
c.add(fromLabel);
From = new JTextField(35);
c.add(From);
subjectLabel = new JLabel("Subject:");
c.add(subjectLabel);
Subject = new JTextField(35);
c.add(Subject);
Body = new JTextArea(12,40);
c.add(Body);
send = new JButton("Send");
c.add(send);
clear = new JButton("Clear");
c.add(clear);
clear.addActionListener(this);
clear.setActionCommand("6");
this.setSize(459, 364);
public static void main(String []args)
JFrame.setDefaultLookAndFeelDecorated(true);
new newmail().show();
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
if (s == ("1"))
new newmail().show();
else if (s == ("2"))
new where().show();
toFile = To.getText();
fromFile = From.getText();
subjectFile = Subject.getText();
bodyFile = Body.getText();
else if (s == ("3"))
bodyBuffer = Body.getSelectedText();
toBuffer = To.getSelectedText();
fromBuffer = From.getSelectedText();
subjectBuffer = Subject.getSelectedText();
else if (s == ("4"))
Body.setText(bodyBuffer);
To.setText(toBuffer);
From.setText(fromBuffer);
Subject.setText(subjectBuffer);
else if (s == ("5"))
new about().show();
else if (s == ("6"))
To.setText("");
From.setText("");
Subject.setText("");
Body.setText("");
public class zimmernorm extends JFrame implements ActionListener
public String toFile, fromFile, subjectFile, bodyFile;
private String toBuffer, fromBuffer, subjectBuffer, bodyBuffer;
private JMenuBar mb;
private JMenu File, Help, View;
private JMenuItem New, About, Inboxmenu, Outboxmenu, Savedmenu;
public zimmernorm()
super("Zimmerman M3");
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
c.setBackground(Color.lightGray);
//<MENU STUFF!!!>
mb = new JMenuBar();
File = new JMenu("File");
View = new JMenu("View");
Help = new JMenu("Help");
New = new JMenuItem("New");
About = new JMenuItem("About");
Inboxmenu = new JMenuItem("Inbox");
Outboxmenu = new JMenuItem("Outbox");
Savedmenu = new JMenuItem("Saved");
File.add(New);
New.addActionListener(this);
New.setActionCommand("1");
Help.add(About);
About.addActionListener(this);
About.setActionCommand("5");
View.add(Inboxmenu);
Inboxmenu.addActionListener(this);
Inboxmenu.setActionCommand("7");
View.add(Outboxmenu);
Outboxmenu.addActionListener(this);
Outboxmenu.setActionCommand("8");
View.add(Savedmenu);
Savedmenu.addActionListener(this);
Savedmenu.setActionCommand("9");
mb.add(File);
mb.add(Help);
mb.add(View);
setJMenuBar(mb);
//</MENU STUFF!!!>
this.setSize(1024, 768);
this.setDefaultCloseOperation( EXIT_ON_CLOSE );
public static void main(String []args)
JFrame.setDefaultLookAndFeelDecorated(true);
new zimmernorm().show();
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
if (s == ("1"))
new newmail().show();
else if (s == ("5"))
new about().show(); -
Cannot find symbol error - Constructor
Hi Folks,
i am getting the following errors when the code is compiled. Please help! The code is as below. This code is for the laptop configuration. I have 2 classes, computer.java and Wclass.java with the WIn.java(main class)
Also, how do i read the input from the radiobutton in the action performed
WClass.java:13: cannot find symbol
symbol : constructor Computer()
location: class Computer
Computer computer = new Computer();
^
WClass.java:181: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,java.lang.String)
Out.append("Computer Configuration for %s\n", computer.getName()
^
WClass.java:182: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("Processor:\t\t\t \n", computer.getProcessor());
^
WClass.java:183: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("HardDisk: \t\t\t \n", computer.getHarddisk());
^
WClass.java:184: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("RAM: \t\t\t \n", computer.getRam());
^
WClass.java:185: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("ProcessorSpeed:\t\t \n", computer.getProcessorSpeed(
^
WClass.java:186: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("Printer: \t\t\t \n", computer.getPrinter());
^
WClass.java:187: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("Inbuilt Wireless LAN: \t\t\n", computer.getWireless(
^
WClass.java:188: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("Floppy(External):\t\t \n", computer.getFloppy());
^
WClass.java:189: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("DVD Writer:\t\t\t \n", computer.getDVD());
^
WClass.java:190: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
Out.append("CD Writer :\t\t\t \n", computer.getCdw());
^
WClass.java:191: cannot find symbol
symbol : method getTotal()
location: class Computer
Out.append("Total \t\t\t \n", computer.getTotal());
^
12 errors
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
public class Computer
private String name;
private float Processor_cost;
private float total_cost;
private float harddrive_cost;
private float ram_cost;
private float psspeed_cost;
private float printer_cost;
private float wireless_cost;
private float floppy_cost;
private float dvd_cost;
private float cdwriter_cost;
float pc[] = {1000f, 700f, 650f, 1200f};
float hd[] = {0, 100f, 150f};
float ps[] = {0, 100f, 125f};
float ram[] = {0, 60f};
float aa[] = {50f, 110f};
float drive[] = {110f, 220f, 20};
double T = 0.0;
public Computer(String Cname, int pcost, float tcost, int hcost, float rcost,
int pscost, float prcost, float wcost, float fcost, float dvdcost, float cdrwcost)
name = Cname;
Processor_cost = pc[pcost];
total_cost = tcost;
harddrive_cost = hd[hcost];
ram_cost = rcost;
psspeed_cost = ps[pscost];
printer_cost = prcost;
wireless_cost = wcost;
floppy_cost = fcost;
dvd_cost = dvdcost;
cdwriter_cost = cdrwcost;
public void setName(String Cname)
name = Cname;
public String getName()
return name;
public void setProcessor(int pcost)
Processor_cost = pc[pcost];
public float getProcessor()
return Processor_cost;
public void setHarddisk(int hcost)
harddrive_cost = hd[hcost];
public float getHarddisk()
return harddrive_cost;
public void setRam(int rcost)
ram_cost = rcost;
public float getRam()
return ram_cost;
public void setProcessorSpeed(int pscost)
psspeed_cost = ps[pscost];
public float getProcessorSpeed()
return psspeed_cost;
public void setPrinter(float prcost)
printer_cost = prcost;
public float getPrinter()
return printer_cost;
public void setWireless(float wcost)
wireless_cost = wcost;
public float getWireless()
return wireless_cost;
public void setFloppy(float fcost)
floppy_cost = fcost;
public float getFloppy()
return floppy_cost;
public void setDVD(float dvdcost)
dvd_cost = dvdcost;
public float getDVD()
return dvd_cost;
public void setCdw(float cdrwcost)
cdwriter_cost = cdrwcost;
public float getCdw()
return cdwriter_cost;
//public String show()
// String out;
//return out.format();
public double Total()
T = getProcessor() + getHarddisk() + getRam() + getProcessorSpeed() + getPrinter() + getWireless() + getFloppy() + getDVD() + getCdw();
return T;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class WClass extends JFrame implements ActionListener
Computer computer = new Computer();
private JPanel P1;
private JPanel P2;
private JButton submit;
private JButton clear;
private JTextArea Out;
private JLabel name;
private JTextField Custname;
private JComboBox processor;
private JComboBox harddrive;
private JRadioButton ram1;
private JRadioButton ram2;
private JRadioButton ram3;
private JPanel radiopanel;
private ButtonGroup radiogroup;
private JComboBox processorsd;
private JLabel L1;
private JCheckBox printer;
private JCheckBox lan;
private JLabel L2;
private JCheckBox fpy;
private JCheckBox dvd;
private JCheckBox cdrw;
private JLabel L3;
private JLabel L4;
private JLabel L5;
private JLabel L6;
private JLabel L7;
private JLabel L8;
private JLabel L9;
private Container c;
int row;
float prncost = 50f;
float wlan = 110f;
float fppy = 110f;
float dvdw = 220f;
float cdw = 20f;
public WClass()
super("Laptop Configuration");
P1 = new JPanel();
P1.setLayout(new GridLayout(10,2,5,10));
P2 = new JPanel(new BorderLayout());
name = new JLabel("Customer Name");
P1.add(name);
Custname = new JTextField(10);
Custname.addActionListener(this);
P1.add(Custname);
L3 = new JLabel("Processor");
P1.add(L3);
String p[] = {"Pentium 4", "Celeron", "AMD", "Intel Centrino"};
processor = new JComboBox(p);
processor.setMaximumRowCount(3);
P1.add(processor);
L4 = new JLabel("Hard Disk");
P1.add(L4);
String h[] = {"30 GB", "40 GB", "60 GB"};
harddrive = new JComboBox(h);
harddrive.setMaximumRowCount(2);
P1.add(harddrive);
L5 = new JLabel("RAM");
P1.add(L5);
radiopanel = new JPanel();
radiopanel.setLayout(new GridLayout(1,2));
ram1 = new JRadioButton("256 MB", true);
ram2 = new JRadioButton("512 MB", false);
radiopanel.add(ram1);
radiopanel.add(ram2);
radiogroup = new ButtonGroup();
radiogroup.add(ram1);
radiogroup.add(ram2);
P1.add(radiopanel);
L6 = new JLabel("Processor Speed");
P1.add(L6);
String ps[] = {"1.8 GHz", "2.2 GHz", "2.8 GHz"};
processorsd = new JComboBox(ps);
processorsd.setMaximumRowCount(2);
P1.add(processorsd);
L1 = new JLabel("Additional Accessories");
P1.add(L1);
printer = new JCheckBox("Ink Jet Printer");
lan = new JCheckBox("Inbuilt Wireless LAN");
P1.add(printer);
L7 = new JLabel("");
P1.add(L7);
P1.add(lan);
L2 = new JLabel("Drives");
P1.add(L2);
fpy = new JCheckBox("Floppy(External)");
dvd = new JCheckBox("DVD Writer");
cdrw = new JCheckBox("CD Writer");
P1.add(fpy);
L8 = new JLabel("");
P1.add(L8);
P1.add(dvd);
L9 = new JLabel("");
P1.add(L9);
P1.add(cdrw);
c = getContentPane();
add(P1, BorderLayout.NORTH);
submit = new JButton("Submit");
clear = new JButton("Clear");
Out = new JTextArea(10,5);
P2.add(submit, BorderLayout.WEST);
P2.add(clear, BorderLayout.EAST);
P2.add(Out,BorderLayout.CENTER);
add(P2, BorderLayout.SOUTH);
public void actionPerformed(ActionEvent event)
if(event.getSource() == submit)
computer.setName(name.getText());
computer.setProcessor(processor.getSelectedIndex());
computer.setHarddisk(harddrive.getSelectedIndex());
//computer.setRam(radiogroup.getAccessibleContext());
computer.setProcessorSpeed(processorsd.getSelectedIndex());
if(printer.isSelected())
computer.setPrinter(prncost);
if(lan.isSelected())
computer.setWireless(wlan);
if(fpy.isSelected())
computer.setFloppy(fppy);
if(dvd.isSelected())
computer.setDVD(dvdw);
if(cdrw.isSelected())
computer.setCdw(cdw);
Out.append("Computer Configuration for %s\n", computer.getName());
Out.append("Processor:\t\t\t \n", computer.getProcessor());
Out.append("HardDisk: \t\t\t \n", computer.getHarddisk());
Out.append("RAM: \t\t\t \n", computer.getRam());
Out.append("ProcessorSpeed:\t\t \n", computer.getProcessorSpeed());
Out.append("Printer: \t\t\t \n", computer.getPrinter());
Out.append("Inbuilt Wireless LAN: \t\t\n", computer.getWireless());
Out.append("Floppy(External):\t\t \n", computer.getFloppy());
Out.append("DVD Writer:\t\t\t \n", computer.getDVD());
Out.append("CD Writer :\t\t\t \n", computer.getCdw());
Out.append("Total \t\t\t \n", computer.getTotal());
if(event.getSource() == clear)
Custname.setText("");
Out.setText("");
ram1 = new JRadioButton("256 MB", true);
c.setLayout(new GridLayout(10,2,5,10));
import javax.swing.JFrame;
public class Win
public static void main(String args[])
WClass window = new WClass();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
window.setSize( 500,550);
window.setVisible( true);
}When you make a class, the compiler often gives you an empty constructor. The Computer class for example would have the following constructor.
public Computer(){ }This means you can write code, as you did in the third program like the following.
Computer c = new Computer();However if you write your own constructor such as:
public Computer(String Cname, int pcost, float tcost, int hcost, float rcost,
int pscost, float prcost, float wcost, float fcost, float dvdcost, float cdrwcost)Then an empty constructor is not supplied. So you must write your own if you want one or you must use the one that you created.
You can create as many constructors as you like, so long as they all take different arguments -
Overlap of components in the panel
This is for an application which computes the total cost of configured laptop.
The main window has 2 panels. The top panel should have a label, and textfield. 3 comboboxes, radiobuttton group, 2 check boxes. I am not able to display the components next to each other. They overlap in the top panel.(This panel has a GridLayout) The code is as follows(does not have all the components yet)
The 2nd panel has a 2 buttons and textarea. Can anybody please help.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class WClass extends JFrame implements ActionListener
private Container pane;
private JPanel P1;
private JPanel P2;
private JButton submit;
private JButton clear;
private JTextArea Out;
private JLabel name;
private JTextField Custname;
private JComboBox processor;
private JComboBox harddrive;
int row;
public WClass()
super("Laptop Computer Configuration");
P1 = new JPanel();
P1.setLayout(new GridLayout(2,4));
P2 = new JPanel(new BorderLayout());
name = new JLabel("Customer Name");
add(name);
Custname = new JTextField(10);
Custname.addActionListener(this);
add(Custname);
String p[] = {"Pentium 4", "Celeron", "AMD", "Intel Centrino"};
processor = new JComboBox(p);
processor.setMaximumRowCount(3);
processor.addItemListener(
new ItemListener()
public void itemStateChanged(ItemEvent e)
if(e.getStateChange() == ItemEvent.SELECTED)
row = processor.getSelectedIndex();
add(processor);
String h[] = {"30 GB", "40 GB", "60 GB"};
harddrive = new JComboBox(h);
harddrive.setMaximumRowCount(2);
harddrive.addItemListener(
new ItemListener()
public void itemStateChanged(ItemEvent e)
if(e.getStateChange() == ItemEvent.SELECTED)
row = harddrive.getSelectedIndex();
add(harddrive);
add(P1, BorderLayout.NORTH);
submit = new JButton("Submit");
clear = new JButton("Clear");
Out = new JTextArea(10,5);
P2.add(submit, BorderLayout.WEST);
P2.add(clear, BorderLayout.EAST);
P2.add(Out,BorderLayout.CENTER);
add(P2, BorderLayout.SOUTH);
public void actionPerformed(ActionEvent event)
import javax.swing.JFrame;
public class Win
public static void main(String args[])
WClass window = new WClass();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
window.setSize( 500,400);
window.setVisible( true);
}It is not easy to read your code due to lack of formatting. When you post code you should highlight it and click the "code" button. This preserves the formatting.
I see some lines that say "add(whatever)". Shouldn't these be "P1.add(whatever)". In other words you want to be adding components to a panel rather than the base JFrame if I understand your requirement.. -
Using JTextArea - How do I clear it?
Hi all.
I have written a GUI program which transfers data from a method to a JTextArea/JScrollPane upon a button ActionEvent.
When I press the "Next Record" button I want to be able to clear the previous details held in this JTextArea before I print the new ones in it. The Same for going backwards through an array. Does anybody know how to do this?
Currently I am using the append method to add the returned String to my JTextArea. I have also tried using a replaceRange(String, int, int) method to clear the box before printing new details, but this isn't working properly as each Record in the array contains a different String length, so I can not enter the int values for each specific object.
Below is the code for the application, and I've highlighted where I have used the methods to add a String to the JTextArea. I'm declaring the class for the action event within creating the actionListener, but can seperate it out if people need to see it more clearly.
RECORDING CLASS ----------
package RecordingManagerGUI;
public class Recording
private String title, artist, genre;
public Recording (String theTitle, String theArtist, String theGenre)
title = theTitle;
artist = theArtist;
genre = theGenre;
public String getAlbum()
return title;
public String getArtist()
return artist;
public String getGenre()
return genre;
public String toString()
String s = "Title: " + title + "\nArtist: " + artist + "\nGenre: " + genre + "\n\n";
return s;
}MANAGER CLASS ---------------
package RecordingManagerGUI;
import java.util.*;
public class Manager
private Recording[] theRecordings;
private int numRecordings, maxRecordings, age;
private String managerName;
//Extending the Manager Class Instance Variables
private int current = 0;
private String record;
public Manager (String theName, int theAge, int max)
managerName = theName;
age = theAge;
maxRecordings = max;
numRecordings = 0;
theRecordings = new Recording[maxRecordings];
public boolean addRecording (Recording newRecording)
if (numRecordings == maxRecordings)
System.out.println("The store is full");
return false;
else
theRecordings[numRecordings] = newRecording;
numRecordings++;
return true;
public int nextRecording ()
if(current < numRecordings)
current += 1;
else
record = "You have reached the end of the Records"; //initialise the string if no records
return current;
public int previousRecording()
if(current > 1)
current -= 1;
else
record = "You have reached the start of the Records"; //initialise the string if no records
return current;
public String displayCurrent()
String displayRec = "";
displayRec += theRecordings[current-1];
return displayRec;
public void displayDetails()
System.out.println("Manager Name: " + managerName + ", " + age);
//public void displayRecordings()
// System.out.println("\nThe Recordings: ");
// for (int i = 0; i < numRecordings; ++i)
// System.out.println(theRecordings);
}RecordingManagerGUI CLASS ----------/*
*Need to add a Label which tells me when I have reached the end of the Records
package RecordingManagerGUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RecordingManagerGUI extends JFrame {
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
JButton nextRecord;
JButton previousRecord;
JLabel recordLabel;
JTextArea displayRecord;
Manager theManager;
public RecordingManagerGUI() {
//Create and set up the window.
super("Recording Manager Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Recording FooFighters = new Recording("The Colour and the Shape", "Foo Fighters", "Rock");
Recording BlindMelon = new Recording("Blind Melon", "Blind Melon", "Alternative Rock");
Recording JoeSatriani = new Recording("The Extremist", "Joe Satriani", "Instrumental Rock");
Recording PercySledge = new Recording("When a Man Loves a Woman", "Percy Sledge", "Soul");
Recording JustinTimberlake = new Recording("Justified", "Justin Timberlake", "Pop");
Recording BeyonceKnowles = new Recording("Dangerously in Love", "Beyonce Knowles", "R'n'B");
Recording TupacShakur = new Recording("2Pacalypse Now", "Tupac Shakur", "Hip Hop");
theManager = new Manager("Cathy", 42, 7);
theManager.addRecording(FooFighters);
theManager.addRecording(BlindMelon);
theManager.addRecording(JoeSatriani);
theManager.addRecording(PercySledge);
theManager.addRecording(JustinTimberlake);
theManager.addRecording(BeyonceKnowles);
theManager.addRecording(TupacShakur);
displayRecord = new JTextArea(10, 30);
displayRecord.setEditable(false);
JScrollPane recordScroll = new JScrollPane(displayRecord);
recordLabel = new JLabel("Record Details");
nextRecord = new JButton("Next Record");
nextRecord.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){theManager.nextRecording();displayRecord.append(theManager.displayCurrent());displayRecord.replaceRange(theManager.displayCurrent(), 0, 30);}}); //ADDING STRING TO JTEXTAREA
previousRecord = new JButton("Previous Record");
previousRecord.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){theManager.previousRecording();displayRecord.replaceRange(theManager.displayCurrent(), 0, 30);}}); //ADDING STRING TO JTEXTAREA
getContentPane().setLayout(new FlowLayout());
getContentPane().add(recordLabel);
getContentPane().add(recordScroll);
getContentPane().add(nextRecord);
getContentPane().add(previousRecord);
//Display the window.
pack();
setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
new RecordingManagerGUI();
}Would appreciate any help thanks. I'm not sure if I just need to create a new instance of the JTextArea upon the event which would hold the String information. If so I'm not really sure how to do this.I don't know, the Swing experts are in the Swing forum. but setText() is defined in TextComponent, which a JTextArea is.
-
How to clear two dimension array and content in JTextArea
hi all....
i have a problem to clear the counter in JTextArea..currently i design a program to store all the student details in two dimensian array...when i click "RESET"button..it will only reset the textarea..but can not clear the actual content inside the array..and when i click "Print Button" again..it's supposed nothing to display..but it displayed the thing which i previously entered......
so i think i need to clear the array...i use append to insert the text...,for this i also can not reset...
which the code is shown below :
txtArea.append(msg1);
the coding for reset area as below :
txtArea.setText("")
Anyone can help me?????
thks...How are you trying to reset the array?, you can just creat a new array.
Noah -
Need help with JTextArea and Scrolling
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
public class MORT_RETRY extends JFrame implements ActionListener
private JPanel keypad;
private JPanel buttons;
private JTextField lcdLoanAmt;
private JTextField lcdInterestRate;
private JTextField lcdTerm;
private JTextField lcdMonthlyPmt;
private JTextArea displayArea;
private JButton CalculateBtn;
private JButton ClrBtn;
private JButton CloseBtn;
private JButton Amortize;
private JScrollPane scroll;
private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
private JComboBox rateTermList;
double interest[] = {5.35, 5.5, 5.75};
int term[] = {7, 15, 30};
double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
int termInMonths, month, termLoop, monthLoop;
public MORT_RETRY()
Container pane = getContentPane();
lcdLoanAmt = new JTextField();
lcdMonthlyPmt = new JTextField();
displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
rateTermList = new JComboBox(rateTerm);
scroll = new JScrollPane(displayArea);
scroll.setSize(600,170);
scroll.setLocation(150,270);//DEFINE BUTTONS
CalculateBtn = new JButton("Calculate");
ClrBtn = new JButton("Clear Fields");
CloseBtn = new JButton("Close");
Amortize = new JButton("Amortize");//DEFINE PANEL(S)
keypad = new JPanel();
buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
keypad.add(new JLabel("Loan Amount$ : "));
keypad.add(lcdLoanAmt);
keypad.add(new JLabel("Term of loan and Interest Rate: "));
keypad.add(rateTermList);
keypad.add(new JLabel("Monthly Payment : "));
keypad.add(lcdMonthlyPmt);
lcdMonthlyPmt.setEditable(false);
keypad.add(new JLabel("Amortize Table:"));
keypad.add(displayArea);
displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
buttons.add(CalculateBtn);
buttons.add(Amortize);
buttons.add(ClrBtn);
buttons.add(CloseBtn);//ADD ACTION LISTENER
CalculateBtn.addActionListener(this);
ClrBtn.addActionListener(this);
CloseBtn.addActionListener(this);
Amortize.addActionListener(this);
rateTermList.addActionListener(this);//ADD PANELS
pane.add(keypad, BorderLayout.NORTH);
pane.add(buttons, BorderLayout.SOUTH);
pane.add(scroll, BorderLayout.CENTER);
addWindowListener( new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
public void actionPerformed(ActionEvent e)
String arg = lcdLoanAmt.getText();
int combined = Integer.parseInt(arg);
if (e.getSource() == CalculateBtn)
try
JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
catch(NumberFormatException ev)
JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
if ((e.getSource() == CalculateBtn) && (arg != null))
try{
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
monthlyInterest = interest[0] / (12 * 100);
termInMonths = term[0] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
monthlyInterest = interest[1] / (12 * 100);
termInMonths = term[1] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
monthlyInterest = interest[2] / (12 * 100);
termInMonths = term[2] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
catch(NumberFormatException ev)
JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
} //IF STATEMENTS FOR AMORTIZATION
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
loopy(7, 5.35);
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
loopy(15, 5.5);
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
loopy(30, 5.75);
if (e.getSource() == ClrBtn)
rateTermList.setSelectedIndex(0);
lcdLoanAmt.setText(null);
lcdMonthlyPmt.setText(null);
displayArea.setText(null);
if (e.getSource() == CloseBtn)
System.exit(0);
private void loopy(int lTerm,double lInterest)
double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
int amount, months, termloop, monthloop;
String lcd2 = lcdLoanAmt.getText();
amount = Integer.parseInt(lcd2);
termloop = 1;
paid = 0.00;
monthlyrate = lInterest / (12 * 100);
months = lTerm * 12;
monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
total = months * monthly;
balance = amount;
while (termloop <= lTerm)
displayArea.setCaretPosition(0);
displayArea.append("\n");
displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
displayArea.append("\n");
displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
monthloop = 1;
while (monthloop <= 12)
monthint = balance * monthlyrate;
monthprin = monthly - monthint;
balance -= monthprin;
paid += monthly;
displayArea.setCaretPosition(0);
displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
monthloop ++;
termloop ++;
public static void main(String args[])
MORT_RETRY f = new MORT_RETRY();
f.setTitle("MORTGAGE PAYMENT CALCULATOR");
f.setBounds(600, 600, 500, 500);
f.setLocationRelativeTo(null);
f.setVisible(true);
}need help with displaying the textarea correctly and the scroll bar please.
Message was edited by:
new2this2020What's the problem you're having ???
PS. -
How to hide the Form Feed char in JTextArea
We have reports (written in C) that are being displayed in a JTextArea.
In our old app, the Form Feed character (ASCII 12) was invisible naturally without having to code around it. In a JTextArea, it appears as a "[]" character. Does anyone know how to make this character invisible to the JTextArea? Removing it is not an option, as it is needed for it's print routine.
I've been searching these forums and the web all morning with no luck.Not sure how the Form Feed character worksIt lets the printer know that a new page is to be started at that point.
Does it always appear with the New Line character?Usually but not always.
Thanks for the reply. It's more involved than just printing standard lines of text, so perhaps I should have been more clear.
The C report already has pagination built in from when it was run from our legacy GUI. In other words, each report knows how many chars wide and how many lines down each page will be. It is different for each report, but they all hover around 150 chars wide and 60 lines down per page, since they are all presented to the user (and printed) in landscape.
In the C code: at the end of each report line a "\n" is appended. At the end of each page, an ASCII 12 character is appended. A header is at the top of each page (different for each report, but usually 2 or 3 lines) that shows the page # and other info.
So, as you are viewing the report, you would see page 1 header, some report content, page 2 header, some more report content, page 3 header, etc. as you scroll down.
So now if you view it in Java: if the user wishes to print, the report is sent to our ReportPrinter class, who tokenizes the report based on "\f" and makes a ReportPage object (implements Printable) for each token. Each ReportPage is then appened to a java.awt.print.Book object, who in turn is sent to the PrinterJob.
Given that the report already has his pages figured out and has a form feed char at the end of each page, the report comes in to the JTextArea with [] chars preceding each page header (approximately every 60th line, depending on the report).
I tried using a JTextPane, but no luck. It was also much slower reading in the report. I just want the textpane to not display the non-printable characters ("\f" in this case).
Maybe you are looking for
-
How do I get all my music back on my iphone 4?
Cracked the screen on my iphone 4, went to apple shop, they changed it (lovely) and restored all the settings from icloud, all went very well, except I noticed that the music doesn't get restored from itunes Match. In fact it was completely empty. Yo
-
File.lastModified() not working in MAC OS
Hi all, Iam trying to get the lastmodified time of a file using this File newFile=new File(uploadFilePath); //uploadFilePath has the path of the file. String newFile_Name=newFile.getName(); long lastmodified=newFile.lastModifi
-
Action Profile - Display SMART FORM in PDF
Hi All, I have a requirement in action profile, in which when a SMART FORM PRINT action is triggered in CRMD_ORDER, the smart form should be displayed in PDF. Then the user should be able to save or print the pdf form. Can some body provide some po
-
Regarding calculation of uom(unit of measurment)
i want to display uom(unit of measure) field in dis format: - UOM IS KG -> SO QTY TO -> (SALES ODER QTY * 1000) G -> (SALES ODR QTY / 1000) I making d report of sales order and i have to display it according to it...plzzz help me its urgent...
-
Shift key in a web page is acting like ctrl+f search key?????
i installed some addons today after a while i noticed .problem with my shift key it is fine while using on text boxes but shift +any alphabet leads to search box similar to ctrl+f box.