I want to know how to center the JFrame title.I referred following link
How to center align the title in a JFrame?
but I need to center title without putting spacing.
Consider leaving the title left-justified...but...this will get you near the center. For resizable frames, you need to rewrite the title on resize.
JFrame t = new JFrame();
t.setSize(600,300);
t.setFont(new Font("System", Font.PLAIN, 14));
Font f = t.getFont();
FontMetrics fm = t.getFontMetrics(f);
int x = fm.stringWidth("Hello Center");
int y = fm.stringWidth(" ");
int z = t.getWidth()/2 - (x/2);
int w = z/y;
String pad ="";
//for (int i=0; i!=w; i++) pad +=" ";
pad = String.format("%"+w+"s", pad);
t.setTitle(pad+"Hello Center");
https://stackoverflow.com/a/9662974/3675925
Thats the only way to do it in Swing. Take note that adding spaces to center the window's title will affect other platforms. For example, for Windows 7 the title is displayed on the top-left, however on Windows 8 the title will be displayed on the top-center. Unless you want to specifically check what OS the client is running, I suggest just leaving the title as it is.
Related
I have a JeditorPane in a JScrollPane. At certain points in the application, I would like to retrieve the text that is visible in the scrollPane (the text that is currently showing) and only this text. Is there a way to do this?
Thank you,
Elliott
You can use the viewport to get the view position and size.
JViewport viewport = scrollPane.getViewport();
Point startPoint = viewport.getViewPosition();
Dimension size = viewport.getExtentSize();
Point endPoint = new Point(startPoint.x + size.width, startPoint.y + size.height);
Once you know the start/end points of the viewport you can use:
int start = editorPane.viewToModel( startPoint );
int end = editorPane.viewToModel( endPoint );
Once you know the offsets of the text you want you can get the text from the component:
String text = editorPane.getText(start, end - start);
None of the code is tested.
I'm trying to fill a JPanel with a neat grid containing as many JLabels as will fit into the JPanel. The size of the JPanel can vary, and the size of the JLabels depends on the label text, the icon included in the JLabel, and the font being used to render the label text.
GridLayout myLayout = new GridLayout();
JPanel myPanel = new JPanel(myLayout);
List<JLabel> myLabels = ...
int panelWidth = myPanel.getWidth();
int panelHeight = myPanel.getHeight();
if (panelWidth == 0 || panelHeight == 0) return;
int maxLabelWidth = 0, maxLabelHeight = 0;
for (JLabel label : myLabels) {
int labelWidth = ???
int labelHeight = ???
if (labelWidth > maxLabelWidth) maxLabelWidth = labelWidth;
if (labelHeight > maxLabelHeight) maxLabelHeight = labelHeight;
}
// Use panelHeight, panelWidth, maxLabelHeight and maxLabelWidth to compute
// rows and columns available for myLayout
myLayout.setRows(nRows); myLayout.setColumns(nColumns);
for (JLabel label : myLabels) {
myPanel.add(label);
// stop if we reach nRows*nColumns labels
}
I've tried myPanel.getGraphics().getFontMetrics().getHeight() to get the height of text, but when the font is large and myPanel is small, the text is taller than labelHeight, and the bottom and top get cut off.
I've tried label.getIcon().getIconHeight() to get the height of the icon, but using this value always cuts off the top and bottom of the icons.
I've tried label.getSize() to get the height and width of the JLabel, but that usually returns 0 height and 0 width. I've tried label.getPreferredSize() but that generally returns a value that's too small.
I've tried label.getGraphics().getFontMetrics().stringWidth(label.getText()) to get the width of the string, and then added that to label.getIcon().getIconWidth() and label.getIcon().getIconTextGap() but that comes up with a value a little larger or smaller than label.getPreferredSize(), and in any case still too small - sometimes the label text is cut off at the end.
At one point I tried adding a constant to each width and height; that prevented cut-off text and icons, but of course it left too much blank space around the JLabels. Is there a way to get an accurate size for each JLabel for this usage?
This question already has answers here:
JSpinner: Increase length of editor box
(5 answers)
Closed 8 years ago.
My problem: JSpinner is so skinny that I can only see the chars on the string in the last spot.
ex: "Hello" I only see 'o'.
I have a JPanel in a JFrame's BorderLayout.SOUTH
The JPanel's layout manager is the default which is - correct me if I'm misinformed - a FlowLayout manager.
also there's multiple components in the previously mentioned JPanel.
I've tried
RandomSpinner = new JSpinner(tempModel);
int w = RandomSpinner.getWidth(); int h = RandomSpinner.getHeight();
RandomSpinner.setSize(new Dimension(w * 2, h));
add(RandomSpinner);
this had no effect on the width of the JSpinner.
How should I change the width of my JSpinner or is this a FlowLayout issue?
thank you
You can do it all in the following three steps:
// 1. Get the editor component of your spinner:
Component mySpinnerEditor = mySpinner.getEditor()
// 2. Get the text field of your spinner's editor:
JFormattedTextField jftf = ((JSpinner.DefaultEditor) mySpinnerEditor).getTextField();
// 3. Set a default size to the text field:
jftf.setColumns(your_desired_number_of_columns);
Set the preferred and minimum sizes:
RandomSpinner = new JSpinner(tempModel);
int w = RandomSpinner.getWidth(); int h = RandomSpinner.getHeight();
Dimension d = new Dimension(w * 2, h);
RandomSpinner.setPreferredSize(d);
RandomSpinner.setMinimumSize(d);
Setting preferred size should be enough if you have enough space in your frame.
We have an app that draws text, but then displays a JTextArea for the user to edit the text when they click on the text. However, the wrapping between these two text-handling components differs. They use the same width, text String, and Font.
For the text-drawing, I'm using the from the Java tutorial, which I've also seen used by others in related questions here and other forums. Here's that part of the code:
FontRenderContext frc = g2d.getFontRenderContext();
TextLayout layout;
AttributedString attrString = new AttributedString(myText);
AttributedCharacterIterator charIterator;
int paragraphStart;
int paragraphEnd;
LineBreakMeasurer lineMeasurer;
float breakWidth;
float drawPosX;
float drawPosY;
attrString.addAttribute(TextAttribute.FONT, myFont);
charIterator = attrString.getIterator();
paragraphStart = charIterator.getBeginIndex();
paragraphEnd = charIterator.getEndIndex();
lineMeasurer = new LineBreakMeasurer(charIterator, frc);
// Set break width to width of Component.
breakWidth = myTextWidth;
drawPosY = startY
// Set position to the index of the first character in the paragraph.
lineMeasurer.setPosition(paragraphStart);
textBounds = new Rectangle(startX, startY(), 0, 0);
// Get lines from until the entire paragraph has been displayed.
while (lineMeasurer.getPosition() < paragraphEnd) {
layout = lineMeasurer.nextLayout(breakWidth);
// Compute pen x position. If the paragraph is right-to-left we
// will align the TextLayouts to the right edge of the panel.
drawPosX = layout.isLeftToRight()
? startX() : breakWidth - layout.getAdvance();
// Draw the TextLayout at (drawPosX, drawPosY).
layout.draw(g2d, drawPosX, drawPosY);
lineBounds = new Rectangle2D.Float(drawPosX, drawPosY - layout.getAscent(), layout.getAdvance(), (layout.getAscent() + layout.getDescent() + layout.getLeading()));
// Move y-coordinate in preparation for next layout.
drawPosY += layout.getAscent() + layout.getDescent() + layout.getLeading();
}
The JTextArea is much simpler:
JTextArea textArea = new JTextArea(myText);
textArea.setSize(myTextWidth, myTextThing.getHeight());
textArea.setOpaque(true);
textArea.setVisible(true);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setFont(myFont);
textArea.setBorder(null);
I set the border to null because I have another rectangle drawn outside the bounds of the text area with a dashed area to show where it is. Might seem silly now, but we use it to show the bounds of the text area when the user first selects the text they want to edit. At that point, the JTextArea isn't yet created. They have to click on it again to begin editing. The reason for this is that once a text area is selected, they may also drag and resize the text area, and that gets messy and more confusing if they had a live JTextArea when they started dragging and resizing.
Separately, both the drawn TextLayouts and the JTextArea appear to wrap words just fine. but when used together you can see the difference. The problem with this is that while the user is editing the text, the JTextArea is doing its thing to wrap the text. But when the user JTextArea loses focus, it is converted to the drawn text, and then the words may be wrapped differently.
Fill the text area with i or l characters. Grab a UI ruler or magnifying glass and count the size of your text area in pixels from the leftmost character of the longest line to the rightmost. Do the same with n, m, and a few other characters for a few more data points. I suspect that the text area has an invisible border of a few pixels it uses even when set to no border. If this is the case, add the same border around the TextLayout component and they should appear identical.
(Alternatively to counting pixels, you could set a background color for the text or the components, but I wouldn't necessarily trust it.)
Can anyone tell me how to alight text right in Java 2d?
Here's the code, it draws a column of text that is naturally aligned left.
Font yFont = new Font("Arial", Font.BOLD, 13);
interval = 0;
g2d.setFont(yFont);
for (String l : binLabels) {
g2d.drawString(l, 0, (135 + interval));
interval = interval + 15;
}
Driving me crazy.
Thanks y'all
slothishtype
In your paintComponent() method you can use the FontMetrics to get the width of the string you want to paint:
FontMetrics fm = getFontMetrics( getFont() );
int width = fm.stringWidth("your string here");
Then you calculate the offset where to start painting based on the width of the component.
The question is why are you trying to do this. You can just use a JLabel and set its alignment to the right.