Inserting text in JTextArea - java

i am developing a simple application in Java and i wanted to know if there is any way i can insert additional text(somewhere in the middle of a sentence) inside a textarea , which is not empty, at a position where the cursor is placed on the click of some component. Can someone please direct me how to go about getting it done

If this is a JTextArea component you can use the .append method to add text to the end of the text area, or the .insert method to insert the new text at a specific position.
If you need to insert the text at the current caret position use the .getCaretPosition method

textArea.replaceSelection(text);
From the API:
Replaces the currently selected content with new content represented
by the given string. If there is no selection this amounts to an
insert of the given text

Check out: JTextComponent.getCaretPosition().
The method getCaretPosition() is inherited by JTextArea, you can use it to get the cursor position. Then you can use JTextArea.insert(String str, int pos) to insert text at that position.
Sample:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTextArea jta = new JTextArea("Hello world\nHello world\nHello world");
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int pos = jta.getCaretPosition(); //get the cursor position
jta.insert("Some more", pos); //insert your text
}
});
frame.add(jta, BorderLayout.CENTER);
frame.add(btn, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

Related

How can I display a JTable on a JFrame

I've spent hours online and I'm afraid I can't quite figure out how to make my JTable show up next to my JButton on a JFrame, if anyone has a simple or comprehensive way to explain why and how to fix the problem Id really appreciate it.
Extensive online research including downloading samples and applying various suggestions; also reached out to my teacher for help but she doesn't have much experience with java.
public class canvas extends JTable{
static void displayJFrame(){
//set variables
int i = 0;
String[][] strArray = new String[3][i];
String[] labelArray = new String[3];
labelArray[0] = "Name: ";
labelArray[1] = "Subject: ";
labelArray[2] = "Average: ";
//create JFrame
JFrame f = new JFrame("Test Average");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setBackground(Color.WHITE);
f.setPreferredSize(new Dimension(600, 600));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
//create JButton
JButton button=new JButton("Enter New Grade");
button.setBounds(450,15,140, 40);
button.addActionListener(e -> average(strArray, i));//gets info from user and adds to strArray
button.addActionListener(e -> count(i));//increases counter
f.add(button);
//create JTable
JTable j = new JTable(strArray, labelArray);
JScrollPane scrollPane = new JScrollPane(j);
j.setBounds(30, 40, 200, 300);
j.setSize(500, 200);
j.setVisible(true);
}
}
all of my code runs as expected except there is no table, I've also tried so many things that didn't work so this basically where I started so that its not crowded by tons of incorrect stuff
You have several problems. First, by default a JFrame uses a BorderLayout. Using the default add(component) method places that component in the center. Using the same add() method again just replaces the new component at the center.
Second, do not pack or set the frame visible until AFTER you have created the entire GUI.
You would do better to create a JPanel and add the components to that panel, then add the panel to the frame. The default layout manager for JPanel is a FlowLayout.

Java split and replace are not working as expected, removing more than regex limiters

I was writing a program and noticed that in certain cases I would run into an exception. I have isolated the problem to my split and replace methods and ran a test in the main method. Code is as follows.
public class tester
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
frame.add(panel, BorderLayout.CENTER);
//create text box
JTextArea textArea = new JTextArea(15,10);
textArea.setEditable(true);
textArea.setText("");
panel.add(textArea);
frame.setVisible(true);
frame.add(panel2, BorderLayout.SOUTH);
String s = textArea.getText().replace("[a-z]", "");
String[] parts = s.split("\\=|\\-|\\/|\\*|\\+|\\[a-z]");
JButton b = new JButton("something");
panel2.add(b);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textArea.setText(s);
}
});
}
}
Specifically at the line in which
String s = textArea.getText().replace("[a-z]", "");
String[] parts = s.split("\\=|\\-|\\/|\\*|\\+|\\[a-z]");
the regex limiters are used.
Typing a test input into the textArea with a string such as 123asdv1+asd-
The expected output once the button should be pressed should be the string:
1231+- when s is called.
However, actual output once pressed is in fact an empty string, blank.
parts is used in my original program to store the numbers into a double variable for use in a calculation, but it was added here for sake of consistency.
It would be very helpful if someone could tell me what i've done wrong, my original program is meant to fetch all the numbers between a special symbol such as + or - to be stored and used for a calculation. If an illegal operation was met, it would print an error message onto the text area and continue from where it left off before the error, this is where I am running into the problem.

Is it possible to change the way my data is currently displayed?

I am using a JTable and after it is filled with data, I have a search button at the bottom with a text input. Once I type in "Joe" it brings up all of joes details. However, these are displayed in one row going left to right (much like a spreadsheet row).
I was wondering if there was a way I can make it display this data in a different way? More like a table rather than going across in one individual row...
Please tell me if I need to show parts of my code as it is quite a bit and I'm unsure if I should paste it all in or not. (New to this site).
Thanks.
Code:
private void makeframe()
{
frame = new JFrame("Search");
frame.setPreferredSize(new Dimension(300, 300));
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
}
DefaultTableModel model = new DefaultTableModel();
model.addColumn("User");
model.addColumn("first name");
model.addColumn("surname");
//this goes on for a while
model.addRow(data);
JTable mainTable = new JTable(model);
contentPane.add(new JScrollPane (mainTable));
frame.setPreferredSize(new Dimension(1300, 200));
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
You can try to create your panel in format you prefer, then use table with only 1 column. Place your pannel inside this column.

How to fit a long String into a JLabel

as the title says: I need to fit a JLabel into a JFrame, but the text in the JLabel are too long, so I need to add some linebreaks. The text in the JLabel are obtained from an online XML file, so i cant just change the text to contain linebreaks.
This code extracts data from the XML-file
Element element = (Element)nodes1.item(i);
String vær = getElementValue(element,"body");
String v = vær.replaceAll("<.*>", "" );
String forecast = "Vær: " + v;
in this case the string I want to add some linebreaks to the string v. The String v contains the parsed data from the xml file. The String forecast is returned and set as a text to the JLabel.
Just ask if something is uncleared, thanks in advance!
I suggest using a JTextArea instead and turning wrapping on. The only way to do it in a JLabel is to put line breaks <br />, which wouldn't work (at least not easily) in your situation if you don't know the text beforehand.
JTextArea is much more flexible. By default it looks different, but you can fiddle around with some of the display properties to make it look like a JLabel.
A simple modified usage example taken from the How to Use Text Areas tutorial -
public class JTextAreaDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
JTextArea textArea = new JTextArea(
"If there is anything the nonconformist hates worse " +
"than a conformist, it's another nonconformist who " +
"doesn't conform to the prevailing standard of nonconformity.",
6,
20);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setOpaque(false);
textArea.setEditable(false);
panel.add(textArea);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
JLabel is able to display HTML text, i.e. if you wrap your text with <html>your text<html> it might be able to wrap the text. That's not tested though, so YMMV.
you can dynamically tell your JLabel to resize itself to fit the text.
if you are not using a LayoutManager try :
jLabel.setText ("A somewaht long message I would not want to
stop");
jLabel.setSize(jLabel.getPreferredSize());
If you are using a Layout Manager this snippet should work:
jLabel.setText ("A somewaht long message I would not want to
stop");
jLabel.validate();

removing horizontal scrollbar for textarea

I'm using Java Swing. I have a textarea in a panel. I don't need a horizontal scrollbar for that textArea, only a vertical scrollbar is needed. I disabled auto scrollbar options, but still the horizontal scrollbar is working. Please help me in thz.
ta.setLineWrap(true)
Sets the line-wrapping policy of the
text area. If set to true the lines
will be wrapped if they are too long
to fit within the allocated width. If
set to false, the lines will always be
unwrapped
Scroll bar comes into text area when you are making your text area too small. This is because your the default column number in netbeans text area is 20.
If you don't want the scroll bar being displayed , then take the textarea properties and change the column number to a value according to your size (say 10).
And the scrollbar will not be shown.
Two examples, the line wrap method and the scroll pane method:
public class Test {
public static void main(String[] args) {
// example text
String rep = "The quick brown fox jumps over the lazy dog.";
String all = rep;
for(int i = 0; i < 100; i++)
all += "\n" + rep;
// create the line wrap example
JTextArea first = new JTextArea(all);
first.setLineWrap(true);
// create the scroll pane example
JScrollPane second =
new JScrollPane(new JTextArea(all),
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// lay it out
JFrame f = new JFrame("Test");
f.setLayout(new GridLayout(1,2));
f.add(first);
f.add(second);
f.setSize(400, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
JTextPane don't have a method to enable or disable line wrap, one best choice is:
private JTextPane noWrapTextPane = new JTextPane() {
#Override
public boolean getScrollableTracksViewportWidth() {
return getUI().getPreferredSize(this).width
<= getParent().getSize().width;
}
};

Categories