1

I'm trying to create a GUI window for the user to enter some information for my program. But it seems like no matter how I change the sizes or the locations, all of my components are squished in far smaller than what I want. Could someone please point out what I am missing? Here's what I tried:

          JFrame inputFrame = new JFrame();
          JPanel panel = new JPanel();
          inputFrame.setTitle("Create Event");
          inputFrame.setSize(500,400);

          JTextField eventName = new JTextField("Untitled event");
          JTextField eventStart = new JTextField();
          JTextField eventEnd = new JTextField();
          JButton save = new JButton("Save");

          JLabel selectedDate = new JLabel(MyCalendarTester.currentMonth + 1 + "/" + selectedDay + "/" + MyCalendarTester.currentYear);

          selectedDay = null;
          panel.setSize(450,300);
          eventName.setBounds(10, 10, 600, 50);
          panel.add(eventName);
          selectedDate.setBounds(10, 20, 50, 20);
          panel.add(selectedDate);
          panel.add(eventStart);
          eventStart.setBounds(100, 20, 50, 20);
          panel.add(eventEnd);
          eventEnd.setBounds(175, 20, 50, 20);
          panel.add(save);
          save.setBounds(250, 20, 60, 30);


          inputFrame.add(panel);
          inputFrame.setVisible(true);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
aurora91
  • 478
  • 1
  • 9
  • 25

1 Answers1

2

The default layout manager for a JPanel is the FlowLayout. The FlowLayout will display components at their preferred size, which is the way the component should be displayed.

You should not attempt to give the component a random size because you don't know what the best size for the component should be based on Font, OS etc.

When you create a JTextField you can use:

JTextField textField = new JTextField(10);

The value 10 will allow the text field to give itself a reasonable preferred size.

The JLabel and JButton size will be determined by the text of the component.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Hmm is there a layout that I can use that still gives me the capability to place the components wherever I want? – aurora91 May 03 '15 at 00:01
  • You don't want to do this. That is not the way you design a GUI. – camickr May 03 '15 at 00:01
  • 1
    Also, read the Swing tutorial on [Layout Manager](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). Each layout manager has different rules for determining the size/location of the component. You can mix/match layout managers to get your desired layout. – camickr May 03 '15 at 00:05