JCheckBox,我的构造函数有问题。

时间:2015-04-12 02:45:08

标签: java jframe jcheckbox

中间的“公共宿舍()”区域给了我一个错误。我在声明构造函数之前遗漏了什么?我不明白这是一个非法的表达方式。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Dorm extends JFrame implements ItemListener {

public static void main(String[] args){

FlowLayout flow = new FlowLayout();
JLabel label = new JLabel("Please select items you would like for your dorm   room: ");

  JCheckBox Internet = new JCheckBox("Internet", false);
  JCheckBox Cable = new JCheckBox("\nCable", false);
  JCheckBox Microwave = new JCheckBox("\nMicrowave", false);
  JCheckBox Refridgerator = new JCheckBox("\nRefridgerator", false); 

     public Dorm(){
        super("Dorm Selections");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        Internet.addItemListener(this);
        Cable.addItemListener(this);
        Microwave.addItemListener(this);
        Refridgerator.addItemListener(this);
        add(labale);
        add(Internet);
        add(Cable);
        add(Microwave);
        add(Retriderator);
     }   

  } 
 }

Dorm.java:22: error: illegal start of expression
     public Dorm(){
     ^
Dorm.java:22: error: ';' expected
     public Dorm(){
                  ^
2 errors

2 个答案:

答案 0 :(得分:2)

你应该把构造函数放在method.like this之外。并在main方法中创建新对象。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Dorm extends JFrame implements ItemListener {


     public Dorm(){
        super("Dorm Selections");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        FlowLayout flow = new FlowLayout();
        JLabel label = new JLabel("Please select items you would like for your dorm   room: ");

        JCheckBox Internet = new JCheckBox("Internet", false);
        JCheckBox Cable = new JCheckBox("\nCable", false);
        JCheckBox Microwave = new JCheckBox("\nMicrowave", false);
        JCheckBox Refridgerator = new JCheckBox("\nRefridgerator", false); 

        Internet.addItemListener(this);
        Cable.addItemListener(this);
        Microwave.addItemListener(this);
        Refridgerator.addItemListener(this);
        add(labale);
        add(Internet);
        add(Cable);
        add(Microwave);
        add(Retriderator);
     }   

     public static void main(String[] args){
         new Dorm();
     }

  } 

答案 1 :(得分:1)

您的构造函数位于main方法中。 将构造函数移动到类级别。