Reputation: 1
I am new to Java Swing. i cretaed a simple JFrame as shown below in the code, but when the line statusLabel = new JLabel("statusLabel", JLabel.WEST);
is there i receive the below posted errors at run time, and when i comment that line out, the JFrame appears.
please let me know why this line statusLabel = new JLabel("statusLabel", JLabel.WEST);
causes error.
public GUI() {
// TODO Auto-generated constructor stub
prepareGUI();
}
private void prepareGUI() {
// TODO Auto-generated method stub
mainFrame = new JFrame("Swing Example");
mainFrame.setSize(400, 400);
headerLabel = new JLabel("headerLabel", JLabel.CENTER);
statusLabel = new JLabel("statusLabel", JLabel.WEST);//this line when it is exist, causes errors
mainFrame.add(headerLabel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
error:
Exception in thread "main" java.lang.IllegalArgumentException: horizontalAlignment
at javax.swing.JLabel.checkHorizontalKey(Unknown Source)
at javax.swing.JLabel.setHorizontalAlignment(Unknown Source)
at javax.swing.JLabel.<init>(Unknown Source)
at javax.swing.JLabel.<init>(Unknown Source)
at test.GUI.prepareGUI(GUI.java:23)
at test.GUI.<init>(GUI.java:15)
at test.GUI.main(GUI.java:31)
Update:
now after using .LEFT instead, the text that suppose to be placed at the .CENTER disappeared. why that is happening
Upvotes: 0
Views: 4350
Reputation: 1
you could change this statement
statusLabel = new JLabel("statusLabel", JLabel.WEST);
to
statusLabel = new JLabel("statusLabel", SwingConstants.WEST);
notice to
import javax.swing.SwingConstants;
Upvotes: 0
Reputation: 42176
That's not a valid argument for the alignment.
From the API:
horizontalAlignment - One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.
Edit- You're also adding both JLabels to the default position of the JFrame, which in your case will be BorderLayout.CENTER. That's why your JLabel is not visible. Either modify the layout of the JFrame, or place the JLabels in different positions in your default BorderLayout. More info here: http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
Upvotes: 2
Reputation: 7769
You cannot use JLabel.WEST
according to the Documentation:
public JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal alignment. The label is centered vertically in its display area.
Parameters: text - The text to be displayed by the label.
horizontalAlignment - One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.
The only options for horizontalAlignment are LEFT, CENTER, RIGHT, LEADING or TRAILING
So in your case use JLabel.LEFT
Upvotes: 1