Java Swing TextArea "Sticky Text" [duplicate] - java

This question already has answers here:
JTextField in which the predefined text in not editable but other text can be appended to it?
(5 answers)
Closed 7 years ago.
I am trying to create a TextArea using java that contains text that cannot be deleted/updated. That being said, the user can still add to the TextArea and delete their own text.
I've tried to play around with getting the length of the TextArea and listening for the 'backspace' keypress however I can still select all the text in the TextArea and replace it.
Example Code
(TA is the TextArea)
TA.setText(cmdx);
cmdLength = TA.getDocument().getLength();
TA.getKeymap().addActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
TA.disable();
try {
backSpace();
} catch (BadLocationException ex) {
Logger.getLogger(CmdFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
AND
public void backSpace() throws BadLocationException {
System.out.println("Backspace is pressed");
int currentLength = TA.getDocument().getLength();
if(currentLength > cmdLength)
{
Document doc = TA.getDocument();
doc.remove(doc.getLength() - 1, 1);
TA.enable();
}
}
I apologize if this question has already been asked.
Thank you in Advance!

Don't let the user directly type in text but catch the respective event and manually set the text to the textField. Then you can implement a check (for example if the text is starting with your sticky text) and if not add it at the beginning again. If it does then simply add the typed key at the end of the text.
Look here for more solutions

Related

How to place foreign characters to a PDF in itextpdf like 'ő' or 'ű'?

I have a function to place my text to the document into something like a table.
private static void addCenteredParagraph(Document document, float width, String text) {
PdfFont timesNewRomanBold = null;
try {
timesNewRomanBold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
} catch (IOException e) {
LOGGER.error("Failed to create Times New Roman Bold font.");
LOGGER.error(e);
}
List<TabStop> tabStops = new ArrayList<>();
// Create a TabStop at the middle of the page
tabStops.add(new TabStop(width / 2, TabAlignment.CENTER));
// Create a TabStop at the end of the page
tabStops.add(new TabStop(width, TabAlignment.LEFT));
Paragraph p = new Paragraph().addTabStops(tabStops).setFontSize(14);
if (timesNewRomanBold != null) {
p.setFont(timesNewRomanBold);
}
p.add(new Tab()).add(text).add(new Tab());
document.add(p);
}
But my problem is it shows empty characters in the exported PDF instead of the letters ő,Ő,ű,Ű.
The Times New Roman supports these characters, so I think I need to set it to UTF8, but I couldn't find a workaround on Google to do it.
Can someone please explain how to make these characters appear properly on the pdf?
Tried these, but some of them are deprecated functions, or not applicable with my arguments I'm trying to give them, or I don't use Chunk.
Itext PDF writer, Is there any way to allow unicode subscript symbol in the pdf? (Without setTextRise)
How can I set encoding for iText when I insert value to placeholder in pdf form?
Edit: I figured out, that timesNewRomanBold is null, even if I set it to HELVETICA, or COURIER.

SceneBuilder JavaFX using a Textbox, create a new line as per comma, from data received

I am building a tradebot, and I created my own UI. I gather data about my account via the API, and setText into a text field (as image shows). What I want to do, is be able to create a new line using the commas as a break, or be able to make some sort of excel table to separate the data and make it easy to use.
When I call for the data, it just dumps everything into a long, line of text.
Any suggestions on how to achieve this?
thanks,
Arthur
#FXML
void onPositionClick(ActionEvent event)
{
Context ctx = new Context("https://api-fxpractice.oanda.com", "XXXXXXXXXXXXXXXXXXXXXX-YYYYYYYYYYYYYYYYYYYYYYYY");
try
{
AccountSummary summary = ctx.account.summary(
new AccountID("101-XXX-XXXXXX-XXX")).getAccount();
String summaryString = String.valueOf(summary);
displayResults.setText(summaryString);
} //end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
I would use System.lineSeparator() because its system-dependent:
String text = "abc,de,fghi,jklmn,o";
String newText = text.replaceAll(",", System.lineSeparator());
System.out.println(newText);
Output:
abc
de
fghi
jklmn
o

Moving both text and icons from one JTextPane to another

I'm currently making a GUI for a chat room. I've made it so the user enters text and can pick images that end up in a JTextPane. After the user presses enter I want to display it in another JTextPane though. Is there an easy way to move both text and icons from one JTextPane to another at the same time? I've only managed to move one of them at a time.
You can use an ElementIterator to copy over a JTextPane’s StyledDocument element by element, with all styling, including icons:
static void copy(Document source,
Document dest) {
try {
dest.remove(0, dest.getLength());
ElementIterator iterator = new ElementIterator(source);
Element element;
while ((element = iterator.next()) != null) {
if (element.isLeaf()) {
int start = element.getStartOffset();
int end = element.getEndOffset();
String text = source.getText(start, end - start);
dest.insertString(dest.getLength(), text,
element.getAttributes());
}
}
} catch (BadLocationException e) {
throw new RuntimeException(e);
}
}

How to add multiple data in JTextField?

I want to add data from JTextField but if I pressed the process again, the data that I write is missing. Is there any solution for this code?
try{
txttujuan.removeAll();
int xxx=0;
String XNilai,Nilai;
for (xxx=0;xxx <jtable.getRowCount();xxx++){
if (jtable.getValueAt(xxx,4).equals("1")){
Nilai ="0"+ (String) jtable.getValueAt(xxx,2);
XNilai+=Nilai+",";
} else continue;
System.out.print(XNilai.substring(0,XNilai.lastIndexOf(",")));
jtextfield.setText();
jtextfield.setText(XNilai.substring(0,XNilai.lastIndexOf(",")));
XNilai="";
}
} catch (Exception e){
System.out.print(e);
}
my data i've already wrote is missing
That is what the setText() method does. It replaces the existing text with the new text.
Instead of using a JTextField you can try using a JTextArea, then you can use the following to add text to the end:
textArea.append( "some text" );
If you really want to use a JTextField then you can use:
Document doc = textField.getDocument();
doc.insertString("some text", doc.getLength(), null);
to append text to the text field.

java - how to make an xml into a hyperlink? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to add hyperlink in JLabel
In my program, I am searching through an index using Lucene and I am retrieving files. I have created XML files for the retrieved docs from the Lucene's search. Now, I want to make these XML files as hyperlinks and display to the user as the search results. That is I want the XML files to be open when the user clicks on this hyperlink. Any help appreciated!?
for(int i=0;i<file_count;i++)
{
file=str+index[i]+".xml";
JLabel label = new JLabel(file,JLabel.CENTER );
label.setOpaque(true);
label.setBackground(Color.RED);
panel.add(label) ;
label.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() > 0)
{
Runtime r= Runtime.getRuntime();
try {
System.out.println("testing : Inside mouseclicked");
Process p = r.exec("cmd.exe /c start "+file);
System.out.println("opened the file");
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.out.println();
}
}
}
});
}
Here is the code that I have made. In this, I am suppose to get output on the screen "file_count" no of times. I am getting that but what is happening is all the links are showing the same file when clicked. Help?
If I do understand your question correctly, you want to allow the user to open a file. The Desktop class (available as of JDK1.6) allows this
File fileToOpen = ...;
Desktop desktop = Desktop.getDesktop();
desktop.open( fileToOpen )
Depending on how you want to present this to the user, you can opt for your JLabel code with the listener but it is probably easier to use a JButton with an ActionListener. Both approaches are discussed in detail in the answer Marko Topolnik already suggested in his comment. The only difference is that they wanted to open an URL, while you want to open a file (so that answer uses the browse method instead of the open method of the Desktop class).

Categories