How to make the text in an SWT Link widget selectable - java

I have a text in the Link SWT widget created as follow:
Link message = new Link(parent, SWT.WRAP);
message.setText(myMessage);
I want the text (in myMessage variable) be selectable, to grant users to copy it.
How can I do this?
I have used Link widget because I need hyperlinks in the text to be clickable.

The SWT Link widget is not selectable. To work around this I can think of either
provide a context menu for the Link with a Copy menu item that copies the text to the clipboard
place a Copy (tool) button next to the Link that copies the text to the clipboard
use a Browser widget which is selectable but harder to layout and requires extra work to trigger the functinality when the link is selected
if you don't mind the extra dependency to org.eclipse.ui.forms, use the FormText. The FormText can show hyperlinks and allows to select and copy text

Why not using a StyledText to allow text selection ?
String string = "This is sample text with a link and some other link here.";
final StyledText styledText = new StyledText (shell, SWT.MULTI | SWT.BORDER);
styledText.setText(string);
String link1 = "link";
String link2 = "here";
StyleRange style = new StyleRange();
style.underline = true;
style.underlineStyle = SWT.UNDERLINE_LINK;
int[] ranges = {string.indexOf(link1), link1.length(), string.indexOf(link2), link2.length()};
StyleRange[] styles = {style, style};
styledText.setStyleRanges(ranges, styles);
styledText.addListener(SWT.MouseDown, new Listener() {
#Override
public void handleEvent(Event event) {
// It is up to the application to determine when and how a link should be activated.
// In this snippet links are activated on mouse down when the control key is held down
if ((event.stateMask & SWT.MOD1) != 0) {
try {
int offset = styledText.getOffsetAtLocation(new Point (event.x, event.y));
StyleRange style = styledText.getStyleRangeAtOffset(offset);
if (style != null && style.underline && style.underlineStyle == SWT.UNDERLINE_LINK) {
System.out.println("Click on a Link");
}
} catch (IllegalArgumentException e) {
// no character under event.x, event.y
}
}
}
});
Full example here

Related

Apache poi PowerPoint slide masters - not generating footer with page number

I have problem with slide master layout which contains page number and static text. I have them on my layouts but they are not appearing once I'm generating presentation. When I go INSTER --> Page Number I can select and they appear. When I'm adding new slide to my generated presentation via PowerPoint (add slide with selected layout), then it's showing page number for that page.
Here is the code:
String fileName = "slidemaster-010";
String templateLocation = "/Users/akonopko/Export/Templates/Presentation10.pptx";
XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(templateLocation));
XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
XSLFSlideLayout masterLayout = defaultMaster.getLayout("Master");
XSLFSlide slide = ppt.createSlide(masterLayout);
XSLFSlideLayout masterLayout1 = defaultMaster.getLayout("1_Custom Layout");
XSLFSlide slide2 = ppt.createSlide(masterLayout1);
List<XSLFShape> slideShapes = slide2.getShapes();
for (XSLFShape shape : slideShapes) {
if (shape.getPlaceholder() == Placeholder.TITLE) {
((XSLFTextShape) shape).setText("Test Text");
}
}
Apache POI just does not copy the placeholders from the XSLFSlideLayout while XMLSlideShow.createSlide(XSLFSlideLayout). It uses XSLFSlideLayout.copyLayout(XSLFSlide) and there DATETIME, SLIDE_NUMBER and FOOTER is explicitly excluded.
One could write a method which copies those placeholders from the layout. This could look like so:
public void copyPlaceholdersFromLayout(XSLFSlideLayout layout, XSLFSlide slide) {
for (XSLFShape sh : layout.getShapes()) {
if (sh instanceof XSLFTextShape) {
XSLFTextShape tsh = (XSLFTextShape) sh;
Placeholder ph = tsh.getTextType();
if (ph == null) continue;
switch (ph) {
// these are special and not copied by default
case DATETIME:
case SLIDE_NUMBER:
case FOOTER:
System.out.println(ph);
slide.getXmlObject().getCSld().getSpTree().addNewSp().set(tsh.getXmlObject().copy());
break;
default:
//slide.getSpTree().addNewSp().set(tsh.getXmlObject().copy());
//already done
}
}
}
}
Get called like so:
copyPlaceholdersFromLayout(masterLayout1, slide2);
But there might be a reason why apache poi explicitly excludes this.

swing component not fully functioning into javafx application

I have two separate based on Swing and Javafx. Now i need to open Swing application inside Javafx Tab pane by below code
SyntaxTester ob = new SyntaxTester(filepath);
SwingNode swingnode = new SwingNode();
JComponent jcomp = new JComponent() {
};
jcomp.add(ob.getContentPane());
swingnode.setContent(jcomp);
BorderPane borderpane = new BorderPane(swingnode);
tab.setContent(borderpane);
Basically this Swing application is JEditorPane based editor. Swing application is added and working successfully inside Tab pane but the issue is that, there is hinting feature and after selecting text from hint, editor looses it's cursor and user again manually click on the editor. Although Swing application separately working fine. Please help me with resolve it. Thanks in advance.
This is what happening when user select from hint list.
if (jLstItems.getSelectedIndex() >= 0) {
result = jLstItems.getSelectedValue().toString();
} else {
result = jTxtItem.getText();
}
char pressed = evt.getKeyChar();
if (pressed != '\n') {
result += (pressed == '\t') ? ' ' : pressed;
}
setVisible(false);
target.replaceSelection(result);

java awt color chooser does't show in proper way in JavaFx

#FXML
Private void handleItemBackAction(ActionEvent eve)
{
java.awt.Color color=JColorChooser.showDialog(null,"Select a color",java.awt.Color.CYAN);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
hex="#"+hex;
Text.setText(hex);
ShortcutButton.setStyle("-fx-background-color: " + hex + ";");
}
When I run this window and click on button at first time color chooser goes behind my actual pane.
When I click on button second time while running it shows at top of all other pane which is correct and so on it works properly.
Then why color chooser not shows in front first time on button click?
The first argument to JColorChooser.showDialog is the parent component of the dialog. You told that method to show the dialog with no parent, so it doesn't know about your other windows.
Instead of using JColorChooser.showDialog, you'll need to embed a JColorChooser instance inside a JavaFX dialog or window:
JColorChooser colorChooser = new JColorChooser(java.awt.Color.CYAN);
SwingNode colorChooserNode = new SwingNode();
colorChooserNode.setContent(colorChooser);
Alert dialog = new Alert(Alert.AlertType.NONE);
// Guarantees dialog will be above (and will block input to) mainStage.
dialog.initOwner(mainStage);
dialog.setTitle("Select a color");
dialog.getDialogPane().setContent(colorChooserNode);
dialog.getDialogPane().getButtonTypes().setAll(
ButtonType.OK, ButtonType.CANCEL);
Optional<ButtonType> response = dialog.showAndWait();
if (response.filter(r -> r == ButtonType.OK).isPresent()) {
int rgb = colorChooser.getColor().getRGB();
String hex = String.format("#%06x", rgb & 0xffffff);
Text.setText(hex);
ShortcutButton.setBackground(new Background(
new BackgroundFill(Color.valueOf(hex), null, null)));
} else {
System.out.println("User canceled");
}
Of course, you're probably better off using ColorPicker in your main window, so you don't have to create an explicit dialog at all:
final ColorPicker colorPicker = new ColorPicker(Color.CYAN);
colorPicker.setOnAction(e -> {
Color color = colorPicker.getValue();
String hex = String.format("#%02x02x02x",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
Text.setText(hex);
ShortcutButton.setBackground(
new Background(new BackgroundFill(color, null, null)));
});
myLayoutPane.getChildren().add(colorPicker);
As an aside, Java variable names should always start with a lowercase letter, to make them easy to distinguish from class names. Consider changing Text to text, and ShortcutButton to shortcutButton.

JTextPane - HTMLDocument: when adding/removing a new style, other attributes also changes

I have a JTextPane (or JEditorPane) in which I want to add some buttons to format text (as shown in the picture).
When I change the selected text to Bold (making a new Style), the font family (and others attributes) also changes. Why? I want to set (or remove) the bold attribute in the selected text and other stays unchanged, as they were.
This is what I'm trying:
private void setBold(boolean flag){
HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
int start = editorPane.getSelectionStart();
int end = editorPane.getSelectedText().length();
StyleContext ss = doc.getStyleSheet();
//check if BoldStyle exists and then add / remove it
Style style = ss.getStyle("BoldStyle");
if(style == null){
style = ss.addStyle("BoldStyle", null);
style.addAttribute(StyleConstants.Bold, true);
} else {
style.addAttribute(StyleConstants.Bold, false);
ss.removeStyle("BoldStyle");
}
doc.setCharacterAttributes(start, end, style, true);
}
But as I explained above, other attributes also change:
Any help will be appreciated. Thanks in advance!
http://oi40.tinypic.com/riuec9.jpg
What you are trying to do can be accomplished with one of the following two lines of code:
new StyledEditorKit.BoldAction().actionPerformed(null);
or
editorPane.getActionMap().get("font-bold").actionPerformed(null);
... where editorPane is an instance of JEditorPane of course.
Both will seamlessly take care of any attributes already defined and supports text selection.
Regarding your code, it does not work with previously styled text because you are overwriting the corresponding attributes with nothing. I mean, you never gather the values for the attributes already set for the current selected text using, say, the getAttributes() method. So, you are effectively resetting them to whatever default the global stylesheet specifies.
The good news is you don't need to worry about all this if you use one of the snippets above. Hope that helps.
I made some minor modifications to your code and it worked here:
private void setBold(boolean flag){
HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
int start = editorPane.getSelectionStart();
int end = editorPane.getSelectionEnd();
if (start == end) {
return;
}
if (start > end) {
int life = start;
start = end;
end = life;
}
StyleContext ss = doc.getStyleSheet();
//check if BoldStyle exists and then add / remove it
Style style = ss.getStyle(editorPane.getSelectedText());
if(style == null){
style = ss.addStyle(editorPane.getSelectedText(), null);
style.addAttribute(StyleConstants.Bold, true);
} else {
style.addAttribute(StyleConstants.Bold, false);
ss.removeStyle(editorPane.getSelectedText());
}
doc.setCharacterAttributes(start, end - start, style, true);
}

How to set font color for selected text in jTextArea?

I have to set defined color(like red) for selected text in jTextArea. It is like highlighting process in text area (jTextArea). When I select particular text and click on any button it should change in predefined color.
I can change jTextArea to jTextPane or JEditorPane if there is any solution.
Styled text (with a color attribute for characters) is available as StyledDocument, and usable in JTextPane and JEditorPane. So use a JTextPane.
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
StyledDocument doc = textPane.getStyledDocument();
int start = textPane.getSelectionStart();
int end = textPane.getSelectionEnd();
if (start == end) { // No selection, cursor position.
return;
}
if (start > end) { // Backwards selection?
int life = start;
start = end;
end = life;
}
Style style = textPane.addStyle("MyHilite", null);
StyleConstants.setForeground(style, Color.GREEN.darker());
//style = textPane.getStyle("MyHilite");
doc.setCharacterAttributes(start, end - start, style, false);
}
Mind: the style can be set at the creation of the JTextPane, and as the outcommented code shows, retrieved out of the JTextPane field.
First of all you can not do this using JTextArea because it is a plain text area.You have to use a styled text area like JEditorPane.see here.You can use a HTMLDocument and do what you want.See here

Categories