-1

I'm a beginner in Java, especially in the GUI Design area. I created a simple Java Swing interface to accept a string from the user and display it using a JOptionPane (ActionListener not yet implemented.)

The main problem I'm facing is with the alignment of the objects in the output. No matter what bounds I give to the objects, they always appear in one line. Also, sometimes, the output Frame will show absolutely nothing. After multiple runs, it will finally show me the objects, but not in the layout I expected them to be.

This is my code:

package guiapp;

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

public class GUIApp {

private static JFrame frame;
private static JPanel panel;
private static JLabel label;
private static JTextField text;
private static JButton click;

public static void CreateGUI(){
frame = new JFrame("Hello to NetBeans!");
frame.setSize(750, 750);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel();
panel.setBackground(Color.BLUE);

label = new JLabel("Enter a string: ");
label.setBounds(50,35,150,40);
label.setVisible(true);

text = new JTextField();
text.setBounds(250,35,150,40);
text.setVisible(true);

click = new JButton("Click here!");
click.setBounds(150,80,150,40);
click.setVisible(true);

panel.add(text);
panel.add(label);
panel.add(click);


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

}

public static void main(String[] args) {
    CreateGUI();
}

}

Can someone please tell me where I'm going wrong? I seem to have got the layout syntax wrong.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Oct 05 '14 at 03:53
  • BTW - `int result = JOptionPane.showInputDialog(parent, "Enter a string");` could replace most of what that GUI does. – Andrew Thompson Oct 05 '14 at 04:22

1 Answers1

3

No matter what bounds I give to the objects, they always appear in one line.

This is probably because of the default layout manager of JPanel: FlowLayout. On the other hand Swing is designed to be used with layout managers and the use of methods such as setBounds(...), setLocation(...) and setSize(...) is discouraged. See Laying out Components within a Container lesson.

dic19
  • 17,821
  • 6
  • 40
  • 69