线程中的java异常" AWT-EventQueue-0" java.lang.IllegalArgumentException异常

时间:2015-06-26 17:12:00

标签: java swing jlabel illegalargumentexception

我在java swing中尝试了我的第一个代码并且遇到了很多错误。我的代码是:

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
             }
          });

    }

}

,错误如下:

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)

我尝试使用其他人发布的问题来解决我的问题,但它没有锻炼。请帮忙。

1 个答案:

答案 0 :(得分:6)

由于以下行而发生错误:

cp.add(new JLabel("value",7));

您正在使用接收文本和水平对齐的JLabel构造函数。对齐是int,但它必须是以下常量之一,否则会抛出IllegalArgumentException

  • LEFT(2)
  • CENTER(0)
  • 右(4)
  • LEADING(10)
  • TRAILING(11)

这些常量在SwingConstants中定义,所以你可以这样写:

cp.add(new JLabel("value", SwingConstants.CENTER));