bdiddy05
asked on
Problems with JFrame
I created a program in Java that allows you to create a phone list. Everything works properly but when the JFrame appears the title name is not aligned with the box, its right next to the title. I want "name" to be next to the box, just like "number" is next to the box.
first code:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CreatePhoneList extends JFrame implements ActionListener
{
private JLabel friendsList = new JLabel("Friend Contact List");
Font bigFont = new Font("Helvetica", Font.ITALIC, 24);
private JTextField name = new JTextField(8);
private JTextField number = new JTextField(4);
private JLabel nLabel = new JLabel("Name");
private JLabel pLabel = new JLabel("Number");
private JButton enterDataButton= new JButton("Enter data");
private Container con = getContentPane();
DataOutputStream ostream;
public CreatePhoneList()
{
super("Create Phone List");
try
{
ostream = new DataOutputStream(new FileOutputStream("phone.dat"));
}
catch(IOException e)
{
System.err.println("File not opened");
System.exit(1);
}
setSize(320,2000);
con.setLayout(new FlowLayout());
friendsList.setFont(bigFont);
con.add(friendsList);
con.add(nLabel);
con.add(name);
con.add(pLabel);
con.add(number);
con.add(enterDataButton);
enterDataButton.addActionListener(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e1)
{
try
{
ostream.writeUTF(name.getText());
ostream.writeUTF(number.getText());
name.setText("");
number.setText("");
}
catch(NumberFormatException e2)
{
System.err.println("Invalid data inputted, only numeric data");
}
catch(IOException e3)
{
System.err.println("Error writing file");
System.exit(1);
}
}
}
second code:
public class UserPhoneList
{
public static void main(String[] args)
{
CreatePhoneList cpl = new CreatePhoneList();
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I created two JPanels, one for the title and one for textfields, labels and button.
Remember GridLayout specifies the number of columns and rows that you want to use.
Finally add these panels to your container that also has gridLayout (35 rows, 1 column).
Your panels will fit only the two first rows.
You can also add extras spaces to your Strings in order to move closer to the fields.
Open in new window