JTextArea getting whole line - java

How can I get chosen line from JTA ?

I suppose you can use getLineStartOffset(int line), and getLineEndOffset(int line) to substring out a particular line from the string returned from getText()
If you mean that you want to know what the user has selected (using the mouse/keyboard):
getSelectedText() should give you that.

Why not break the lines up into tokens. then if you know the line number you want, you can just access it via an array of Strings
public class JTALineNum extends JFrame{
JTextArea jta = null;
JButton button = null;
public JTALineNum(){
jta = new JTextArea();
button = new JButton("Hit Me");
button.addActionListener(new ButtonListener());
add(jta, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setSize(200,200);
setVisible(true);
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String text = jta.getText();
String[] tokens = text.split("\n");
for(String i : tokens){
System.out.println("Token:: " + i);
}
}
}
public static void main(String args[]){
JTALineNum app = new JTALineNum();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Related

I'm trying to make a button to count characters in a text field

I'm trying to use the JButton count to count the number of characters entered into the JTextField t. I'm new to Java and GUIs but here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends Frame implements ActionListener{
TextField t;
Button count;
int a;
Choice choice;
public GUI1(){
this.t = new TextField("", 30);
this.count = new Button("count");
this.count.addActionListener(this);
JTextField x = new JTextField();
x.setEditable(false);
this.setTitle("Character count");
this.setLayout(new FlowLayout());
this.add(x);
this.add(t);
this.add(count);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()== this.count)
t.setText(choice.getSelectedItem()+ " " +a);
}
I'm also trying to enter the value in another uneditable JTextField x. Any help is appreciated.
Add this to your code
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a = t.getText().length();
}
});
OR
You can use lambda expression like this
count.addActionListener(e -> a = t.getText().length());
For More
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
You need to add a listener
TextField t = new TextField();
Button b = new Button("Count");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
}
});
You can read more about here
http://www.tutorialspoint.com/awt/awt_button.htm
First of all, I recommend you not to use AWT elements, since it brings tons of problems and it has little to no support, instead you can try using Swing components which are a replacement/fix for AWT. You can read more about here. You might also want to read AWT vs Swing (Pros and Cons).
Now going into your problem:
You should avoid extending from JFrame, I might recommend you to create a new JFrame object instead. Here's the reason to why. That being said, you can also remove all your this.t and other calls with this.
I'm glad you're using a Layout Manager!
And now to count the number of characters on your JTextField and set text to your other JTextField you should use this code:
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
Also I fixed your code, I changed AWT elements to Swing ones and added number of cols to your second JTextField so it would appear.
So, here's a running example that I made from your code (And removed Choice choice line since you didn't posted that code):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 {
JTextField t;
JButton count;
int a;
JFrame frame;
public GUI1(){
frame = new JFrame();
t = new JTextField("", 15);
count = new JButton("count");
JTextField x = new JTextField("", 15);
x.setEditable(false);
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
frame.setTitle("Character count");
frame.setLayout(new FlowLayout());
frame.add(x);
frame.add(t);
frame.add(count);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[]) {
new GUI1();
}
}
When you click on a button you should
String str = t.getText(); // get string from jtextfield
To save the text from the texfield. Then you can use something like:
a = str..length(); // get length of string
x.setText(str + " " + a); //set it to the field
To set it to the JTextField.

Split String on JButton press

I am trying to make the input from a JTextField get split into an array of words when I press a button. When I press the button the program gives me a huge list of errors. The line of code that splits the sentence and where I call the class in the action listener is where eclipse says the error is coming from. I do not know why I am getting this error and I don't know how to fix. I have tried a lot of different things but they don't work. If you could explain why this isn't working or how to fix that would be great. Here is my code. Thank you for your help.
Main Class:
public class Control {
public static void main(String[] args) {
OpenWindow ow = new OpenWindow();
ow.window();
}
}
Second Class:
public class OpenWindow extends JFrame{
//Making variables
String input;
String firstWord2;
JButton jb = new JButton("Button");
JLabel jl = new JLabel();
JTextField jtf = new JTextField(40);
JPanel jp1 = new JPanel(new GridLayout(3,1));
SentenceSplitter ss = new SentenceSplitter();
public void window() {
//Make window pop up
setTitle("Project");
setSize(600, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Action Listener
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = jtf.getText();
//Error from line below
ss.split();
firstWord2 = ss.getFirstWord();
jl.setText(firstWord2);
}
});
//Add JFrames
jp1.add(jtf);
jp1.add(jb);
jp1.add(jl);
add(jp1);
}
//Make input accesible from other classes
String getInput() {
return input;
}
}
Third Class:
public class SentenceSplitter {
String firstWord;
public void split() {
OpenWindow ow2 = new OpenWindow();
//Get input
String sentence = ow2.getInput();
//Error from line below
String[] splitSentence = sentence.split(" ");
firstWord = splitSentence[0];
}
String getFirstWord() {
return firstWord;
}
}
In your code you
creating OpenWindow
In The OpenWindow object you are creating a SentenceSplitter and listening for a click
On the click you are calling the split method on the previously created SentenceSplitter
In split you are creating a new OpenWindow
What you maybe should do is pass the String as an input parameter to the split method

how to remove lines one by one from a JTextArea

How can i remove lines from a JTextArea one by one instead of all together?
I have a JTextArea which gets appended with string results from a thread, now i would like to remove one line at a time while the thread is executing.
You first need to decide what should trigger the line removal.
Should it be the addition of a new line, so that total line number is constant. If so then you should write your code to call the line removal code in the same location that where a new line is added.
Or should it be at a constant rate -- and if so, then you will want to use a Swing Timer for this.
Then you need to decide which line to remove. If not the first line, then you'll need to figure out how to calculate which line. The javax.swing.text.Utilities class can help you find out the start and finish location of every line of text in your JTextArea.
Edit
You ask:
the main concern is about how to remove it from the JTextArea, i have already calculated the start and end positions of a line that has to be deleted.But what function can assist in removing just that one line?
You would first get the JTextArea's Document by calling, getDocument()
Then you could call remove(int offs, int length) on the Document as per the Document API.
Try This :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class SwingControlDemo {
String [] m;
int i=0;
String append="";
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
Timer t;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showTextAreaDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextAreaDemo(){
headerLabel.setText("Control in action: JTextArea");
JLabel commentlabel= new JLabel("Comments: ", JLabel.RIGHT);
final JTextArea commentTextArea =
new JTextArea("This is a Swing tutorial "
+"\n to make GUI application in Java."+"\n to make GUI application in Java"+"\n to make GUI application in Java",5,20);
JScrollPane scrollPane = new JScrollPane(commentTextArea);
JButton showButton = new JButton("Show");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s=commentTextArea.getText();
m=s.split("\n");
t.start();
}
});
t=new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
i++;
append="";
if(i<=m.length)
{
for(int j=i;j<m.length;j++)
{
append=append+m[j];
}
commentTextArea.setText(append);
}
else
{
t.stop();
}
}});
controlPanel.add(commentlabel);
controlPanel.add(scrollPane);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}

Java Enter Event Does Not Activate Handler

I am new to Java events, listeners and handlers. I can write code to create a button click event and a working result. However, I cannot get a simple enter event within a TextField to work.
Notice I do declare and call action listeners, input handlers, and define a resulting method execution. (I import java.awt and javax.swing libraries not shown below.)
public convertStringToCapitalLetters() {
setTitle("Convert String to All Capital Letters");
Container c = getContentPane();
c.setLayout(new GridLayout(2, 2));
inputLabel = new JLabel("Enter String: ", SwingConstants.LEFT);
stringTextField = new JTextField(50);
outputLabel = new JLabel("Capitalized String: ", SwingConstants.LEFT);
newStringLabel = new JLabel("", SwingConstants.RIGHT);
c.add(inputLabel);
c.add(stringTextField);
c.add(outputLabel);
c.add(newStringLabel);
inputHandler = new InputHandler();
stringTextField.addActionListener(inputHandler);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str, newStr;
str = stringTextField.getText();
newStr = str.toUpperCase();
newStringLabel.setText(String.format("", newStr));
}
}
public static void main(String[] args) {
convertStringToCapitalLetters capitalConv = new convertStringToCapitalLetters();
}
I think you just made a very small mistake which is to forget to specify the placeholder %s in String.format()
Try this:
newStringLabel.setText(String.format("%s", newStr));
You don't need the String.format("", newStr) call when setting the label's text, you can simply use
newStringLabel.setText(newStr);

how can i store the inputs given by the user from GUI to a string array for future use in java

.....
public void launchFrame(){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,500);
f.setVisible(true);
f.setLocationRelativeTo(null);
JLabel nameL=new JLabel("Title", SwingConstants.LEFT);
String[] FormOptions = {"Choose","Text Field","Password Field","Button","Radio Button","Check Box","Drop Down Menu"};
String[] NormalOptions = {"Choose","Write Text", "Upload Picture", "Frame", "I-Frame"};
JTextField nameTF=new JTextField(10);
final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Form:");
JComboBox forms=new JComboBox(FormOptions);
comboPanel.add(comboLbl);
comboPanel.add(forms);
comboPanel.add(nameL);
comboPanel.add(nameTF);
final JPanel comboPanel1 = new JPanel();
comboPanel1.setVisible(false);
JLabel comboLbl1 = new JLabel("Normal HTML:");
JComboBox Normals = new JComboBox(NormalOptions);
comboPanel1.add(comboLbl1);
comboPanel1.add(Normals);
JButton HTML = new JButton( "Form or Normal");
HTML.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
comboPanel1.setVisible(!comboPanel1.isVisible());
comboPanel.setVisible(!comboPanel.isVisible());
}
});
f.add(comboPanel, BorderLayout.NORTH);
f.add(comboPanel1, BorderLayout.CENTER);
f.add(HTML,BorderLayout.SOUTH);
f.setVisible(true);
static String[] info = new String[500];//Here i need help
}
public static void main(String args[]){
BasicGuiTest gui = new BasicGuiTest();
gui.launchFrame();
}
//What Should i do here? I want to get whether the user is choosing form or Normal as
//well as its options..
private class GetInfo implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
info[i]=comboPanel.getSelectedItem
}
//Then i will output the string array to a text file..
or, you could avoid reinventing the wheel and use the built in java Preferences API?
http://docs.oracle.com/javase/1.4.2/docs/guide/lang/preferences.html
Okay, so first thing I would do is make info an ArrayList, instead of String Array.
public static List<String> info = new ArrayList<String>();
So you don't have to worry about the length of the string. Then you can append to the list using
info.append(comboPanel.getSelectedItem());
And here's code to write the list to a file.
FileWriter writer = new FileWriter(new File("C:/filename.txt"));
for(String line : info){
writer.write(line + "\n");
}
writer.close();
Does this answer your question?

Categories

Resources