Agregar texto junto a un campo de texto para describir qué datos se espera que el usuario ingrese en él

I am trying to create a simple GUI that simulates a record store. I am still in the beginning stages.

I am running into trouble when I try to add text to describe what the user is expected to enter in the text field.

In addition, I am also having trouble positioning every textfield on its own line. In other words if there is space for two textfields in one line, then it displays in one line, and I am trying to display every text field on its own line.

Esto es lo que intenté hasta ahora:

item2 = new JTextField("sample text");

However the code above just adds default text within the text field, which is not what I need :/

I appreciate all the help in advance.

public class MyClass extends JFrame{
        private JTextField item1;
        private JTextField item2;

        public MyClass(){
            super("Matt's World of Music");
            setLayout(new FlowLayout());

            item1 = new JTextField();
            item2 = new JTextField();


            thehandler handler = new thehandler();




preguntado el 26 de agosto de 12 a las 23:08

It seems this 'question' (there is not a single '?' in the text) consists of two entirely separate problems that should be handled on two entirely separate posts. -

public class MyClass extends JFrame{ mejor sería public class RecordStore{ 1) Use a descriptive name, even for test/throwaway codes. Make the name RecordStoreTest or RecordStoreTest01 if you like, but make it meaningful. 2) Instead of extending frame, keep a reference to one. -- And while I am here. Create the main GUI in a JPanel and add it to the frame. But do not extend panel either, just reference one. -

4 Respuestas

For your first problem, you need to use a JLabel to display your text. The constructor is like this:

JLabel label = new JLabel("Your text here");

Works really well in GUI.

As for getting things on their own lines, I recommend a GridLayout. Easy to use.

In your constructor, before adding anything, you do:

setLayout(new GridLayout(rows,columns,x_spacing,y_spacing));

x_spacing y y_spacing are both integers that determine the space between elements horizontally and vertically.

Then add like you have done. Fiddle around with it and you'll get it worked out.

So your final would look like:

setLayout(new GridLayout(2,2,10,10));
add(new JLabel("Text 1"));
add(new JLabel("text 2"));

Respondido 27 ago 12, 04:08

Podrías usar un JLabel to label your textfields.

    JLabel label1 = new JLabel("Item 1: ");

If you really want text inside the fields, you could set the text in the field with the constructor, and then add a MouseListener to clear the text on click:

    item1 = new JTextField("Text");
    item1.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (item1.getText().equals("Text")) // User has not entered text yet

Or, (probably better) use a FocusListener:

    item1 = new JTextField("Text");
    item1.addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
            if (item1.getText().equals("Text")) // User has not entered text yet
        public void focusLost(FocusEvent e) {
            if (item1.getText().equals("")) // User did not enter text

As for layout, to force a separate line, you use use a Caja.

    Box itemBox = Box.createVerticalBox();

Respondido 27 ago 12, 00:08

+1 para "Or, (probably better) use a FocusListener:" I typically use keyboard over mouse. 'clicks' are no good! - Andrew Thompson

Si combinas el FocusListener con una llamada a selectAll on focusGained, it will even be user-friendly. Otherwise the user always has to select and delete the description manually - petirrojo

@Robin Really? Wouldn't setText(""); clear the field immediately? - Alden


item1 = new JTextField(10);
item2 = new JTextField(10);

that should solve problem with width of JTextField. For beginning use GridLayout to display JTextField in one line. After that I strongly recomend using of MIG Layout

put JLabel next to JTextField to describe what the user is expected to enter in the text field.

JLabel lbl = new JLabel("Description");

or you could also consider using of toolTipText:

item1.setToolTipText("This is description");

Respondido 27 ago 12, 00:08

For making a form in Java Swing, I always recommend the FormLayout of JGoodies, which is designed to ... create forms. The links contains an example code snippet, which I just copy-pasted here to illustrate how easy it is:

public JComponent buildContent() {
    FormLayout layout = new FormLayout(
            "$label, $label-component-gap, [100dlu, pref]",
            "p, $lg, p, $lg, p");

    PanelBuilder builder = new PanelBuilder(layout);
    builder.addLabel("&Title:",  CC.xy(1, 1));
    builder.add(titleField,      CC.xy(3, 1));
    builder.addLabel("&Author:", CC.xy(1, 3));
    builder.add(auhtorField,     CC.xy(3, 3));
    builder.addLabel("&Price:",  CC.xy(1, 5));
    builder.add(priceField,      CC.xy(3, 5));
    return builder.getPanel();

Now for the description:

  • Use a label in front of the textfield to give a very short description
  • You can put a longer description in the textfield as suggested by @Alden. However, if the textfield is for short input, nobody will be able to read the description
  • You can use a tooltip (JComponent#setTooltipText) to put a longer description. Those tooltips also accept basic html which allows some formatting. Drawback of the tooltips is that the user of your application has to 'discover' that feature as there is no clear indication those are available
  • You can put a "help-icon" (like e.g. a question mark) after each text field (use a JButton with only an icon) where on click you show a dialog with a description (e.g. by using the JOptionPane clase)
  • You can put one "help-icon" on each form which shows a dialog with a description for all fields.

Note for the dialog suggestion: I wouldn't make it a model one, allowing users to open the dialog and leave it open until they are finished filling in the form

Respondido 27 ago 12, 08:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.