David
David

Reputation: 137

Laying ot components in Java Swing

Oh hay there, didn't see you. I was wondering if there is a better, more efficient way of formatting the labels, panels, and buttons in java then what I have done below. Here is my code, I want to make Welcome, the date, and the button to all be on separate lines. And the only logical way of doing so is creating blank labels, right?

private void GeneralTab() {
  generalPanel = new JPanel(new FlowLayout());
  String currentTime = SimpleDateFormat.getInstance().format(
    Calendar.getInstance().getTime());
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel("WELCOME "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" ")); 
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel("                  "));
  generalPanel.add(new JLabel("Today's Date: " + currentTime));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
  generalPanel.add(new JLabel(" "));
   generalPanel.add(createExitButton());
 }

Upvotes: 3

Views: 181

Answers (1)

jjnguy
jjnguy

Reputation: 138874

It looks like you need to learn some more about LayoutManagers. They help you layout components in different ways.

Check out the Java tutorials. They are probably the best way to get started using different layouts.

Here is a link to the tutorial:

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

In your case, it looks like you want to use a BoxLayout. You should place the components you want on one line in their own JPanel. Then, add each JPanel to the generalPanel. You need to set the layout manager of the generalPanel to a BoxLayout like so:

generalPane.setLayout(new BoxLayout(generalPane, BoxLayout.Y_AXIS));

Upvotes: 7

Related Questions