Change JSpinner Size (width) [duplicate] - java

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.

Related

How many JLabels fit in my JPanel

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?

center align the title in JFrame

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.

JDialog.pack() hides JLabel

I am trying to write a form in java, but after dynamically inserting JLabels to the current JDialog and doing a pack() the windows is resized to minimum. The JLabels are displayed, but I have to resize the window manually.
Here is the part where the JLabels are inserted:
public void displayQuizz(Test quiz){
int xLable = 44;
int yLable = 41;
int widthLable = 403;
int heightLable = 70;
int noOfQuestion = 1;
for(Question question : quiz.getQuestions()){
JLabel lblNewLabel = new JLabel(Integer.toString(noOfQuestion) + ". " + question.getStatement());
lblNewLabel.setBounds(xLable, yLable, widthLable, heightLable);
contentPanel.add(lblNewLabel);
contentPanel.revalidate();
contentPanel.repaint();
this.pack();
noOfQuestion++;
yLable += heightLable;
}
}
The pack() method sets the size of a Window (where JFrame and JDialog are subclasses from) to the preferred size.
The preferred size is determined by
The LayoutManager, which takes the arrangement of the components and
their preferred size into account
The component itself, if it does not have a layout manager
As you don't use a layout manager in your example (and set the bounds of the label manually), you also have to specify the preferred size yourself (see getPreferredSize(), the default is 0x0, that's the problem you encountered).
I'd encourage you to get used to always use layout managers (there's quite a lot of them, and you can easily write your own layout manager strategy if none suffices your needs).

Swing: resize Image but keep same size

I want to be able to do something similar to resize canvas in gimp
I want to generate a bunch of images to a certain width.
I used
int width = (int)(size * fraction);
int height =(int)(size*icon.getIconHeight()/icon.getIconWidth()*fraction);
miniature = new ImageIcon(i.getScaledInstance(width, height, Image.SCALE_SMOOTH));
this goes well while I'm doing fraction 1 but I have 3 images that have the same source but are different size (1, 2/3, 1/3)
the problem is
I have and image A
I want to create B, C and D such as the drawing inside respect the follow ratio
B = A
C = 2/3 A
D = 1/3 A
but the image stays the same dimension A = B = C = D
Assuming I'm following what you are trying to do...
Create a JLabel for each image:
JLable l = new JLabel(miniture);
Create a JLabel with a GridLayout:
JPanel p = new JPanel(new GridLayout());
Add the labels to the panel:
p.add(l);
The GridLayout will ensure that all the JLabels will have the same height and width.

JList with JScrollPane and prototype cell value wraps element names (replaces with dots instead of showing horizontal scrollbar), why?

I've got a Jlist inside a JScrollPane and I've set a prototype value so that it doesn't have to calculate the width for big lists, but just uses this default width.
Now, the problem is that the Jlist is for some reason replacing the end of an element with dots (...) so that a horizontal scrollbar will never be shown.
How do I disable with "wrapping"? So that long elements are not being replaced with dots if they are wider than the Jlist's width?
I've reproduced the issue in a small example application. Please run it if you don't understand what I mean:
import javax.swing.*;
import java.awt.*;
public class Test
{
//window
private static final int windowWidth = 450;
private static final int windowHeight = 500;
//components
private JFrame frame;
private JList classesList;
private DefaultListModel classesListModel;
public Test()
{
load();
}
private void load()
{
//create window
frame = new JFrame("Test");
frame.setSize(windowWidth, windowHeight);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
//classes list
classesListModel = new DefaultListModel();
classesList = new JList(classesListModel);
classesList.setPrototypeCellValue("prototype value");
classesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
classesList.setVisibleRowCount(20);
JScrollPane scrollClasses = new JScrollPane(classesList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
for (int i = 0; i < 200; i++)
{
classesListModel.addElement("this is a long string, does not fit in width");
}
//panel
JPanel drawingArea = new JPanel();
drawingArea.setBackground(Color.white);
drawingArea.add(scrollClasses);
frame.add(drawingArea);
//set visible
frame.setVisible(true);
}
}
Even if you force horizontal scrollbar, you still won't be able to scroll because the element is actually not wider than the width because of the dot (...) wrapping.
Thanks in advance.
Scrollbars appear automatically when the preferred size of the component added to the scrollpane is greater than the size of the scrollpane.
By using the setPrototypeCellValue(...) method you are affecting the way the list calculates its preferred size, which means you are responsible for providing the proper value that ensures the strings will not be truncated.
So the simple solution is not not use that method, but in addition you will need to set the preferred size of the scrollpane to be whatever you want. Then the horizontal scrollbars will appear if required.
My answer to that question is that first find the longest element in the list then use
setPrototype method on that elements
When you call classesList.setPrototypeCellValue("prototype value") you are telling the JList classesList to limit its maximum width to the length of the string "prototype value". (See javadocs)
Then later on when you populate the list with the strings "this is a long string, does not fit in width", no wonder it does not fit in the width! Because the width of the prototype you gave it is smaller than the width of the string you are filling the list with.
The JScrollPane will automatically show the scrollbars and you usually don't need to adjust their behavior. The JList will also automatically adjust its width to try and show the maximum width item in the list. The problem occurs when you tell the JList to fix its width by calling the setPrototypeCellValue().
If you comment out
classesList.setPrototypeCellValue("prototype value");
or replace it with
classesList.setPrototypeCellValue("this is a long string, does not fit in width");
then it will function as you expected it to.

Categories