1

JTextField in JPanel which in turn in JDialog doesn't take specified size. I tried to use BoxLayout and FlowLayout, but still have not achieved the desired size. I.E. I measure the size of String example and set this size to width of JTextField inputCat, but inputCat doesn't take this size, then I call it. How correctly set size of specified String to JTextField? Here is my code:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.util.Calendar;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DemoJDialog {

    static private JInternalFrame internal;


    public static void main(String[] args) {
        new DemoJDialog();
    }

    public DemoJDialog() {
        EventQueue.invokeLater(new Runnable() {
            @SuppressWarnings({ "rawtypes", "unchecked" })
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                internal = new JInternalFrame("Example", true, true, false, true);
                internal.setLayout(new BorderLayout());
                internal.setVisible(true);

                JDesktopPane dp = new JDesktopPane();
                dp.add(internal);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(dp);
                frame.setSize(800, 600);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);


                JTextField inputCat = new JTextField(); 


                String example = new String("Some very-very-very-"
                        + "very-very-very-very-very-very long string (really long )");
                int heightInputCat = inputCat.getSize().height;
                FontMetrics FN = internal.getFontMetrics(internal.getFont());
                int widthInputCat = SwingUtilities.computeStringWidth(FN, example);
                inputCat.setSize(widthInputCat, heightInputCat);



                String[] comboString = { "Telecast", "Radiocast" };
                JComboBox comboBox = new JComboBox(comboString);

                Calendar now = Calendar.getInstance();
                SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(), 
                        null, null, Calendar.MONTH);
                final JSpinner spinner = new JSpinner(modelSpinner);
                spinner.setEditor(new JSpinner.DefaultEditor(spinner)); 

                JPanel listPane = new JPanel();
                listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
                listPane.add(comboBox);
                listPane.add(Box.createHorizontalStrut(10));
                listPane.add(inputCat);
                listPane.add(Box.createHorizontalStrut(10));
                listPane.add(spinner);

                Object[] array = {
                        new JLabel ("Enter a new category:"),
                        listPane
                };

                JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
                        JOptionPane.OK_CANCEL_OPTION);
                JDialog dialog = pane.createDialog(internal, "Enter a new category:");
                dialog.setVisible(true);


            }
        });
    }

}
kaos169
  • 25
  • 4
  • 1
    For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Madhan Jun 20 '15 at 11:18
  • What do you want to accomplish with this? – Madhan Jun 20 '15 at 11:22
  • I don't really understand the requirement or question (especially since there *was no question asked*) but note that `JTextField inputCat = new JTextField();` should better be `JTextField inputCat = new JTextField(10); // suggest a width in columns!` – Andrew Thompson Jun 20 '15 at 11:35
  • Great links @Madhan. :) – Andrew Thompson Jun 20 '15 at 11:36
  • 1
    I'm new to StackOverflow just following your footsteps @AndrewThompson – Madhan Jun 20 '15 at 11:39
  • @Madhan Thanks and sorry for my lack of preparation. – kaos169 Jun 20 '15 at 12:41
  • @AndrewThompson maybe I should delete this incorreсt post? – kaos169 Jun 20 '15 at 12:44
  • @AndrewThompson Thanks a lot. How correlate width in columns and width in pixels? In javadocs on docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html it is not explained. I.E. what exactly means width in columns? – kaos169 Jun 20 '15 at 12:48
  • *"How correlate width in columns and width in pixels?"* It depends on the font and font size etc. But you should never 'think in pixels' for building a Java GUI. Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jun 20 '15 at 14:33
  • *"maybe I should delete this incorreсt post?"* We'd prefer to see it [edited](http://stackoverflow.com/posts/30953133/edit) into a *great* question! ;) – Andrew Thompson Jun 20 '15 at 14:35
  • @AndrewThompson http://stackoverflow.com/a/5630271/418556 - it's real hardcore for me for this moment, thanks :) I corrected question – kaos169 Jun 20 '15 at 15:25
  • It's a shame you did not correct the question to include an MCVE. :( – Andrew Thompson Jun 20 '15 at 15:29
  • @AndrewThompson I'm really sorry, that I spend so much of your time. In what exactly I made a mistake? My example insufficiently minimal, or question is blurred? – kaos169 Jun 20 '15 at 15:44
  • *"My example insufficiently minimal,.."* There is more to an MCVE than Minimal. It has 3 other words and that uncompilable code snippet achieves *none* of them. Note that the GUI thread I linked to includes an MCVE. It is 4 'scroll downs' worth of code, so an MCVE can be **longer** than the code above. – Andrew Thompson Jun 20 '15 at 15:52
  • @AndrewThompson, ok, so my example can not be execute by itself, i.e. does not correspond to paragraph COMPLETE. Am I right? – kaos169 Jun 20 '15 at 16:25
  • Right.. but since it is not Complete, we cannot Verify your results, and it is therefore not an Example (as meant by MCVE). – Andrew Thompson Jun 20 '15 at 16:28
  • @AndrewThompson changed sample. – kaos169 Jun 20 '15 at 17:30

2 Answers2

1

This works just fine here:

enter image description here

import java.awt.EventQueue;
import java.util.Calendar;
import javax.swing.*;

public class DemoJDialog {

    public static void main(String[] args) {
        new DemoJDialog();
    }

    public DemoJDialog() {
        EventQueue.invokeLater(new Runnable() {
            @SuppressWarnings({"rawtypes", "unchecked"})
            @Override
            public void run() {
                String example = new String("Some very-very-very-"
                        + "very-very-very-very-very-very "
                        + "long string (really long)");
                // create a textfield the size of the string!
                JTextField inputCat = new JTextField(example);
                inputCat.setCaretPosition(0);

                String[] comboString = {"Telecast", "Radiocast"};
                JComboBox comboBox = new JComboBox(comboString); 

                Calendar now = Calendar.getInstance();
                SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
                        null, null, Calendar.MONTH);
                final JSpinner spinner = new JSpinner(modelSpinner);
                spinner.setEditor(new JSpinner.DefaultEditor(spinner));

                JPanel listPane = new JPanel();
                listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
                listPane.add(comboBox);
                listPane.add(Box.createHorizontalStrut(10));
                listPane.add(inputCat);
                listPane.add(Box.createHorizontalStrut(10));
                listPane.add(spinner);

                Object[] array = {
                    new JLabel("Enter a new category:"),
                    listPane
                };

                JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
                        JOptionPane.OK_CANCEL_OPTION);
                JDialog dialog = pane.createDialog(listPane, "Enter a new category:");
                dialog.setVisible(true);
            }
        });
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • But `JTextField` is filled by the example `String`. And I need empty `JTextField` with this width – kaos169 Jun 20 '15 at 18:56
0

But JTextField is filled by the example String. And I need empty JTextField with this width

Just use constructor which specifies desired colums Count:

JTextField inputCat = new JTextField(example.length());
andronix
  • 124
  • 9