I am trying to developing auto suggest Textfield. When i am typing in Textfield it is delay one key and suggest one key late **
When i am typing aaa it is querying as 'aa' only and suggest according to that in list.When i am pressing any key after aaa (extra key Press) then it will querying as aaa
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 414, 239);
frame.getContentPane().add(panel);
panel.setLayout(null);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
try {
addListItem();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
textField.setBounds(71, 24, 86, 20);
panel.add(textField);
textField.setColumns(10);
list = new JList<String>();
list.setBounds(71, 55, 86, 97);
list.setVisible(false);
list.getScrollableTracksViewportHeight();
panel.add(list);
}
public void addListItem() throws Exception {
list.setVisible(true);
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdemo", "root", "root");
ps = c.prepareStatement(
"SELECT stud_name FROM student_info where stud_name like '" + textField.getText().trim() + "%' ");
ResultSet s = ps.executeQuery();
model = new DefaultListModel<String>();
while (s.next()) {
model.addElement(s.getString("stud_name"));
System.out.println(s.getString("stud_name"));
}
list.setModel(model);
}
Use keyReleased instead of keyPressed method of KeyAdapter class.
Related
I am trying to get a scroll bar for a Panel that will get a big number of lines, however I am stuck whit this.
As you can see in my window (click here to open the picture), Scroll bars does not adjust to the panel's dimensions
Below you can see the code i am working with:
public class Config extends JFrame {
private static JPanel contentPane;
private static JScrollPane paneSiteScroll;
private static JPanel paneSite;
private JTextField txtURL;
private JButton btnAdd;
private JLabel lblName;
private JTextField txtName;
private JPanel paneBar;
/**
* Launch the application.
*/
public static void config() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Config frame = new Config();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Throwable
*/
public Config() throws Throwable {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Start top Add Bar
paneBar = new JPanel();
paneBar.setBounds(0, 0, 700, 35);
contentPane.add(paneBar);
paneBar.setLayout(null);
JButton btnBack = new JButton("Back");
btnBack.setBounds(1, 3, 65, 28);
paneBar.add(btnBack);
btnBack.setVerticalAlignment(SwingConstants.TOP);
JLabel lblUrl = new JLabel("URL:");
lblUrl.setBounds(80, 9, 35, 20);
paneBar.add(lblUrl);
txtURL = new JTextField();
txtURL.setBounds(115, 5, 310, 26);
paneBar.add(txtURL);
txtURL.setColumns(10);
lblName = new JLabel("Name:");
lblName.setBounds(435, 9, 47, 20);
paneBar.add(lblName);
txtName = new JTextField();
txtName.setBounds(480, 5, 155, 26);
paneBar.add(txtName);
txtName.setColumns(10);
btnAdd = new JButton("Add");
btnAdd.setBounds(635, 3, 61, 29);
paneBar.add(btnAdd);
//End top Add Bar
//Start Scroll and Panel configuration
paneSiteScroll = new JScrollPane();
paneSite = new JPanel();
paneSite.setLayout(null);
paneSite.setBounds(10, 40, 400, 600);
/*Testing different dimensions configuration*/
paneSiteScroll.setSize(new Dimension(300, 300));
paneSiteScroll.setBounds(10, 40, 300, 200);
paneSiteScroll.setPreferredSize(new Dimension(400, 300));
/*Testing different dimensions configuration*/
paneSiteScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
paneSiteScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
paneSiteScroll.getViewport().add(paneSite);
contentPane.add(paneSiteScroll);
paneSiteScroll.setVisible(true);
paneSite.setVisible(true);
//End Scroll and Panel configuration
try {
Categories.categories(paneSite); //GET CATEGORIES
} catch (Throwable e) {
e.printStackTrace();
}
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!txtURL.getText().isEmpty() || !txtName.getText().isEmpty()) {
InsertDB insert = new InsertDB();
try {
insert.insertDB("INSERT INTO sites (siUrl, siName) VALUES ('" + txtURL.getText() +"'"
+ ", '" + txtName.getText() + "')",
conn);
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
JOptionPane.showMessageDialog(null, "URL or Name cannot be empty!");
}
}
});
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Back action button
dispose();
}
});
}
}
This is my first question, I do not know what else to add, also i visited many question from stak overflow with similar problems but i couldn't figure it out.
Thanks in advance.
Finally fixed it, I restored the layout to null and added paneSite.setPreferredSize(new Dimension(600, 600)); after paneSite.setbounds. This make it work.
When I enter data to a database using the sample code below, the line System.out.println("Insertion complete") is shown on the console. When I go to the database, I find that the stored data is a blank.
I think the problem could be my sqlquery, but I don't see any problem with it.
Here is an example of my code:
public class SignUpFrame extends JFrame {
public SignUpFrame() {
super("SIGN UP");
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
setResizable(false);
setLocation(500, 250);
getContentPane().setBackground(Color.WHITE);
ImageIcon FrameIcon = new ImageIcon("images/signup.png");
JLabel frameicon = new JLabel(FrameIcon);
frameicon.setBounds(150, 0, 100, 100);
add(frameicon);
JLabel firstNamelbl,LastNameLbl,EmailAddressLbl,PasswordLbl,ConfirmPasswordLbl;
JTextField firstNametxt,LastNametxt,EmailAddresstxt;
JPasswordField passwordtxt,ConfirmPasswordtxt;
JButton OKbtn;
JButton CANCELbtn;
firstNamelbl = new JLabel("FIRST NAME:");
firstNametxt = new JTextField();
firstNametxt.setBounds(150, 110, 200, 20);
firstNamelbl.setBounds(50, 110, 100, 20);
LastNameLbl = new JLabel("USERNAME:");
LastNametxt = new JTextField();
LastNametxt.setBounds(150, 140, 200, 20);
LastNameLbl.setBounds(50,140, 100, 20);
EmailAddressLbl = new JLabel("EMAIL ADDRESS:");
EmailAddresstxt = new JTextField();
EmailAddresstxt.setBounds(150, 170, 200, 20);
EmailAddressLbl.setBounds(50, 170, 150, 20);
PasswordLbl = new JLabel("PASSWORD:");
passwordtxt = new JPasswordField();
passwordtxt.setBounds(150, 200, 200, 20);
PasswordLbl.setBounds(50, 200, 150, 20);
ConfirmPasswordLbl = new JLabel("CONFIRM PASSWORD:");
ConfirmPasswordtxt = new JPasswordField();
ConfirmPasswordtxt.setBounds(200, 230, 150, 20);
ConfirmPasswordLbl.setBounds(50, 230, 150, 20);
add(firstNamelbl);
add(firstNametxt);
add(LastNameLbl);
add(LastNametxt);
add(EmailAddressLbl);
add(EmailAddresstxt);
add(PasswordLbl);
add(passwordtxt);
add(ConfirmPasswordLbl);
add(ConfirmPasswordtxt);
OKbtn = new JButton("OK");
OKbtn.setBounds(100, 270, 50, 20);
add(OKbtn);
char [] pass = passwordtxt.getPassword();
String passWord = new String(pass);
String FIRSTNAME,USERNAME,EMAIL,PASSWORD;
FIRSTNAME = firstNametxt.getText().toString();
USERNAME =LastNametxt.getText().toString();
EMAIL = EmailAddresstxt.getText().toString();
PASSWORD = passWord;
OKbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String url = "jdbc:mysql://localhost:3306/System";
String user = "root";
String password = "";
Connection con;
try {
con = DriverManager.getConnection(url, user, password);
Statement statement = con.createStatement();
String sqlquery = "insert into signUp_tb "+
"(FirstName,UserName,Email,Password) values ('"+FIRSTNAME+"','"+USERNAME+"','"+EMAIL+"','"+PASSWORD+"')";
statement.executeUpdate(sqlquery);
System.out.println("Insertion complete");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
CANCELbtn = new JButton("CANCEL");
CANCELbtn.setBounds(170, 270, 100, 20);
add(CANCELbtn);
CANCELbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
}
}
You need to initialize your FIRSTNAME, USERNAME etc in ActionListener for OK button. You had initialized those Strings when there was no input data, that's why everything was blank. You want to get JTextFields values when user presses button. Not before.
Tested on SQLite.
OKbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
char [] pass = passwordTxt.getPassword();
String PASSWORD = new String(pass);
String FIRSTNAME,USERNAME,EMAIL;
FIRSTNAME = firstNameTxt.getText();
USERNAME = lastNameTxt.getText();
EMAIL = emailAddressTxt.getText();
String url = "jdbc:mysql://localhost:3306/System";
String user = "root";
String password = "";
Connection con;
try {
con = DriverManager.getConnection(url, user, password);
Statement statement = con.createStatement();
String sqlquery = "insert into signUp_tb "+
"(FirstName,UserName,Email,Password) values ('"+FIRSTNAME+"','"+USERNAME+"','"+EMAIL+"','"+PASSWORD+"')";
statement.executeUpdate(sqlquery);
System.out.println("Insertion complete");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
And setVisible(true) should be the last thing you do. Should look like:
SwingUtilities.invokeLater(() -> {
this.setVisible(true);
});
So you will launch it from EDT.
Edit: about setLayout(null) - Try those A Visual Guide to Layout Managers .
Although it is possible to do without a layout manager, you should use
a layout manager if at all possible. A layout manager makes it easier
to adjust to look-and-feel-dependent component appearances, to
different font sizes, to a container's changing size, and to different
locales. Layout managers also can be reused easily by other
containers, as well as other programs.
From Doing Without a Layout Manager (Absolute positioning)
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
I ve been working on a phonebook program on eclipse java
but and idk how to save information from a textfield to mysql and then be able use it in search, such as writing the name and finding all the info of the specific contact
I also want to save it to my sql
thats my code:
public class Phone {
private JFrame frame;
private JTextField firstfield;
private JTextField phonefield;
private JTextField emailfield;
private JTextField lastfield;
private JPanel MainScreen;
private JPanel newcontact;
private JPanel searchscreen;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Phone window = new Phone();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Phone() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel MainScreen = new JPanel();
frame.getContentPane().add(MainScreen, "name_6058038854379");
MainScreen.setLayout(null);
MainScreen.setVisible(true);
final JPanel newcontact = new JPanel();
newcontact.setLayout(null);
frame.getContentPane().add(newcontact, "name_791613670731");
newcontact.setVisible(false);
final JPanel searchscreen = new JPanel();
frame.getContentPane().add(searchscreen, "name_6068807854350");
searchscreen.setVisible(false);
JButton newrecord = new JButton("New Record");
newrecord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newcontact.setVisible(true);
MainScreen.setVisible(false);
}
});
newrecord.setBounds(63, 99, 116, 52);
MainScreen.add(newrecord);
JButton Search = new JButton("Search");
Search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchscreen.setVisible(true);
newcontact.setVisible(false);
}
});
Search.setBounds(243, 99, 102, 52);
MainScreen.add(Search);
JLabel myphonebook = new JLabel(" My Phonebook");
myphonebook.setBounds(162, 44, 102, 14);
MainScreen.add(myphonebook);
JLabel first = new JLabel("First Name:");
first.setBounds(118, 83, 66, 14);
newcontact.add(first);
JLabel last = new JLabel("Last Name:");
last.setBounds(118, 108, 66, 14);
newcontact.add(last);
JLabel Phone = new JLabel("Phone:");
Phone.setBounds(118, 143, 66, 14);
newcontact.add(Phone);
JLabel Emailadress = new JLabel("Email Adress:");
Emailadress.setBounds(118, 180, 66, 14);
newcontact.add(Emailadress);
firstfield = new JTextField();
firstfield.setColumns(10);
firstfield.setBounds(220, 80, 86, 20);
newcontact.add(firstfield);
lastfield = new JTextField();
lastfield.setColumns(10);
lastfield.setBounds(220, 108, 86, 20);
newcontact.add(lastfield);
phonefield = new JTextField();
phonefield.setColumns(10);
phonefield.setBounds(220, 140, 86, 20);
newcontact.add(phonefield);
emailfield = new JTextField();
emailfield.setColumns(10);
emailfield.setBounds(220, 177, 86, 20);
newcontact.add(emailfield);
JLabel lblNewContact = new JLabel("New Contact");
lblNewContact.setBounds(166, 30, 86, 14);
newcontact.add(lblNewContact);
JButton Save = new JButton("Save");
Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String firstname=firstfield.getText();
String lastname=lastfield.getText();
String phonenumber=phonefield.getText();
String emailadress=emailfield.getText();
}
});
Save.setBounds(81, 232, 89, 23);
newcontact.add(Save);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newcontact.setVisible(false);
MainScreen.setVisible(true);
}
});
cancel.setBounds(283, 232, 89, 23);
newcontact.add(cancel);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_6081212161880");
}
}
Write this into your savecommand. You should only create a database an table and change the uppercased words.
try
{
// create a mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://LOCATION/DATABASE";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into TABLE (first_name, last_name, phone_number, email_adress)"
+ " values (?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, firstname);
preparedStmt.setString (2, lastname);
preparedStmt.setString (3, phonenumber);
preparedStmt.setString (4, emailadress);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
I don't know what is wrong with this code; the SQL commands and the path looks alright. The connect to the db is ok; but when I try to pass a simple search; it returns that that table doesn't exist.
I tried it (the same code) in a different method to add data and it works fine; so I don't know what I'm doing wrong.
Thanks for your attention.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
First_GUI frame = new First_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn = null; //Call the Connection Class from JavaSqlite Class
/**
* Create the frame.
*/
public First_GUI() {
conn = Sqlite_Connection.dbconnector(); //call the connection CONN from SQLite class, method DBconnector.
setTitle("First GUI App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panel, BorderLayout.NORTH);
JLabel lblEnterTheName = new JLabel("Enter the Name :");
lblEnterTheName.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblEnterTheName.setVerticalAlignment(SwingConstants.TOP);
lblEnterTheName.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(lblEnterTheName);
NameField = new JTextField();
panel.add(NameField);
NameField.setColumns(10);
JButton Search = new JButton("Search");
Search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// ****************************************************************
// Here is the PROBLEM.
String sql = "SELECT * FROM Bank_001 where AccountName like ?";
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, NameField.getText());
ResultSet rs = pst.executeQuery();
rs.close();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
});
panel.add(Search);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextPane textPane = new JTextPane();
textPane.setFont(new Font("Tahoma", Font.PLAIN, 14));
scrollPane.setViewportView(textPane);
}
}
can you show the code for this ?
conn = Sqlite_Connection.dbconnector();
are you using setURL() on a new SQLiteDataSource ?
assuming using setURL, is it constructed correctly ?
Something like:
"jdbc:sqlite:sqlite-test.db"
i have written a code to create a sms form and i want to add the ability to show error message when the text area is empty. i put JOptionpane in my code but diologe dose not appear when i run the program! here is my code
private void initialize() {
frame = new JFrame("?????? ? ????? ?????");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JOptionPane optionPane = new JOptionPane();
JPanel middlePanel = new JPanel();
txtPath = new JTextField();
txtPath.setBounds(150, 10, 200, 21);
frame.getContentPane().add(txtPath);
txtPath.setColumns(10);
txtPath2 = new JTextField();
txtPath2.setBounds(150, 65, 200, 21);
frame.getContentPane().add(txtPath2);
txtPath2.setColumns(20);
JButton btnBrowse = new JButton("?????");
btnBrowse.setBounds(5, 10, 87, 23);
frame.getContentPane().add(btnBrowse);
final JButton ok = new JButton("?????");
ok.setBounds(250, 230, 87, 23);
frame.getContentPane().add(ok);
JButton cancel = new JButton("???");
cancel.setBounds(110, 230, 87, 23);
frame.getContentPane().add(cancel);
final JTextArea textarea = new JTextArea();
textarea.setBounds(50, 100, 300, 100);
frame.getContentPane().add(textarea);
textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setSize(10, 1);
progressBar.setForeground(Color.blue);
frame.getContentPane().add(progressBar);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
// For Directory
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// For File
//fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
txtPath.setText(fileChooser.getSelectedFile().toString());
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt", "rtf"));
}
}
});
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textarea.getLineCount()>=1)
{
test t=new test();
ReadTextFile readTextFile=new ReadTextFile();
t.testMethode(txtPath2.getText(), textarea.getText(),readTextFile.readFile(txtPath.getText()) );
}
else
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
}
GUI's are event driven environments. Something happens, you respond to it.
You if-else statement will never be false because the time it is executed, the textarea will be blank (have no text).
You need to respond to some event (ie send for example) at which time you would make your check to valid the form.
Take a look at Creating a GUI with Swing for more details
Updated with example
public class Example {
public static void main(String[] args) {
new Example();
}
public Example() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private final JTextArea msg;
public TestPane() {
msg = new JTextArea(10, 20);
JButton send = new JButton("Send");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JScrollPane(msg), gbc);
add(send, gbc);
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (msg.getText().trim().length() > 0) {
// Send msg
} else {
JOptionPane.showMessageDialog(TestPane.this, "Please write something (nice)", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
}
Updated based on changes to the answer by the OP
if(textarea.getLineCount()>=1) will always return true. Try using msg.getText().trim().length() > 0 instead to determine the JTextArea contains text or not...
Updated
mKobel has made an excellent point. You really should avoid using null layouts. You don't control what font size or screen DPI/resolution your application might need to work on. Layout managers take out the guess work.
You should try checking out A visual guide to layout managers and Using layout managers for more details