Applet - align text to bottom middle - java

Is there a way to align text from g.drawString() to the bottom center of a java applet?
I am also hoping for a way that is fluid between full-screen and small screen.

Yes, start by taking a look at Measuring Text
String text = "Happy at the bottom";
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() - fm.stringWidth(text)) / 2;
int y = (getHeight() - fm.getHeight()) + fm.getAscent();
g.drawString(text, x, y);
The next question that needs to asked, is could what you want be achieved by using a JLabel and a BorderLayout (or other compound layout)....?

Related

How to center a text in a rectangle in JavaFX

I am trying to draw a string exactly in the center of a rectangle using JavaFX GraphicsContext2D.
I don't want to use JavaFX components so please do not recommend them.
For example, I stroke a rectangle with attributes: x = 10, y = 10, width = 100, height = 100. Now I want to stroke a text in a way that it comes exactly in the center(horizontally and vertically) of the rectangle. How can I do it?
As #James_D comments, you can use the GraphicsContext methods setTextAlign() and setTextBaseline() to center the fillText() in an arbitrary Rectangle. Starting from this example, I added the following lines in the tooltips loop in order to produce the image shown:
gc.setTextAlign(TextAlignment.CENTER);
gc.setTextBaseline(VPos.CENTER);
gc.setFill(Color.BLACK);
gc.fillText(color.toString(),
bounds.getX() + bounds.getWidth() / 2,
bounds.getY() + bounds.getHeight() / 2);

JavaFX center view on cursor position

I created my first JavaFX app that displays images. I want it to zoom the image to full size on mouse down (centered on cursor position) and to refit the image on mouse up.
All is working fine but the i don't know how to center on cursor position. My zoom method looks like that at the moment:
private void zoom100(double cursorx, double cursory){
double centery = imageView.getLayoutBounds().getHeight()/2;
double centerx = imageView.getLayoutBounds().getWidth()/2;
imageView.setFitHeight(-1); //zooms height to 100%
imageView.setFitWidth(-1); //zooms width to 100%
imageView.setTranslateX(centerx-cursorx); //moves x
imageView.setTranslateY(centery-cursory); //moves y
}
My idea is to set an offset with translate. I am not sure if translate is the correct approach. If it is the correct approach how to calculate the correct values? (centerx-cursorx) is wrong!
I uploaded the code here: https://github.com/dermoritz/FastImageViewer (it is working now - see my answer)
I didn't test it but I think the order is wrong. you calculate the center before you set the fit size. By setting the fit size your image view will change it's preferred size. therefore the center point won't match anymore.
I found a solution, but i am still not sure if this is a good way to go:
private void zoom100(double x, double y) {
double oldHeight = imageView.getBoundsInLocal().getHeight();
double oldWidth = imageView.getBoundsInLocal().getWidth();
boolean heightLarger = oldHeight>oldWidth;
imageView.setFitHeight(-1);
imageView.setFitWidth(-1);
//calculate scale factor
double scale=1;
if(heightLarger){
scale = imageView.getBoundsInLocal().getHeight()/oldHeight;
}else {
scale = imageView.getBoundsInLocal().getWidth()/oldWidth;
}
double centery = root.getLayoutBounds().getHeight() / 2;
double centerx = root.getLayoutBounds().getWidth() / 2;
double xOffset = scale * (centerx - x);
double yOffset = scale *(centery - y);
imageView.setTranslateX(xOffset);
imageView.setTranslateY(yOffset);
}
The picture must be centered within "root". I think there should be something more direct - only using properties of imageview?!
Meanwhile the app works using this code: https://github.com/dermoritz/FastImageViewer

Fonts - How to position top-left corner of a string?

Let's say I want to use the java.awt.Graphics.drawString(String str, int x, int y) method to draw a string at some specific coordinates, say somewhere like (300, 300). However the drawString() method will always position the bottom-left-hand corner of the string at those coordinates, not the top-left-hand corner which is what I want.
What's an easy way to draw the top-left hand corner of a string at a specified coordinate? I am aware of the java.awt.FontMetrics utility class but quite sure if it can be helpful.
FontMetrics is the class to use:
public static int getStringAscent(Graphics page, Font f, String s) {
// Find the size of string s in the font of the Graphics context "page"
FontMetrics fm = page.getFontMetrics(f);
return fm.getAscent();
}
The ascent is the maximum height glyphs of the given string raise from the baseline. The start of the baseline is the reference point for the drawString method, and therefore the ascent is the distance with which you must adjust the coordinate. If you use this to draw a String using Graphics2D g:
g.drawString(msg, x, y);
you can shift it down by the ascender height for Font f:
Font small = new Font("Helvetica", Font.BOLD, 24);
FontMetrics metrics = getFontMetrics(small);
int d = metrics.getAscent();
g.drawString(msg, x, y + d );
Try this:
FontMetrics metric = g.getFontMetrics(g.getFont());
g.drawString(str, x, y + metric.getAscent() - metric.getDescent() - metric.getLeading());

setLocation of 2 frames in the middle of the screen

I need to center two JFrame side by side on the screen (for instance as if they were a single frame centered).
To center a single JFrame I used the command:
frame.setLocationRelativeTo(null);
How can I resolve now?
You need to know three things...
The available visible area of the screen
The size of both windows...(this counts as two)
There are a few ways to get the screen size, but what you really want is the viewable area, the area within which it is safe to show windows...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
// Use this if need to know about a device which is not the default...
//GraphicsDevice lstGDs[] = ge.getScreenDevices();
GraphicsDevice device = ge.getDefaultScreenDevice();
GraphicsConfiguration cf = device.getDefaultConfiguration();
Rectangle bounds = cf.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);
This now tells you the area within which it is safe to show content, taking into consideration things like the taskbar/dock that some OS's have...
Next, you need to know the size of the window...
frameA.pack();
frameB.pack();
Dimension dimA = frameA.getSize();
Dimension dimB = frameB.getSize();
Now, you need to calculate the position of the windows...
Point pA = new Point(
bounds.x + ((bounds.width / 2) - dimA.width),
bounds.y + ((bounds.height- dimA.height) / 2));
Point pB = new Point(
bounds.x + (bounds.width / 2),
bounds.y + ((bounds.height- dimB.height) / 2));
And there you have it...
Now, having said all that, you might like to take a look at The Use of Multiple JFrames, Good/Bad Practice? and How to Use Split Panes
You can manually set the position of your frame with #setLocation I think

How to get the center x and y of desktop with swing

I want my jframe to open in the center of a person's monitor.
(By default a jframe will open at coordinate. (0,0))
To achieve this, before setting the frame visible, I use this method.
this.setLocation(x,y);
In theory, monitor screen sizes can be different, meaning the center coordinate will be different for almost all computers.
HERES MY QUESTION:
How would I get the center coordinate of the computer monitor running the swing application?
How would I get the center coordinate of the computer monitor running the swing application?
You can get the center coordinate with java.awt.Toolkit:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int centerX = screenSize.width/2;
int centerY = screenSize.height/2;
However, you don't need it.
Just use:
yourFrame.setLocationRelativeTo(null);
And it will be automatically centered
Try it
//call `setSize` first
this.setSize(300, 600);
Toolkit tk = this.getToolkit();
Dimension dim = tk.getScreenSize();
int x = (int) dim.getWidth() / 2 - this.getWidth() / 2;
int y = (int) dim.getHeight() / 2 - this.getHeight() / 2;
this.setLocation(x, y);
Here this represents JFrame class object.
JFrame will display in the center of the screen.
Query the Toolkit object.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int centerX = screenSize.getWidth() / 2;
int centerY = screenSize.getHeight() / 2;
Swing's documentation states that the window will be centered on screen if setRelativeTo is passed null.
public void setLocationRelativeTo(Component c)
As stated in their docs:
"If the component is null, or the GraphicsConfiguration associated with
this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method."
http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setLocationRelativeTo(java.awt.Component)
So simply do:
frame.setLocationRelativeTo(null);
..since your question was really how to get it to open in the center, not how to get the center coordinate.

Categories