9

In Food Tab, I want to achieve this

enter image description here

But I only able to get this

enter image description here

How can I increase the width of the JTextField which are in Food Tab ? Below is my code

 public class FoodOrdering {
        static private JFrame frame;
        static private JTextField textField;
        static private GridBagConstraints gbc;
        static private JLabel[] foodLabel;
        static private JLabel[] labels;
        static private JTextField[] qtyField;
        static private JLabel[] foodImage;
        static private File[] file;
        private static final int ELEMENTS = 9;
        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        FoodOrdering window = new FoodOrdering();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        /**
         * Create the application.
         * 
         * @throws IOException
         */
        public FoodOrdering() throws IOException {
            initialize();
        }
        /**
         * Initialize the contents of the frame.
         * 
         * @throws IOException
         */
            static void initialize() throws IOException {
            frame = new JFrame();
            frame.setBounds(100, 100, 700, 550);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);
            frame.setLocationRelativeTo(null);
            JLabel lblFoodOrdered = new JLabel("Food Ordered");
            lblFoodOrdered.setBounds(529, 11, 81, 14);
            frame.getContentPane().add(lblFoodOrdered);
            TextArea textArea = new TextArea();
            textArea.setBounds(462, 31, 199, 275);
            frame.getContentPane().add(textArea);
            JLabel lblTotal = new JLabel("Total  : ");
            lblTotal.setBounds(519, 315, 46, 14);
            frame.getContentPane().add(lblTotal);
            textField = new JTextField();
            textField.setBounds(575, 312, 86, 20);
            frame.getContentPane().add(textField);
            textField.setColumns(10);
            JButton btnOrder = new JButton("Order");
            btnOrder.setBounds(521, 352, 89, 23);
            frame.getContentPane().add(btnOrder);
            JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
            addIt(tabbedPane, "Foods");
            addIt1(tabbedPane, "Drinks");
            addIt1(tabbedPane, "Desserts");
            tabbedPane.setBounds(23, 11, 400, 450);
            frame.getContentPane().add(tabbedPane);
            frame.setVisible(true);
        }
        static void addIt1(JTabbedPane tabbedPane, String text) {
            JLabel label = new JLabel(text);
            JButton button = new JButton(text);
            JPanel panel = new JPanel();
            panel.add(label);
            panel.add(button);
            tabbedPane.addTab(text, panel);
        }
        static void addIt(JTabbedPane tabbedPane, String text) throws IOException {
            JPanel panel = new JPanel(new GridBagLayout());
            gbc = new GridBagConstraints();
            gbc.insets = new Insets(1, 1, 1, 1);
            foodImage = new JLabel[ELEMENTS];
            foodLabel = new JLabel[ELEMENTS];
            labels = new JLabel[ELEMENTS];
            qtyField = new JTextField[ELEMENTS];
            file = new File[ELEMENTS];
            try {
                file[0] = new File("C:\\Users\\tony\\Desktop\\MedSalad.png");
                file[1] = new File("C:\\Users\\tony\\Desktop\\JapanesePanNoodles.png");
                file[2] = new File("C:\\Users\\tony\\Desktop\\Spaghetti.png");
                file[3] = new File("C:\\Users\\tony\\Desktop\\PadThai.png");
                file[4] = new File("C:\\Users\\tony\\Desktop\\RamenNoodles.png");
                file[5] = new File("C:\\Users\\tony\\Desktop\\SpaghettiAndMeatBalls.png");
                file[6] = new File("C:\\Users\\tony\\Desktop\\chickenRice.jpg");
                file[7] = new File("C:\\Users\\tony\\Desktop\\thaiFood.jpeg");
                file[8] = new File("C:\\Users\\tony\\Desktop\\vietnamFood.jpg");
                foodLabel[0] = new JLabel("Salad");
                foodLabel[1] = new JLabel("Japanese Noodles");
                foodLabel[2] = new JLabel("Spaghetti");
                foodLabel[3] = new JLabel("Spaghetti Meat Balls");
                foodLabel[4] = new JLabel("Noodles");
                foodLabel[5] = new JLabel("Kids Spaghetti");
                foodLabel[6] = new JLabel("Chicken Rice");
                foodLabel[7] = new JLabel("Thai Food");
                foodLabel[8] = new JLabel("Vietnam Food");
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (int i = 0; i < ELEMENTS; i++) {
                Image image = ImageIO.read(file[i]);
                Image imageScaled = image.getScaledInstance(80, 95, Image.SCALE_SMOOTH);
                ImageIcon imageIcon = new ImageIcon(imageScaled);
                qtyField[i] = new JTextField(3);
                foodImage[i] = new JLabel(imageIcon);
            }
            gbc.gridx = 0;
            for (int i = 0; i < ELEMENTS; i++) {
                if (i % 3 == 0) {
                    gbc.gridy += 2;
                    gbc.gridx = 0;
                }
                panel.add(foodImage[i], gbc);
                gbc.gridy++;
                panel.add(foodLabel[i], gbc);
                gbc.gridy--;
                gbc.gridx++;
                panel.add(qtyField[i], gbc);
                gbc.gridx++;
                tabbedPane.addTab(text, panel);
            }
        }
        public void setVisible(boolean b) throws IOException {
        }
    }
John Joe
  • 12,412
  • 16
  • 70
  • 135
  • 4
    The first thing I would do is get rid of `frame.getContentPane().setLayout(null);` and start using an appropriate layout manager which can handle the size requirements of your `JTabbedPane` better. It looks to me that the panel with the `GridBagLayout` has simply run out of room and is using the minimum size of the components instead – MadProgrammer Jul 25 '17 at 08:44
  • create the `JTextField` and not directly add it to the array, so you can do some operation on it. then you can call `textField.setPreferredSize(new Dimension(50, (int) textPane.getPreferredSize().getHeight()));` – XtremeBaumer Jul 25 '17 at 08:44
  • 3
    @XtremeBaumer `new JTextField(3);` sets the `preferredSize` of the textfield to three columns based on the current font metrics. The problem probably extends from the use of a `null` layout manager which is already causing issues and changing the preferred size of the field manually is both a bad idea and probably cause a cascade of additional problems - The immediate solution is to find a better layout manager for the frame – MadProgrammer Jul 25 '17 at 08:46
  • You're also over using `static`, I'd highly recommend that you take the time to learn without it - at least in the he context your are using it – MadProgrammer Jul 25 '17 at 08:47

3 Answers3

4

The JTextfield objects are so narrow because of a very old "bug" in GridBagLayout which causes it to ignore the preferred size of its contents.

There are several possible ways to work-around this bug:

  1. Create a class called PreferredGridBagLayout as explained in the link and use that instead of GridBagLayout.
  2. Set the minimum size of each of your qtyField instances with qtyField[i].setMinimumSize(qtyField[i].getPreferredSize()).
  3. Create subclasses of JTextField which override the method getMinimumSize() to return the same value as getPreferredSize(), or some other reasonable minimum size.

Because this problem is so common when using GridBagLayout, solution #1 is the easiest in the long term.

Afterwards, you'll need to make your tabbedPane object a little wider, or switch to a layout manager in the main panel that automatically determines the size of the tabbed pane.

There are multiple things that could be improved in your code. Creating good layouts in Swing is not easy, and you will need much more work to make a pretty layout. But this will solve your problem with collapsing text fields.

Enwired
  • 1,563
  • 1
  • 12
  • 26
1

This problem simply can be solved by setting the

qtyField[i].setMinimumSize(new Dimension(33,20));

function. The reason for setting minimum size is that the GridBagLayout dont have enough space to arrange all those components properly so it only takes the minimum size of the empty textField.

Just add the code after the line

qtyField[i] = new JTextField(3);

and you will be also needed to increase the width of tabbedPane a little bit more to make the components(qtyField) visible

enter image description here

NEKIBUR RAHMAN
  • 204
  • 3
  • 15
0

Instead of using null layout. use some other layout like border layout. Then use just one line:

frame.pack();

This will display all the components at their preferred sizes.

Just a coding practice: instead of setting bounds use panels to add components and then add these panels to a main panel. Like use one different panel to add your Jlabel of food ordered, textarea, Jlabel for order and order button. And then add that panel to your main panel.

Hope you understand. :)

bhavna garg
  • 270
  • 2
  • 19