3

我是 Swing 新手,正在 Eclipse 中制作一个非常基本的事件处理程序。这是我写的代码:

public class SwingDemo2 {

JLabel jl;

public SwingDemo2() {
    JFrame jfr = new JFrame("Swing Event Handling");
    jfr.setSize(250, 100);
    jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    jl = new JLabel();
    jl.setVisible(false);

    JButton jb1 = new JButton("OK");
    jb1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            jl.setText("You Pressed OK");
            jl.setVisible(true);
        }
    });

    JButton jb2 = new JButton("Reset");
    jb2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            jl.setText("You Pressed Reset");
            jl.setVisible(true);
        }
    });

    jfr.setLayout(new BorderLayout());
    jfr.add(jl, SwingConstants.NORTH);
    jfr.add(jb1, SwingConstants.EAST);
    jfr.add(jb2, SwingConstants.WEST);
    jfr.setVisible(true);
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new SwingDemo2();
        }
    });
}

}

Eclipse 提示我打开调试透视图,他向我显示错误:
Thread [AWT-EventQueue-0] (Suspended (exception IllegalArgumentException)) EventDispatchThread.run() line: not available [local variables unavailable]

当我使用FlowLayout而不是BorderLayout.

我一直在尝试在门户网站上查找有关错误的信息,我遇到了这个类似的问题。答案是在不解释问题的情况下更改一堆设置(这也无济于事)。请解释错误,以便我确保不再重复。提前谢谢!

注意:更新了错误信息

4

2 回答 2

4

尝试使用

jfr.add(jl, BorderLayout.PAGE_START);
jfr.add(jb1, BorderLayout.LINE_START);
jfr.add(jb2, BorderLayout.LINE_END);

Java Docs 的重要说明:

Before JDK release 1.4, the preferred names for the various areas were different, 
ranging from points of the compass (for example, BorderLayout.NORTH for the 
top area) to wordier versions of the constants we use in our examples. 
The constants our examples use are preferred because they are standard and 
enable programs to adjust to languages that have different orientations.

有关 BorderLayout 的更多信息,请参阅如何使用 BorderLayout

要真正知道为什么会出现该错误,我只是在代码中编写了这两行

System.out.println("SwingConstants.NORTH : " + SwingConstants.NORTH);
System.out.println("BorderLayout.PAGE_START : " + BorderLayout.PAGE_START);

输出如下:

SwingConstants.NORTH : 1
BorderLayout.PAGE_START : First

查看输出,您可以理解使用SwingContantsover 的值有什么问题BorderLayout Constraints

于 2013-01-06T16:12:10.283 回答
4
  • 使用 BorderLayout代替SwingConstants,jfr.add(jl, BorderLayout.NORTH);

  • SwingConstantsTextLayout, 不为JComponents layout

于 2013-01-06T16:12:56.973 回答