I want to delete selected text in a text area using Java Swing, but I couldn't find a way to do that. At some point I thought of using textArea.setText(""); but, when I do, it clears out everything. Can some one please help me with this?
Here is the code I've written so far,
public class DeleteTest extends JFrame implements ActionListener {
JPanel panel;
JTextArea textArea;
JButton button;
public DeleteTest() {
setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
panel.setBackground(getBackground().BLACK);
textArea = new JTextArea(300, 300);
button = new JButton("clear");
button.addActionListener(this);
panel.add(button);
add(textArea, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==button){
String selected=textArea.getSelectedText();
if(!selected.equals("")){
}
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
DeleteTest de = new DeleteTest();
}
};
SwingUtilities.invokeLater(r);
}
}
txtArea.replaceSelection("");
this should be shorter and more effective.
If you wanna remove only selected text then try this:
textArea.setText(textArea.getText().replace(textArea.getSelectedText(),""));
Hope this helps.
For JavaFx TextArea you can use deleteText(IndexRange range) method to delete the selected text.
textArea.deleteText(textArea.getSelection());
To delete text based on index use deleteText(int start, int end) overloaded method
textArea.deleteText(startIndex, endIndex);
We can use replaceSelection(String replacement) method to delete the text, in fact deleteText internally uses replaceText method but deleteText method will improve the readability of the code.
Related
I have two JFrame (JFrame1 and JFrame2) with two JTextField1 and JTextField2. My question is when I write "Hello world " on JTextField2 from Jframe2 and then click on OK button, I see "Hello world " on JTextField1 on Jframe1 class.
How can I do this? I'm sorry if this is a newbie question but I'm learning..
Here is my code:
JFrame2:
private JFrame1 jf1;
private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {
jf1.setjTextField1(this.jTextField2);
}
What you are doing there is actually sending the reference to the actual JTextField from one frame to the other one.
That's probably not a good idea cause both frames would be end up referencing the same visual component.
What you probably want is to keep all visual components separate, but make the text of the second text field equal to the text in the first one.
Something like this:
private void btn2ActionPerformed(java.awt.event.ActionEvent evt) {
jf1.getjTextField1().setText(this.jTextField2.getText());
}
You could use an Observer Pattern or Producer/Consumer Pattern to solve the problem.
The basic idea is, you have something that generates a value and something that either wants to be notified or consume the generated value.
One of the other prinicples you should take the time to learn is also Code to interface (not implementation). This sounds stranger then it is, but the the idea is to reduce the unnecessary exposure of your objects (to unintended/controlled modifications) and decouple your code, so you can change the underlying implementation without affecting any other code which relies on it
Given the nature of your problem, an observer pattern might be more suitable. Most of Swing's listener's are based on the same principle.
We start by defining the contract that the "generator" will use to provide notification of changes...
public interface TextGeneratorObserver {
public void textGenerated(String text);
}
Pretty simple. This means we can safely provide an instance of any object that implements this interface to the generator and know that it won't do anything to our object, because the only thing it knows about is the textGenerated method.
Next, we need something that generates the output we are waiting for...
public class GeneratorPane extends JPanel {
private TextGeneratorObserver observer;
private JTextField field;
private JButton button;
public GeneratorPane(TextGeneratorObserver observer) {
this.observer = observer;
field = new JTextField(10);
button = new JButton("OK");
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.textGenerated(field.getText());
}
};
button.addActionListener(listener);
field.addActionListener(listener);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
add(field, gbc);
add(button, gbc);
}
}
This is just a simple JPanel, but it requires you to pass a instance of TextGeneratorObserver to it. When the button (or field) triggers the ActionListener, the ActionListener calls the textGenerated to notify the observer that the text has been generated or changed
Now, we need someone to observer it...
public class ObserverPanel extends JPanel implements TextGeneratorObserver {
private JLabel label;
public ObserverPanel() {
label = new JLabel("...");
add(label);
}
#Override
public void textGenerated(String text) {
label.setText(text);
}
}
This is a simple JPanel which implements the TextGeneratorObserver interface and updates it's JLabel with the new text
Then, we just need to plumb it together
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
ObserverPanel op = new ObserverPanel();
op.setBorder(new CompoundBorder(new LineBorder(Color.RED), new EmptyBorder(10, 10, 10, 10)));
GeneratorPane pp = new GeneratorPane(op);
pp.setBorder(new CompoundBorder(new LineBorder(Color.GREEN), new EmptyBorder(10, 10, 10, 10)));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(2, 1));
frame.add(pp);
frame.add(op);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
This is a complete working example I just coded out:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class FrameRunner
{
public static void main(String[] args){
MyFrame f1 = new MyFrame("Frame 1");
MyFrame f2 = new MyFrame("Frame 2");
f1.addRef(f2);
f2.addRef(f1);
}
}
class MyFrame extends JFrame{
JTextField txt = new JTextField(8);
JButton btn = new JButton("Send");
MyFrame f = null;
public MyFrame(String title){
super(title);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new FlowLayout());
setPreferredSize(new Dimension(400, 300));
setVisible(true);
add(btn);
add(txt);
pack();
setLocationRelativeTo(null);
init();
}
public void addRef(MyFrame f){
this.f = f;
}
public void init(){
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
f.update(txt.getText());
}
});
}
public void update(String str){
txt.setText(str);
}
}
In order to make the code short and easier for you to understand. Many of the things I did not following the conventions and I did not modularize the codes. But this should give you a very good idea of how you can pass in the reference of another JFrame.
This code shows an example of how Frame1 has a reference on Frame2. Yet Frame2 also has a reference on Frame1.
Whatever things you type in JFrame1 can be send to JFrame2's textfield. Same for the other way round.
I have a text game which has buttons. When a button is clicked, text appears. My text appears inside a jPanel, which is inside a jScrollPane. I would like my jPanel to automatically make more vertical space for my lines of text to be added. I have been doing it by hand but it is a lot more time consuming. Is there anyway to do this, or maybe pack a jPanel somehow. I am pretty new to this so if any extra information is needed for you to help me out feel free to ask. Thanks.
I would use a component that can do this automatically -- a JTextArea. It will automatically enlarge as more text is added.
If you need more specific help or a code example, please post your own small compilable and runnable test example program, and I can try to modify it.
You state:
I don't want to use a JTextArea because I don't want the user to be able to highlight or delete any of the text that was there in the first place.
No problem. Just make the JTextArea non-focusable and non-editable.
I have been using jLabels which are equal to "" and when a button is pressed, that jLabel is given a new value.
Try something like this:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class AddNewLines extends JPanel {
private JTextArea textArea = new JTextArea(10, 15);
private JButton addLineBtn = new JButton(new AddLineAction("Add Line", KeyEvent.VK_A));
public AddNewLines() {
textArea.setEditable(false);
textArea.setFocusable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollPane);
add(addLineBtn);
}
class AddLineAction extends AbstractAction {
private int count = 0;
public AddLineAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (count != 0) {
textArea.append("\n");
}
textArea.append("Line of Text: " + count);
count++;
}
}
private static void createAndShowGui() {
AddNewLines mainPanel = new AddNewLines();
JFrame frame = new JFrame("Add New Lines");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
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);
}
}
I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.
How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?
Thank you !
It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameExample
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public JFrameExample()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add JTextField");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate(); // For JDK 1.7 or above.
//frame.getContentPane().revalidate(); // For JDK 1.6 or below.
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new JFrameExample().displayGUI();
}
});
}
}
Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:
// handle the button action event
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create the new text field
JTextField newTextField = new JTextField();
// add it to the container
panel.add(newTextField);
panel.validate();
panel.repaint();
}
});
When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).
I have a jTextField , and I set it's value to a certain sum when I create the frame.
Here is the initiation code:
totalTextField.setText(
itemsPriceTextField.getText() +
Float.toString(orderDetails.delivery)
);
This textfield should show a sum of items selected by the user.
The selection is done on a different frame, and both frames are visible / invisible
at a time.
The user can go back and forth and add / remove items.
Now, every time i set this frame visible again, I need to reload the value set to that field
(maybe no changes were made, but if so, I need to set the new correct sum) .
I'm quite desperate with it.
Can anyone please give me a clue?
Thanks in advance! :)
Before setting the frame visible again, one should update the fields with the new values / states.
something like:
jTextField.setText("put your text here");
jRadioButton.setSelected(!isSelected());
.
/* update all you need */
.
jFrame.setVisible(true);
The frame will come up with the new values / states.
Add a WindowListener to the frame. Then you can handle the windowActivated event and reset the text of the text field.
See How to Write Window Listeners.
Use a DocumentListener triggering the JTextField public void setText(String t)
Here an example with DocumentListener:
public class SetTextInJTextField extends JFrame implements DocumentListener {
JTextField entry;
JTextField entryToSet = new JTextField();
public SetTextInJTextField() {
createWindow();
entry.getDocument().addDocumentListener(this);
}
private void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void createUI(final JFrame frame) {
JPanel panel = new JPanel();
entry = new JTextField();
entryToSet = new JTextField();
LayoutManager layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
panel.add(this.entry);
panel.add(entryToSet);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
public void setTextInTargetTxtField() {
String s = entry.getText();
entryToSet.setText(s);
}
// DocumentListener methods
public void insertUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void removeUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void changedUpdate(DocumentEvent ev) {
}
public static void main(String args[]) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SetTextInJTextField().setVisible(true);
}
});
}
}
inspired from: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextFieldDemoProject/src/components/TextFieldDemo.java
related lesson: https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html