I was trying my first code in java swing and got many errors. my code is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Swinging extends JFrame
{
JTextField ans;
int count =0;
static final long serialVersionUID = 1L;
Swinging()
{
Container cp= getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("value",7));
ans=new JTextField("0",10);
cp.add(ans);
JButton inc= new JButton("increment");
cp.add(inc);
inc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
++count;
ans.setText(count+"");
}
});
setSize(200,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class Usingswing {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Swinging(); // Let the constructor do the job
}
});
}
}
and the errors are as follows:
Exception in thread "AWT-EventQueue-0" 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 hopeso.Swinging.<init>(Usingswing.java:16)
at hopeso.Usingswing$1.run(Usingswing.java:45)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
i tried solving my problem using the questions posted by other people but it didn't workout. please help.
The error occurs because of the following line:
You're using
JLabel
's constructor that receives the text and the horizontal alignment. The alignment is anint
, but it has to be one of the following constants, otherwise it will throw theIllegalArgumentException
:These constants are defined in
SwingConstants
, so you can just write something like this: