JTextArea
hi all,
i am new to java please help me
I am using JTextArea..
I added one JTextArea to panel in the south(I used borderlayout)
the problem is I want to fix the height of the JTextArea
so Is there any method to fix the height...
please help me on this
thanks
The size of a JTextArea (height & width) is determined by the rows and columns of the JTextArea.
If you want to control the height/width yourself then don't specify the rows/columns when you create the JTextArea and use the setPreferredSize(...) method to control the size.
Read the API for the different constructors and methods that affect the rows and columns.
Similar Messages
-
To refresh the contents in JTextArea on selection of a row in JTable.
This is the block of code that i have tried :
import java.awt.GridBagConstraints;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import ui.layouts.ComponentsBox;
import ui.layouts.GridPanel;
import ui.layouts.LayoutConstants;
import util.ui.UIUtil;
public class ElectronicJournal extends GridPanel {
private boolean DEBUG = false;
private boolean ALLOW_COLUMN_SELECTION = false;
private boolean ALLOW_ROW_SELECTION = true;
private GridPanel jGPanel = new GridPanel();
private GridPanel jGPanel1 = new GridPanel();
private GridPanel jGPanel2 = new GridPanel();
DefaultTableModel model;
private JLabel jLblTillNo = UIUtil.getHeaderLabel("TillNo :");
private JLabel jLblTillNoData = UIUtil.getBodyLabel("TILL123");
private JLabel jLblData = UIUtil.getBodyLabel("Detailed View");
private JTextArea textArea = new JTextArea();
private JScrollPane spTimeEntryView = new JScrollPane();
private JScrollPane pan = new JScrollPane();
String html= " Item Description: Price Change \n Old Price: 40.00 \n New Price: 50.00 \n Authorized By:USER1123 \n";
private JButton jBtnExporttoExcel = UIUtil.getButton(85,
"Export to Excel - F2", "");
final String[] colHeads = { "Task No", "Data", "User ID", "Date Time",
"Description" };
final Object[][] data = {
{ "1", "50.00", "USER123", "12/10/2006 05:30", "Price Change" },
{ "2", "100.00", "USER234", "15/10/2006 03:30", "Price Change12345"},
final String[] colHeads1 = {"Detailed View" };
final Object[][] data1 = {
{ "Task:Price Change", "\n"," Old Price:50.00"," \n ","New Price:100.00"," \n" }
JTable jtblTimeEntry = new JTable(data, colHeads);
JTable jTbl1 = new JTable(data1,colHeads1);
ComponentsBox jpBoxButton = new ComponentsBox(LayoutConstants.X_AXIS);
public ElectronicJournal() {
super();
jtblTimeEntry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (ALLOW_ROW_SELECTION) { // true by default
ListSelectionModel rowSM = jtblTimeEntry.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
//Ignore extra messages.
if (e.getValueIsAdjusting()) return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if (lsm.isSelectionEmpty()) {
System.out.println("No rows are selected.");
} else {
int selectedRow = lsm.getMinSelectionIndex();
System.out.println("Row " + selectedRow
+ " is now selected.");
textArea.append("asd \n 123 \n");
} else {
jtblTimeEntry.setRowSelectionAllowed(false);
if (DEBUG) {
jtblTimeEntry.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(jtblTimeEntry);
initialize();
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
System.out.println();
System.out.println("--------------------------");
private void initialize() {
this.setSize(680, 200);
this.setBackground(java.awt.SystemColor.control);
jBtnExporttoExcel.setBackground(SystemColor.control);
ComponentsBox cmpRibbonHORZ = new ComponentsBox(LayoutConstants.X_AXIS);
cmpRibbonHORZ.addComponent(jBtnExporttoExcel, false);
jpBoxButton.add(cmpRibbonHORZ);
this.addFilledComponent(jGPanel, 1, 1, 1, 1, GridBagConstraints.BOTH);
this.addFilledComponent(jGPanel1, 2, 1, 11, 5, GridBagConstraints.BOTH);
this.addFilledComponent(jGPanel2, 2, 13, 17, 5, GridBagConstraints.BOTH);
jGPanel.setSize(650, 91);
jGPanel.setBackground(SystemColor.control);
jGPanel.addFilledComponent(jLblTillNo,1,1,GridBagConstraints.WEST);
jGPanel.addFilledComponent(jLblTillNoData,1,10,GridBagConstraints.BOTH);
jGPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
jGPanel1.setBackground(SystemColor.control);
jGPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
0));
spTimeEntryView.setViewportView(jtblTimeEntry);
jGPanel1.addFilledComponent(spTimeEntryView, 1, 1, 11, 4,
GridBagConstraints.BOTH);
jGPanel2.addFilledComponent(jLblData,1,1,GridBagConstraints.WEST);
jGPanel2.setBackground(SystemColor.control);
jGPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
0));
//textArea.setText(html);
pan.setViewportView(textArea);
int selectedRow = jTbl1.getSelectedRow();
System.out.println("selectedRow ::" +selectedRow);
int colCount = jTbl1.getColumnCount();
System.out.println("colCount ::" +colCount);
StringBuffer buf = new StringBuffer();
System.out.println("Out Of For");
/*for(int count =0;count<colCount;count++)
{System.out.println("Inside For");
buf.append(jTbl1.getValueAt(selectedRow,count));
// method 1 : Constructs a new text area with the specified text.
textArea =new JTextArea(buf.toString());
//method 2 :To Append the given string to the text area's current text.
textArea.append(buf.toString());
jGPanel2.addFilledComponent(pan,2,1,5,5,GridBagConstraints.BOTH);
this.addAnchoredComponent(jpBoxButton, 7, 5, 11, 5,
GridBagConstraints.CENTER);
This code displays the same data on the JTextArea everytime i select each row,but my requirement is ,it has to refresh and display different datas in the JTextArea accordingly,as i select each row.Please help.Its urgent.
Message was edited by: Samyuktha
SamyukthaPlease help.Its urgentThen why didn't you use the formatting tags to make it easier for use to read the code?
Because of the above I didn't take a close look at your code, but i would suggest you should be using a ListSelectionListener to be notified when a row is selected, then you just populate the text area. -
How to Capture New Line in JTextArea?
I apologize if this is easy, but I've been searching here and the web for a few hours with no results.
I have a JTextArea on a form. I want to save the text to a database, including any newline characters - /n or /r/n - that were entered.
If I just do a .getText for the component, I can do a System.println and see the carriage return. However, when I store and then retrieve from the database, I get the lines concatenated.
How to I search for the newline character and then - for lack of a better idea - replace it with a \n or something similar?
TIA!PerfectReign wrote:
Okay, nevermind. I got it.
I don't "see" the \n but it is there.
I added a replaceAll function to the string to replace \n with
and that saves to the database correctly.
String tmpNotes = txtNotes.getText().replaceAll("\n", "<br />");Oh, you're viewing the text as HTML? That would have been good to know. ;)
I'll have to find a Wintendo machine to try this as well.Be careful not to get a machine that that says "Nii!" -
How to refresh a JPanel/JTextArea
My main problem is that I don't know how to correctly refresh a JTextArea in an Applet. I have an Applet with 2 internal frames. Each frame is comprised of a JPanel.
The first internal frame calls the second one as shown below:
// Set an internal frame for Confirmation and import the Confirm class into it//
Container CF = nextFrame.getContentPane();
//<Jpanel>
confirmation = new Confirmation( );
CF.add ( confirmation, BorderLayout.CENTER );
mFrameRef.jDesktopPane1.add(nextFrame,JLayeredPane.MODAL_LAYER);
currentFrame.setVisible(false); // Hide this Frame
nextFrame.setVisible(true); // Show Next Frame/Screen of Program
confirmation (Jpanel) has a JTextArea in it. When it's called the first time it displays the correct information (based on choices from the first frame). If a user presses the back button (to return to first frame) and changes something, it doesn't refresh in the JTextArea when they call the confirmation(Jpanel) again. I used System.out.println (called right after jtextareas code), and it shows the info has indeed changed...I guess I don't know how to correctly refresh a JTextArea in an Applet. Here is the relevent code for the 2nd Internal Frame (confirmation jpanel):
// Gather Info to display to user for confirmation //
final JTextArea log = new JTextArea(10,35);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
log.append("Name: " storeInfoRef.getFirstName() " "
+storeInfoRef.getLastName() );
log.append("\nTest Project: " +storeInfoRef.getTestProject() );
JScrollPane logScrollPane = new JScrollPane(log);Here is the relevant code that I am having the problem with...
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Confirmation extends JPanel {
// Variables declaration
private StoreInfo storeInfoRef; // Reference to StoreInfo
private MFrame mFrameRef; // Reference to MFrame
private Progress_Monitor pmd; // Ref. to Progress Monitor
private JLabel ConfirmMessage; // Header Message
private JButton PrevButton; // Navigation Button btwn frames
private JInternalFrame prevFrame, currentFrame; // Ref.to Frames
// End of variables declaration
public Confirmation(MFrame mFrame, StoreInfo storeInfo) {
mFrameRef = mFrame; // Reference to MFrame
storeInfoRef = storeInfo; // Reference to Store Info
prevFrame = mFrameRef.FileChooserFrame; // Ref. to Previous Frame
currentFrame = mFrameRef.ConfirmationFrame; // Ref. to this Frame
initComponents();
// GUI for this class //
private void initComponents() {
ConfirmMessage = new JLabel();
PrevButton = new JButton();
UploadButton = new JButton();
setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints1;
ConfirmMessage.setText("Please confirm that the information "
+"entered is correct");
add(ConfirmMessage, gridBagConstraints1);
// Gather Info to display to user for confirmation //
final JTextArea log = new JTextArea(10,35);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
log.append("Name: " storeInfoRef.getFirstName() " "
+storeInfoRef.getLastName() );
log.append("\nTest Project: " +storeInfoRef.getTestProject() );
log.append("\nTest Director: " +storeInfoRef.getTestDirector() );
log.append("\nTest Location: " +storeInfoRef.getTestLocation() );
log.append("\nDate: " +storeInfoRef.getDate() );
String fileOutput = "";
Vector temp = new Vector( storeInfoRef.getFiles() );
for ( int v=0; v < temp.size(); v++ )
fileOutput += "\n " +temp.elementAt(v); // Get File Names
log.append("\nFile: " +fileOutput );
// log.repaint();
// log.validate();
// log.revalidate();
JScrollPane logScrollPane = new JScrollPane(log);
System.out.println("Name: " storeInfoRef.getFirstName() " " +storeInfoRef.getLastName() );
System.out.println("Test Project: " +storeInfoRef.getTestProject() );
System.out.println("Test Director: " +storeInfoRef.getTestDirector() );
System.out.println("Test Location: " +storeInfoRef.getTestLocation() );
System.out.println("Date: " +storeInfoRef.getDate() );
System.out.println("File: " +fileOutput );
// End of Gather Info //
add(logScrollPane, gridBagConstraints1);
PrevButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
PrevButtonMouseClicked(evt);
PrevButton.setText("Back");
JPanel Buttons = new JPanel();
Buttons.add(PrevButton);
add(Buttons, gridBagConstraints1);
// If User Presses 'Prev' Button //
private void PrevButtonMouseClicked(java.awt.event.MouseEvent evt) {
try
currentFrame.setVisible(false); // Hide this Frame
prevFrame.setVisible(true); // Show Next Frame/Screen of Program
catch ( Throwable e ) // If A Miscellaneous Error
System.err.println( e.getMessage() );
e.printStackTrace( System.err );
}// End of Confirmation class -
How to put a Jpanel always over a JtextArea ?
I want to have a little Jpanel above a JTextArea.
At the initialize section, I add first the Jpanel and after the JtextArea (both in a 'parent' Jpanel with null layout)
When I run the program I see the Jpanel over the JtextArea, but when I write on it and it reaches the area when the Jpanel is placed, the JtexArea brings to front and the Jpanel is no longer visible.
So, how can I have my Jpanel on top always ?
And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)
Thanks
( I do not send any code because it is so simple as putting this two components into a Jpanel)tonnot wrote:
And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)JLayeredPane
( I do not send any code because it is so simple as putting this two components into a Jpanel)Try it with a JLayeredPane and if you still have problems, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html].
db -
How to repaint a JTextArea inside a JScrollPane
I am trying to show some messages (during a action event generated process) appending some text into a JTextArea that is inside a JScrollPane, the problem appears when the Scroll starts and the text appended remains hidden until the event is completely dispatched.
The following code doesnt run correctly.
((JTextArea)Destino).append('\n' + Mens);
Destino.revalidate();
Destino.paint(Destino.getGraphics());
I tried also:
Destino.repaint();
Thanks a lot in advanceCorrect me if I am wrong but I think you are saying that you are calling a method and the scrollpane won't repaint until the method returns.
If that is so, you need to use threads in order to achieve the effect you are looking for. Check out the Model-View-Contoller pattern also. -
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). -
Display data from entity into a Jtextareaþ
Hello everyone,
How do I display data I am retrieving from the entity into a Jtextarea?
Here is how I am doing it:
in the main class of the application client, I set up a method
which stores the remote interface so I can call the method
anyway of my application.
public class Main extends javax.swing.JFrame {
@EJB
private static BRemote bRemote;
//accessor method
static BRemote getBRemote() {
return bRemote;
// I can out the method to request data
public void findB(String bal){
Main.getBRemote().findbyDname(bal);
searesttxta.setText(getBRemote().toString());
} The searesttxta is the JTextArea.
the data I get is
folder._BRemote_Wrapper@3ce08241
So, how do I get to display the entity in the textarea?
thanks
eveHi,
Thank you for your reply.
Yes I do have sets and get methods but I also understand I can
use the to string too. But to attach it to the JTextArea.
eve -
Highlighting text in JtextArea
I want to highlight text in a JTextArea each time the text changes and therefore i use a DocumentListener and also the following :
public Highlighter.HighlightPainter redHighlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
Highlighter hilite = gJTextArea.getHighlighter();
hilite.addHighlight(bufferBegin , bufferEnd, redHighlightPainter);
but the text remains black
How can you explain this?
ThanksI have used the same exact piece of code in a JTextArea and it works perfectly. Maybe your problem is elsewhere in the code because this should work fine. Are you sure that the Document listener is fireing when changes occur?
-
How can i get the content of JTextArea with out loosing Indentation.
I am developing one mail sending application. I am getting mailid , from address, mail body from one Swing. In one JTextArea i am typing i have typed some matter. When i call the content of JTextArea using
jtx.getText() method, i am getting all the content as one paragraph. That means there is no indentation which was there in TextArea.
Please provide me some solution how can i get the content of JTextArea wiht out loosing indentation.And it was you who asked the question!
-
Problem with JTextArea or is it my code, Help!!!
Hi,
I am going crazy. I am sending a message to a JTextArea and I get some very wierd things happening? I really need help because this is driving me crazy. Please see the following code to see my annotations for the problems. Has anyone else experienced problems with this component?
Thanks,
Steve
// THIS IS THE CLASS THAT HANDLES ALL OF THE WORK
public class UpdateDataFields implements ActionListener { // 400
JTextArea msg;
JPanel frameForCardPane;
CardLayout cardPane;
TestQuestionPanel fromRadio;
public UpdateDataFields( JTextArea msgout ) { // 100
msg = msgout;
} // 100
public void actionPerformed(ActionEvent evt) { // 200
String command = evt.getActionCommand();
String reset = "Test of reset.";
try{
if (command.equals("TestMe")){ // 300
msg.append("\nSuccessful");
Interface.changeCards();
} // 300
catch(Exception e){
e.printStackTrace();
try{
if (command.equals("ButtonA")){ // 300
// WHEN I CALL BOTH OF THE FOLLOWING METHODS THE DISPLAY WORKS
// BUT THE CHANGECARDS METHOD DOES NOT WORK. WHEN I COMMENT OUT
// THE CALL TO THE DISPLAYMESSAGE METHOD THEN THE CHANGECARDS WORKS
// FINE. PLEASE THE INTERFACE CLASS NEXT.
Interface.changeCards();
Interface.displayMessage("test of xyz");
} // 300
catch(Exception e){
e.printStackTrace();
} // 200
} // 400
// END OF UPDATEDATAFIELS END END END
public class Interface extends JFrame { // 300
static JPanel frameForCardPane;
static CardLayout cardPane;
static JTextArea msgout;
TestQuestionPanel radio;
Interface () { // 100
super("This is a JFrame");
setSize(800, 400); // width, height
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set-up card layout
cardPane = new CardLayout();
frameForCardPane = new JPanel(); // for CardLayout
frameForCardPane.setLayout(cardPane); // set the layout to cardPane = CardLayout
TestQuestionPanel cardOne = new TestQuestionPanel("ABC", "DEF", msgout, radio);
TestQuestionPanel cardTwo = new TestQuestionPanel("GHI", "JKL", msgout, radio);
frameForCardPane.add(cardOne, "first");
frameForCardPane.add(cardTwo, "second");
// end set-up card layout
// set-up main pane
// declare components
msgout = new JTextArea( 8, 40 );
ButtonPanel commandButtons = new ButtonPanel(msgout);
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(2, 4, 5, 15)); pane.setBorder(BorderFactory.createEmptyBorder(30, 20, 10, 30));
pane.add(frameForCardPane);
pane.add( new JScrollPane(msgout));
pane.add(commandButtons);
msgout.append("Successful");
setContentPane(pane);
setVisible(true);
} // 100
// HERE ARE THE METHODS THAT SHOULD HANDLE THE UPDATING
static void changeCards() { // 200
cardPane.next(frameForCardPane);
System.out.println("Calling methods works!");
} // 200
static void displayMessage(String test) { // 200
String reset = "Test of reset.";
String passMessage = test;
cardPane.next(frameForCardPane);
System.out.println("Calling methods works!");
msgout.append("\n"+ test);
} // 200
} // 300Hi,
I instantiate it in this class. Does that change your opinion or the advice you gave me? Please help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutQuestionsv2 {
public static void main(String[] arguments) {
JFrame frame = new Interface();
frame.show();
} -
Reading a text File into a JTextArea
I know this is really basic question, but what is the best and/or simplest way to read text from a .txt file into a JTextArea? I'm new to Java and any help anyone can provide would be greatly appreciated.
it should be in quotes only if it is a string repersentation of a String class.
FileReader reader = new FileReader("readme.txt");
quotes are not needed if you write it this way
String filename = "readme.txt";
FileReader reader = new FileReader(filename);
...remember that String is a class and not a data type, it is also a special case in java where the class can act like a datatype in declarations.
I don't think anything else can behave like this in java
String text = "sometext";
"sometext".equals(text);
this returns true. -
How do you read data from a text file into a JTextArea?
I'm working on a blogging program and I need to add data from a text file named messages.txt into a JTextArea named messages. How do I go about doing this?
Student_Coder wrote:
1) Read the file messages.txt into a String
2) Initialize messages with the String as the textSwing text components are designed to use Unix-style linefeeds (\n) as line separators. If the text file happens to use a different style, like DOS's carriage-return+linefeed (\r\n), it needs to be converted. The read() method does that, and it saves the info about the line separator style in the Document so the write() method can re-convert it.
lethalwire wrote:
They have 2 different ways of importing documents in this link:
http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
Neither of those methods applies to JTextAreas. -
Keyevent used for setMnemonic show in editable jtextarea
I don't know if this has been fix. I notice that if I used the setMnemonic to access a editable jtextarea, that the key I used is inserted into the jtextarea. After searching the web, I found nothing about this problem.
So, I took the program from the java tutorial, MenuDemo.java and reproduct the same problem but setting the jtextarea to editable (output.setEditable(true). It happens everytime. Below is the MenuDemo.java with the change. By selecting t or b in the A Menu menu,then which ever t or b used will show up in the text area after the expected line displays. I am using 1.5 so this problem may have been fix.
If anyone knows if it has or a work around, please let me know.
Thanks
Kevin
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
* This class adds event handling to MenuLookDemo.
public class MenuDemo extends JFrame
implements ActionListener, ItemListener {
JTextArea output;
JScrollPane scrollPane;
String newline = "\n";
public MenuDemo() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
//Add regular components to the window, using the default BorderLayout.
Container contentPane = getContentPane();
output = new JTextArea(5, 30);
output.setEditable(true);
scrollPane = new JScrollPane(output);
contentPane.add(scrollPane, BorderLayout.CENTER);
//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menuItem.addActionListener(this);
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.gif"));
menuItem.setMnemonic(KeyEvent.VK_B);
menuItem.addActionListener(this);
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
menuItem.setMnemonic(KeyEvent.VK_D);
menuItem.addActionListener(this);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
rbMenuItem.addActionListener(this);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
rbMenuItem.addActionListener(this);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
cbMenuItem.addItemListener(this);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
cbMenuItem.addItemListener(this);
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2, ActionEvent.ALT_MASK));
menuItem.addActionListener(this);
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
menuItem.addActionListener(this);
submenu.add(menuItem);
menu.add(submenu);
//Build second menu in the menu bar.
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"This menu does nothing");
menuBar.add(menu);
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem)(e.getSource());
String s = "Action event detected."
+ newline
+ " Event source: " + source.getText()
+ " (an instance of " + getClassName(source) + ")";
output.append(s + newline);
public void itemStateChanged(ItemEvent e) {
JMenuItem source = (JMenuItem)(e.getSource());
String s = "Item event detected."
+ newline
+ " Event source: " + source.getText()
+ " (an instance of " + getClassName(source) + ")"
+ newline
+ " New state: "
+ ((e.getStateChange() == ItemEvent.SELECTED) ?
"selected":"unselected");
output.append(s + newline);
// Returns just the class name -- no package info.
protected String getClassName(Object o) {
String classString = o.getClass().getName();
int dotIndex = classString.lastIndexOf(".");
return classString.substring(dotIndex+1);
public static void main(String[] args) {
MenuDemo window = new MenuDemo();
window.setTitle("MenuDemo");
window.setSize(450, 260);
window.setVisible(true);Yes your are correct. I forgot why I went to 1.5 but until better time come along and I can get a new computer, I will have to live with 1.4.2._06. But, it did fit my problem.
-
Creating a Frame with two JTextareas
Please Help,
I am currently studying java at the moment i am new to programming and find it difficult. However i have a problem using Swing. I am trying to create a "JTextarea" in the NORTH of the Frame and another "JTextarea" in the CENTER. I have write both bits of code to do this. When i added the second JTextarea i lost the first JTextArea when i ran the program. I figure the program is reading the first part of code then overwriting it with the second part of the code. Can anyone help?
The code i wrote was as follows;
//Java extension Package
import javax.swing.*;
//Java core Pakages
import java.awt.*;
import java.awt.event.*;
public class Panel extends JFrame
public JTextArea textArea1, textArea2;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Swing Example");
//Displays NORTH JTextArea
JTextArea textArea1 = new JTextArea("Click something to see what happens...");
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(textArea1,BorderLayout.NORTH);
//Displays text in CENTER
JTextArea textArea2 = new JTextArea("This is a JTextArea\n" +
"component. It is placed in\n" +
"the Center position after the\n" +
"JTextArea is placed North,\n" +
"the three JButtons are\n" +
"placed in a West JPanel\n" +
"and the JComboBox\n" +
"components is placed in an\n" +
"East JPanel.");
frame.getContentPane() .setLayout(new BorderLayout());
frame.getContentPane() .add(textArea2,BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}Hello,
Thankyou for helping me with that problem it is much appreciated no doubt ill have some more questions.
L. Tambiah
Maybe you are looking for
-
Digital Sound Output suddenly muted (though Apple TV is not)
I'm wondering if there's a simple explanation (and fix) to the problem. Before upgrading iTunes and OSX to the most current versions, I encountered the problem of no output via USB. That problem I attributed to a broken audio output jack requiring
-
Convert iPhoto file into pdf file
Need to convert iPhoto files in pdf format to send as email attachment to a recipient who requires it in this format. How do I do it?
-
Import a application In sharepoint 2010
I Have a exported application in my c drive in a folder . I want to import it to a new web application . how can i achieve this I tried using management shell like : import-spweb http: // path:c:\path name but its throwing an error like. impor
-
Error Script when try to delete records under condition
Dear Members I have a problem when i try to delete a record at MDX script into BOC I have the follow problem TIME FLOW C_DATASRC ENTITY INTCO CONSGROUP RPTCURRENCY C_CATEGORY C_ACCT DIVISION SEGMENT SIGNDATA 2011.FEB VALID INPUT CIA12 I_CCO11 NON_GRO
-
Dears, Is it possible to create dynamic image marker theme? for example, I have a geometry table which contains the location of schools and universites, i would like to show different marker for each type. the geometry table has a code field (S: for