Reputation: 35276
Here's my code where I tried to make a TextArea autogrow:
textArea.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
int lines = 0;
final String s = textArea.getText();
for(int i = 0; i != -1; i = s.indexOf("\n", i + 1)) {
lines++;
}
if (((int)event.getCharCode()) == 13) { // User hit "Enter" key
lines++;
}
if(textArea.getVisibleLines() < lines) {
textArea.setVisibleLines(lines);
}
}
});
However this does not work at all.
What I need is
Given than the TextArea have been rendered with default height and width initially. Also if the text exceeds the width, a scroll left, right bar should show up.
Upvotes: 0
Views: 1915
Reputation: 2948
I am using this approach to do something similar.
textArea.setVisibleLines(1);
textArea.addKeyUpHandler(new KeyUpHandler()
{
@Override
public void onKeyUp(KeyUpEvent event)
{
textArea.setHeight("auto");
textArea.setHeight(textArea.getElement().getScrollHeight() + "px");
}
});
I am also applying these styles to fit my needs
.textArea {
resize: none;
overflow: hidden;
}
Upvotes: 1
Reputation: 46841
Here is the solutions:
Shink the TextArea as user remove lines
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
public void onModuleLoad() {
final TextArea textArea=new TextArea();
textArea.setStyleName("textboxStyle");
textArea.getElement().getStyle().setOverflow(Overflow.AUTO);
textArea.getElement().setAttribute("wrap","off");
textArea.setVisibleLines(1);
textArea.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
System.out.println("Value changed");
}
});
textArea.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
int lines = 0;
final String s = textArea.getText();
for (int i = 0; i != -1; i = s.indexOf("\n", i + 1)) {
lines++;
}
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) { // User hit "Enter"
// key
lines++;
}
textArea.setVisibleLines(lines);
}
});
RootPanel.get().add(textArea);
}
Should also be able to handle "CTRL + V" and paste text event
Yes you can handle it using addChangeHandler
method
textArea.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
System.out.println("Value changed");
}
});
if the text exceeds the width, a scroll left, right bar should show up.
textArea.getElement().setAttribute("wrap","off");
css applied
.textboxStyle{
font-family: sans-serif;
font-size: 12px;
font-weight: normal;
}
screeenshots
Upvotes: 0