Control image placement on JTextPane - jtextpane

I am able to add ImageIcons to a JTextPane, but when I add them they show up in the center of the JTextPane. I can't find a way to control where they are placed on the JTextPane. Can someone please help me with this?
This method is making the JTextPane:
private void loadTextPanel(JPanel contentPane) {
chatLogPanel = new JPanel();
chatLogPanel.setLayout(null);
EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));
DefaultStyledDocument document = new DefaultStyledDocument();
chatLog = new JTextPane(document);
chatLog.setEditorKit(new WrapEditorKit());
chatLog.setBorder(eb);
chatLog.setMargin(new Insets(5, 5, 5, 5));
chatLogScrollPane = new JScrollPane(chatLog);
addComponent(chatLogPanel, chatLogScrollPane, 0, 0, 500, 240);
addComponent(contentPane, chatLogPanel, 0, 40, 500, 240);
}
This is the code I'm using to add a string to the Panel:
private static void appendToChatLog(JTextPane tp, String msg, Color c) {
chatLog.setEditable(true);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, Integer.valueOf(3));
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
tp.replaceSelection(msg);
chatLog.setEditable(false);
}
And this is what I'm currently using to add the image to the JTextPane:
BufferedImage image = generateBufferedImage(message.getImage());
Icon icon = new ImageIcon(image);
StyleContext context = new StyleContext();
StyledDocument document = (StyledDocument) chatLog.getDocument();
Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);
JLabel label = new JLabel(icon);
StyleConstants.setComponent(labelStyle, label);
try {
document.insertString(document.getLength(), "Ignored", labelStyle);
} catch (BadLocationException badLocationException) {
badLocationException.printStackTrace();
}

To insert a component to a JTextPane, and display it like a character, use the insertComponent method.
To insert an Icon instead, use the insertIcon method.
Quite intuitive isn't it ;)

Related

How do I change the background color of a tabbed page in Xamarin iOS?

I need to change the background color of the currently tabbed page in my UITabBarController. I've searched through every stackoverflow post I could find but nothing worked for me. I thought there would be something like UITabBar.Appearance.SelectedImageTintColor, just for the background color but it doesn't seem so.
For example, I want to change the color of that part when I am on the right tab:
Does someone know how to do that?
You could invoked the following code in your UITabBarController
public xxxTabBarController()
{
//...set ViewControllers
this.TabBar.BarTintColor = UIColor.Red;
}
Update
//3.0 here is if you have three child page in tab , set it as the current value in your project
//
var size = new CGSize(TabBar.Frame.Width / 3.0, IsFullScreen());
this.TabBar.SelectionIndicatorImage = ImageWithColor(size,UIColor.Green);
double IsFullScreen()
{
double height = 64;
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
if (UIApplication.SharedApplication.Delegate.GetWindow().SafeAreaInsets.Bottom > 0.0)
{
height = 84;
}
}
return height;
}
UIImage ImageWithColor(CGSize size, UIColor color)
{
var rect = new CGRect(0, 0, size.Width, size.Height);
UIGraphics.BeginImageContextWithOptions(size, false, 0);
CGContext context = UIGraphics.GetCurrentContext();
context.SetFillColor(color.CGColor);
context.FillRect(rect);
UIImage image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
The trick is to use the SelectionIndicatorImage Property of the UITabBar and generate a completely filled image with your desired color using the following method:
private UIImage ImageWithColor(CGSize size)
{
CGRect rect = new CGRect(0, 0, size.Width, size.Height);
UIGraphics.BeginImageContext(size);
using (CGContext context = UIGraphics.GetCurrentContext())
{
context.SetFillColor(UIColor.Green); //change color if necessary
context.FillRect(rect);
}
UIImage image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
To initialize everything we override ViewWillLayoutSubviews() like this:
public override void ViewWillLayoutSubviews()
{
base.ViewWillLayoutSubviews();
// The tabbar height will always be 49 unless we force it to reevaluate it's size on runtime ...
myTabBar.InvalidateIntrinsicContentSize();
double height = myTabBar.Frame.Height;
CGSize size = new CGSize(new nfloat(myTabBar.Frame.Width / myTabBar.Items.Length, height));
// Now get our all-green image...
UIImage image = ImageWithColor(size);
// And set it as the selection indicator
myTabBar.SelectionIndicatorImage = image;
}
As mentioned in this article (google translating it step by step when necessary lol) calling InvalidateIntrinsicContentSize() will force the UITabBar to reevaluate it's size and will get you the actual runtime height of the tab bar (instead of the constant 49 height value from XCode).

Custom Toolbar in UINavigation Controller

I am having trouble understanding what approach to take to customize my own Toolbar in Xamarin.ios. The Navigation controller comes with its own default toolbar but how can i change the height and have my own buttons, background image.
What is the best approach for the above ?
You can create a custom navigationBar as you want .
public class xxxViewController: UIViewController
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
NavigationController.NavigationBar.Hidden = true;
double height = IsiphoneX();
UIView backView = new UIView()
{
BackgroundColor = UIColor.White,
Frame = new CGRect(0,20,UIScreen.MainScreen.Bounds.Width, height),
};
UIButton backBtn = new UIButton() {
Frame = new CGRect(20, height-44, 40, 44),
Font = UIFont.SystemFontOfSize(18),
} ;
backBtn.SetTitle("Back", UIControlState.Normal);
backBtn.SetTitleColor(UIColor.Blue, UIControlState.Normal);
backBtn.AddTarget(this,new Selector("GoBack"),UIControlEvent.TouchUpInside);
UILabel titleLabel = new UILabel() {
Frame=new CGRect(UIScreen.MainScreen.Bounds.Width/2-75, 0,150, height),
Font = UIFont.SystemFontOfSize(20),
Text = "xxx",
TextColor = UIColor.Black,
Lines = 0,
};
UILabel line = new UILabel() {
Frame = new CGRect(0, height, UIScreen.MainScreen.Bounds.Width, 0.5),
BackgroundColor = UIColor.Black,
};
backView.AddSubview(backBtn);
backView.AddSubview(titleLabel);
backView.AddSubview(line);
View.AddSubview(backView);
}
double IsiphoneX()
{
double height = 44;
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
if (UIApplication.SharedApplication.Delegate.GetWindow().SafeAreaInsets.Bottom > 0.0)
{
height = 64;
}
}
return height;
}
[Export("GoBack")]
void GoBack()
{
NavigationController.PopViewController(true);
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
NavigationController.NavigationBar.Hidden = false;
}
}
You can set the property of title , backButton and navigationBar as you need (such as text , color ,BackgroundColor ,font e.g.)

Programmatically display a message next to text field in JavaFX

I have a TextField in my JavaFX application. I want to programmatically display a message on the right side of the text (like the validation message). I thought of using Popup and setting the Label with message in that Popup. But I'm not sure how I can position this to the right side of the text field. Below is the sample code for this. Can you please help me with this?
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX Welcome");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Text scenetitle = new Text("Welcome");
scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
grid.add(scenetitle, 0, 0, 2, 1);
Label userName = new Label("User Name:");
grid.add(userName, 0, 1);
TextField userTextField = new TextField();
grid.add(userTextField, 1, 1);
Label pw = new Label("Password:");
grid.add(pw, 0, 2);
PasswordField pwBox = new PasswordField();
grid.add(pwBox, 1, 2);
Label label=new Label();
label.setText("This is an error message");
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 6);
final Popup popup = new Popup();
popup.getContent().add(label);
//Want to display this popup to the right of the userTextField.
Scene scene = new Scene(grid, 300, 275);
primaryStage.setScene(scene);
primaryStage.show();
}
After showing the stage, do
Bounds userTextFieldBounds = userTextField.getBoundsInLocal();
Point2D popupLocation = userTextField.localToScreen(userTextFieldBounds.getMaxX(), userTextFieldBounds.getMinY());
popup.show(userTextField, popupLocation.getX(), popupLocation.getY());
The localToScreen(...) method was introduced in Java 8; if you are in an earlier version you will need
Bounds userTextFieldBounds = userTextField.getBoundsInLocal();
Point2D popupLocation = userTextField.localToScene(userTextFieldBounds.getMaxX(), userTextFieldBounds.getMinY());
popup.show(userTextField,
popupLocation.getX()+scene.getX()+primaryStage.getX(),
popupLocation.getY()+scene.getY()+primaryStage.getY());

JavaFX ScrollPane showing objects outside of viewport

In my current application I have created a ScrollPane with an AnchorPane as content. Depending on the actions of the user this AnchorPane will be filled with more or less images for which I use a Canvas(necessary for drawing more information on the image).
However when I scroll through the ScrollPane, all the child images are still being repainted even when they aren't inside the ViewPort. Has anyone else had this problem or a solution for this?
screenshot:
https://dl.dropboxusercontent.com/u/51537629/images%20drawn%20outside%20of%20viewport.png
Initialization of the scrollpane:
iconPane = new AnchorPane();
iconPane.setStyle("-fx-background-color: white; -fx-border-color: gray;");
iconPane.setMinHeight(546);
iconPane.setMinWidth(814);
scrollpane = new ScrollPane();
scrollpane.setContent(iconPane);
scrollpane.setVisible(false);
AnchorPane.setTopAnchor(scrollpane, 13.0);
AnchorPane.setBottomAnchor(scrollpane, 13.0);
AnchorPane.setLeftAnchor(scrollpane, 13.0);
AnchorPane.setRightAnchor(scrollpane, 13.0);
Creation of an icon:
private VBox createIconPane(TaskInformation tinfo) {
VBox vbox = new VBox();
Canvas canvas = new Canvas(75, 75);
GraphicsContext gc = canvas.getGraphicsContext2D();
Image im;
if (tinfo.getCurrent() != null) {
if (tinfo.isCurrentStop()) {
String status = utilities.getCurrentTaskVersion(tinfo.getTask()).getStatus();
if (status.equals("finished")) {
im = new Image(this.getClass().getClassLoader().getResourceAsStream("dna-current.png"));
} else if (status.equals("failed")) {
im = new Image(this.getClass().getClassLoader().getResourceAsStream("dna-failed.png"));
} else {
im = new Image(this.getClass().getClassLoader().getResourceAsStream("dna-processing.png"));
}
} else {
im = new Image(this.getClass().getClassLoader().getResourceAsStream("dna-current.png"));
}
} else {
im = new Image(this.getClass().getClassLoader().getResourceAsStream("dna-excluded.png"));
}
gc.drawImage(im, 5, 5);
gc.setStroke(Color.GREEN);
gc.strokeText(tinfo.getFinished() + "", 59, 15);
gc.setStroke(Color.RED);
gc.strokeText(tinfo.getFailed() + "", 59, 28);
gc.setStroke(Color.BLUE);
gc.strokeText(tinfo.getProcessing() + "", 59, 41);
Label namelabel = new Label(tinfo.getTask().getName());
namelabel.setLayoutX(0);
namelabel.setLayoutY(68);
vbox.getChildren().addAll(canvas,
return vbox;
}
Addition of all icons to the view:
private void createChildIcon(TaskInformation tinfo) {
VBox taskicon = createIconPane(tinfo);
taskicon.setLayoutX((tinfo.getTask().getLevel() - 6) / 2 * 120 + 5);
if (tinfo.getTask().getLevel() <= levelLastAddedTask && maxYCoor != 5) {
maxYCoor += 95;
}
levelLastAddedTask = tinfo.getTask().getLevel();
taskicon.setLayoutY(maxYCoor);
iconPane.getChildren().add(taskicon);
for (int count = 0; count < tinfo.getChildren().size(); count++) {
createChildIcon(tinfo.getChildren().get(count));
}
}
JDK: 7, but it can be compiled as older versions as well
JFX: 2.2.21
After some testing with one of my colleagues we discovered that it must be a Windows issue. It works perfectly on Linux, but not on Windows.
Try adding VM option "-Dprism.order=j2d". This is a work-around rather than a solution because it is replacing your hardware accelerated graphic pipeline with a software pipeline. If this works, add VM option "-Dprism.verbose=true" so that we can see what hardware was problematic.
I added a bug in the JavaFX Issue Tracker: https://javafx-jira.kenai.com/browse/RT-31044.

Change color title UITable static section

I have two UITable static sections in my application with both different headers.
The color of the header must be changed because the custom background.
How can I do this solution like ( link ) in my MonoTouch application?
Because I use static sections, I don't have a UITableViewSource where I can do stuff in.
My solution (thanks to Krumelur)
[Export("tableView:viewForHeaderInSection:")]
UIView GetViewForHeaderInSecion (UITableView tableview, int section)
{
UIView view = new UIView (new RectangleF (0, 0, 300, 0));
view.BackgroundColor = UIColor.Clear;
UILabel label = new UILabel (new RectangleF (15, 5, 300, 25));
label.BackgroundColor = UIColor.Clear;
label.TextColor = UIColor.White;
label.ShadowColor = UIColor.Black;
label.ShadowOffset = new SizeF(0, 1);
label.Font = UIFont.BoldSystemFontOfSize(18);
if (section == 0) {
label.Text = "First section";
} else {
label.Text = "Second section";
}
view.AddSubview(label);
return view;
}
You'll have to export the missing method in your controller. Something like:
[Export("tableView:viewForHeaderInSection:")]
UIView GetViewForHeaderInSection(UITableView tableview, int section
{
// return your UIView with whatever background color here
}
Note that you cannot change the color of the predefined view but have to return an entire view instead.

Resources