Originally Posted by
gpelefty90
Thank you for your reply. I am still confused on how to align the JLabel to a JTextField. I was wondering if you could show me example. It seems i have to put all of these fields in a Layout to create and organize the GUI application.
Thanks
Try this example code. It does compile and performs correctly when run:
[CODE]
import javax.swing.*;
import java.awt.*;
public class LabelDemo {
public static void main(String[] args) {
new LabelDemo().start();
}
public void start() {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Here is one example using a JPanel to place the label directly to the right.
JPanel panel = new JPanel();
//Let's allign the components to the left side of the panel by telling its Layout Manager to do so.
FlowLayout layout = (FlowLayout) panel.getLayout();
layout.setAlignment(FlowLayout.LEFT);
panel.setLayout(layout);
JTextField txt = new JTextField(20);
JLabel label = new JLabel("Hey! Look at me!");
//Just as a note, you can also try just pre-setting the text of a JTextField to whatever you wanted to label it.
//Then the user can just delete the pre-set text and enter the correct value.
txt.setText("Preset text!");
//Now it's time to add the stuff...
panel.add(txt);
panel.add(label);
/*
* The FlowLayout alligns things from left to right (can be configured) and is the nicest to you usually about
* giving you the preferred size you want. You cannot, however, choose a specific place for the component to go.
* They are simply alligned left to right from the top of the JPanel to the bottom.
*/
frame.setContentPane(panel);
frame.setSize(400,100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
[/CODE]
Keep in mind there are other ways to do this. Lets say you wanted the JTextField on the far left and the JLabel on the far right. Then you could make the JPanel have a BorderLayout and assign them positions at BorderLayout.EAST and BorderLayout.WEST.
Let me know if you have questions.