12

I was trying to make my JTextField fill the width and set a height for it but still failed. I tried adding the code setPreferredSize(new Dimension(320,200)); but still failed. Is there any way I can make my JTextField fill the width and set the height to 200 or something?

MadProgrammer
  • 336,120
  • 22
  • 219
  • 344
Ms. B
  • 1,005
  • 6
  • 15
  • 26
  • 3
    The question that needs to asked is..."why?". It's typically better to let the layout managers decide the best size to use. You can provide hints back to the layout manager through the `Font` and `columns` methods of the text field. This way, it will have a better chance of working on difference OS's – MadProgrammer Feb 11 '13 at 02:43

8 Answers8

27

You should not play with the height. Let the text field determine the height based on the font used.

If you want to control the width of the text field then you can use

textField.setColumns(...);

to let the text field determine the preferred width.

Or if you want the width to be the entire width of the parent panel then you need to use an appropriate layout. Maybe the NORTH of a BorderLayout.

See the Swing tutorial on Layout Managers for more information.

camickr
  • 316,400
  • 19
  • 155
  • 279
6

set the height to 200

Set the Font to a large variant (150+ px). As already mentioned, control the width using columns, and use a layout manager (or constraint) that will respect the preferred width & height.

Big Text Fields

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class BigTextField {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                // the GUI as seen by the user (without frame)
                JPanel gui = new JPanel(new FlowLayout(5));
                gui.setBorder(new EmptyBorder(2, 3, 2, 3));

                // Create big text fields & add them to the GUI
                String s = "Hello!";
                JTextField tf1 = new JTextField(s, 1);
                Font bigFont = tf1.getFont().deriveFont(Font.PLAIN, 150f);
                tf1.setFont(bigFont);
                gui.add(tf1);

                JTextField tf2 = new JTextField(s, 2);
                tf2.setFont(bigFont);
                gui.add(tf2);

                JTextField tf3 = new JTextField(s, 3);
                tf3.setFont(bigFont);
                gui.add(tf3);

                gui.setBackground(Color.WHITE);

                JFrame f = new JFrame("Big Text Fields");
                f.add(gui);
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See http://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
3

There's a way which maybe not perfect, but can meet your requirement. The main point here is use a special dimension to restrict the height. But at the same time, width actually is free, as the max width is big enough.

package test;
import java.awt.*;
import javax.swing.*;

public final class TestFrame extends Frame{
    public TestFrame(){
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.setPreferredSize(new Dimension(500, 200));
        p.setMaximumSize(new Dimension(10000, 200));
        p.add(new JLabel("TEST: "));

        JPanel p1 = new JPanel();
        p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
        p1.setMaximumSize(new Dimension(10000, 200));
        p1.add(new JTextField(50));

        p.add(p1);

        this.setLayout(new BorderLayout());
        this.add(p, BorderLayout.CENTER);
    }
    //TODO: GUI CREATE
}
1
     f.setLayout(null);

add the above lines ( f is a JFrame or a Container where you have added the JTestField )

But try to learn 'LayoutManager' in java ; refer to other answers for the links of the tutorials .Or try This http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Abhishek Bhandari
  • 585
  • 1
  • 4
  • 15
  • See [`setLayout(null)` is never necessary. Ever!](https://forums.oracle.com/forums/thread.jspa?threadID=1351374) for why I down voted advice that started with that recommendation and lead into layout managers starting with 'But..'. Using size hints and a layout manager is the sensible strategy for this. – Andrew Thompson Feb 11 '13 at 09:10
  • What do you Think the Default layout of the JFrame is ? @AndrewThompson – Abhishek Bhandari Feb 11 '13 at 09:48
  • @AndrewThompson Try adding a JTextField in a simple Class which extends JFrame , give some size to JTextField. call the constructor from the main method. you will see there the use of setLayout(null), and you can contribute the the above discussion too :) – Abhishek Bhandari Feb 11 '13 at 09:50
  • "The default content pane will have a BorderLayout manager set on it." So I believe other container may also having some or the other . To get things clear . setLayout(null) is cool if you don't want to use any layout . – Abhishek Bhandari Feb 11 '13 at 10:01
  • @AndrewThompson "Class which extends JFrame" was an example . I have a habit learning with examples . – Abhishek Bhandari Feb 11 '13 at 10:04
  • *"I have a habit learning with examples"* Hopefully you can learn from [BigTextField](http://stackoverflow.com/a/14806175/418556) then. :) – Andrew Thompson Feb 11 '13 at 10:10
  • " setLayout(null) is never necessary. Ever! " is not true for everything . Thats all I am here for .And thats the centre.;) – Abhishek Bhandari Feb 11 '13 at 10:16
0

What type of LayoutManager are you using for the panel you're adding the JTextField to?

Different layout managers approach sizing elements on them in different ways, some respect SetPreferredSize(), while others will scale the compoenents to fit their container.

See: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

ps. this has nothing to do with eclipse, its java.

drew moore
  • 29,711
  • 17
  • 73
  • 109
0
package myguo;
import javax.swing.*;

public class MyGuo {

    JFrame f;
    JButton bt1 , bt2 ;
    JTextField t1,t2;
    JLabel l1,l2;

    MyGuo(){

        f=new JFrame("LOG IN FORM");
        f.setLocation(500,300);
        f.setSize(600,500);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        l1=new JLabel("NAME");
        l1.setBounds(50,70,80,30);

        l2=new JLabel("PASSWORD");
        l2.setBounds(50,100,80,30);

        t1=new JTextField();
        t1.setBounds(140, 70, 200,30);

         t2=new JTextField();
        t2.setBounds(140, 110, 200,30);

        bt1 =new JButton("LOG IN");
        bt1.setBounds(150,150,80,30);

        bt2 =new JButton("CLEAR");
        bt2.setBounds(235,150,80,30);

         f.add(l1);
        f.add(l2);
         f.add(t1);
         f.add(t2);
         f.add(bt1);
         f.add(bt2);

    f.setVisible(true);

    }
    public static void main(String[] args) {
        MyGuo myGuo = new MyGuo();
}
}
Laurel
  • 5,771
  • 12
  • 29
  • 54
0

xyz.setColumns() method is control the width of TextField.

import java.awt.*;
import javax.swing.*;



class miniproj extends JFrame {

  public static void main(String[] args)
  {
    JFrame frame=new JFrame();
    JPanel panel=new JPanel();
    frame.setSize(400,400);
    frame.setTitle("Registration");


    JLabel lablename=new JLabel("Enter your name");
    TextField tname=new TextField(30);
    tname.setColumns(45);

    JLabel lableemail=new JLabel("Enter your Email");
    TextField email=new TextField(30);
    email.setColumns(45);
    JLabel lableaddress=new JLabel("Enter your address");
    TextField address=new TextField(30);
    address.setColumns(45);
    address.setFont(Font.getFont(Font.SERIF));
    JLabel lablepass=new JLabel("Enter your password");
    TextField pass=new TextField(30);
    pass.setColumns(45);

    JButton login=new JButton();
    JButton create=new JButton();
    login.setPreferredSize(new Dimension(90,30));
    login.setText("Login");
    create.setPreferredSize(new Dimension(90,30));
    create.setText("Create");



    panel.add(lablename);
    panel.add(tname);
    panel.add(lableemail);
    panel.add(email);
    panel.add(lableaddress);
    panel.add(address);
    panel.add(lablepass);
    panel.add(pass);
    panel.add(create);
    panel.add(login);



    frame.add(panel);
    frame.setVisible(true);
  }
}

enter image description here

slfan
  • 8,665
  • 115
  • 63
  • 77
amir khan
  • 1,806
  • 1
  • 9
  • 10
-1

setBounds is working only in BorderLayout use BorderLayout for frame or container or panel and use setBounds to set the width and height of text field. see this code simple code

 import java.awt.*;
 import javax.swing.*;

   class uni1
   {
     public static void main(String[] args)
{
    JFrame frm = new JFrame();
    TextField txt = new TextField();
    txt.setBounds(0, 0, 1200, 400);
    frm.add(txt,BorderLayout.NORTH);
    frm.setLayout(new BorderLayout());
    frm.setVisible(true);
    frm.setDefaultCloseOperation(frm.EXIT_ON_CLOSE);
}

}