2014-11-18 8 views
0

책에있는 과제의 지시 사항을 따르고 있습니다. 나는 단추를 만들고 있는데, 한 단추는 "노란색"을 클릭하면 사용자가 배경을 노란색으로 바꾼다. 컴파일 오류가 발생합니다.자바 초보자가 기호 오류를 찾을 수 없습니다.

Error; cannot find symbol 
    add(Red, BorderLayout.Red); 
same goes for add(Yellow, BorderLayout.Yellow); 
       add(Cyan, BorderLayout.CYAN); 
       add(Magenta, BorderLayout.MAGENTA); 
       add(White, BorderLayout.WHITE); 

also error; cannot find symbol 
for ButtonRed.addActionListener(this); 
       ButtonYellow.addActionListener(this); 
       ButtonCyan.addActionListener(this); 
       ButtonMagenta.addActionListner(this); 
       ButtonWhite.addActionListener(this); 

여기 내 코드입니다.

/* 
Chapter 6: Borders 
Programmer:Jesse-le Edwards 
Date:11-16-14 
Filename: Buttons.java 
Purpose: 
*/ 

import java.awt.*; 
import java.applet.*; 
import java.awt.event.*; 


public class Buttons extends Frame implements ActionListener { 

    public void paint(Graphics g) { 
     setBackground(Color.red); 
    } 

    public void actionPerformed(ActionEvent e) { 


     String arg = e.getActionCommand(); 
     if (arg == "Yellow") { 
      setBackground(Color.yellow); 
     } 
    } 

    public Buttons() { 

     //set the layout 
     setLayout(new BorderLayout(20, 5)); 

     //Add buttons 
     Button Red = new Button("Red"); 
     Button Yellow = new Button("Yellow"); 
     Button Cyan = new Button("Cyan"); 
     Button West = new Button("Magenta"); 
     Button White = new Button("White"); 

     add(Red, BorderLayout.RED); 
     add(Yellow, BorderLayout.YELLOW); 
     add(Cyan, BorderLayout.CYAN); 
     add(Magenta, BorderLayout.MAGENTA); 
     add(White, BorderLayout.WHITE); 

     ButtonRed.addActionListener(this); 
     ButtonYellow.addActionListener(this); 
     ButtonCyan.addActionListener(this); 
     ButtonMagenta.addActionListner(this); 
     ButtonWhite.addActionListener(this); 

     //override the windowClosing event 
     addWindowListener(
       new WindowAdapter() { 
        public void windowClosing(WindowEvent e) { 
         System.exit(0); 
        } 
       } 
     ); 

    } 

    public static void main(String[] args) { 

     // set frame properties 
     Buttons f = new Buttons(); 
     f.setTitle("Border Application"); 
     f.setBounds(200, 200, 300, 300); 
     f.setVisible(true); 
    } 

} 
+3

[BorderLayout'] (https://docs.oracle.com/javase/7/docs/api/java/awt/BorderLayout.html) JavaDocs에서 시작하여 필드가 없습니다. 'Red' (또는 당신이 사용하려고 시도한 다른 값)라고 불리는 것입니다. 그렇다면 [자바에서 문자열을 어떻게 비교합니까?] (http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)를보십시오. 왜냐하면'arg == "Yellow" ''String''이 Java에서 어떻게 비교되는지 ... – MadProgrammer

+0

문자열은'foo.equals ("bar")'와 비교되어야합니다. 이것은 당신의 코드에서 arg.equals ("Yellow")'가 될 것이다. 'Button'은'JButton'이어야합니다. 변수 이름은'ActionListener'를 추가 한 행과 일치하지 않습니다. 'ButtonMagenta.addActionListner (this);는 ListA에있는 E를 유의하여 addActionListener (this) 여야합니다. – Charlie

+1

'ButtonRed '란 무엇입니까? 나는 그것의 'Red', Red.addActionListener (this)로 변경한다고 생각한다; – Anptk

답변

1

코드에 많은 문제가 있습니다. 설명 하겠지만 아래 코드는 작동합니다. 코드가 정확히 수행해야 할 작업을 지정하지 않았으므로 작업을 계속 진행하기위한 지침으로 사용할 수 있습니다.

가장 큰 실수는 Button Red = new Button("Red");과 같은 버튼을 선언했지만 ButtonRed을 변수로 사용하려고 시도한 경우입니다.

equals()이 아닌 ==을 사용하여 문자열을 비교해야합니다.

BorderLayout에는 Red라는 필드가 없습니다. 나는 임의의 위치, 북쪽, 남쪽, 동쪽, 서쪽을 자유롭게 사용했다.

이제 프로젝트를 계속 개선 할 수 있습니다.


import java.awt.BorderLayout; 
import java.awt.Button; 
import java.awt.Color; 
import java.awt.Frame; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.WindowAdapter; 
import java.awt.event.WindowEvent; 

public class Buttons extends Frame implements ActionListener 
{ 
    public void paint(Graphics g) { 
     setBackground(Color.red); 
    } 

    public void actionPerformed(ActionEvent e) { 

     String arg = e.getActionCommand(); 
     if (arg.equals("Yellow")) 
      setBackground(Color.yellow); 
    } 

    public Buttons() 
    { 
     setLayout(new BorderLayout(20, 5)); 

     Button Red = new Button("Red"); 
     Button Yellow = new Button("Yellow"); 
     Button Cyan = new Button("Cyan"); 
     Button West = new Button("Magenta"); 
     Button White = new Button("White"); 

     add(Red, BorderLayout.NORTH); 
     add(Yellow, BorderLayout.WEST); 
     add(Cyan, BorderLayout.EAST); 
     add(White, BorderLayout.SOUTH); 

     Red.addActionListener(this); 
     Yellow.addActionListener(this); 
     Cyan.addActionListener(this); 
     White.addActionListener(this); 

     addWindowListener(new WindowAdapter() 
     { 
      public void windowClosing(WindowEvent e) 
      { 
       System.exit(0); 
      } 
     }); 
    } 

    public static void main(String[] args) { 

     // set frame properties 
     Buttons f = new Buttons(); 
     f.setTitle("Border Application"); 
     f.setBounds(200, 200, 300, 300); 
     f.setVisible(true); 
    } 
} 
+0

실행 중일 때 페이지 하단에 단 1 개의 버튼 (흰색)이 표시됩니다. 'Panel'을 추가하고 그것에 버튼을 추가하십시오. 'Frame'은 오직 하나의 객체 만 처리 할 수 ​​있습니다! – Charlie

+1

누가 잘못했는지 설명해 주시던 분. 유효한 포인트를 작성하면 기꺼이 삭제할 것입니다. – FunctionR

+0

@Charlie는 OP가 버튼의 위치를 ​​지정 했습니까? – FunctionR

1

우선 모든 내가 그것을 실행하기 위해 코드의 여러 부분을 고정

자바

떨어져 세계에 오신 것을 환영합니다,하지만 주로이 부분은 대부분의 문제

//set the layout 
setLayout(new BorderLayout(20,5)); 

//Add buttons 
Button Red = new Button("Red"); 
Button Yellow = new Button("Yellow"); 
Button Cyan = new Button("Cyan"); 
Button West = new Button("Magenta"); 
Button White = new Button("White"); 

add(Red, BorderLayout.RED); 
add(Yellow, BorderLayout.YELLOW); 
add(Cyan, BorderLayout.CYAN); 
add(Magenta, BorderLayout.MAGENTA); 
add(White, BorderLayout.WHITE); 

ButtonRed.addActionListener(this); 
ButtonYellow.addActionListener(this); 
ButtonCyan.addActionListener(this); 
ButtonMagenta.addActionListner(this); 
ButtonWhite.addActionListener(this); 

//set the layout 
setLayout(new BorderLayout(20,5)); 

했다 명명 스키마를 사용하는 고정 코드 :

//Add buttons 
Button Red = new Button("Red"); 
Button Yellow = new Button("Yellow"); 
Button Cyan = new Button("Cyan"); 
Button Magenta = new Button("Magenta"); 
Button White = new Button("White"); 

add(Red,BorderLayout.NORTH); 
add(Yellow,BorderLayout.EAST); 
add(Cyan,BorderLayout.SOUTH); 
add(Magenta,BorderLayout.WEST); 
add(White,BorderLayout.CENTER); 

Red.addActionListener(this); 
Yellow.addActionListener(this); 
Cyan.addActionListener(this); 
Magenta.addActionListener(this); 
White.addActionListener(this); 

변수에 단지 naming convention을 사용해야합니다. 빨간색 => 빨강은 수업이 아니며 단지 속성이기 때문에 사용하십시오.

귀하의 전체 코드 실행중인 것을 :

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.WindowAdapter; 
import java.awt.event.WindowEvent; 

public class Buttons extends Frame implements ActionListener 
{ 

    public void paint(Graphics g) 
    { 
     setBackground(Color.red); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 

     String arg = e.getActionCommand(); 
     if (arg == "Yellow") 
     { 
      setBackground(Color.yellow); 
     } 
    } 

    public Buttons() 
    { 

     //set the layout 
     setLayout(new BorderLayout(20, 5)); 

     //Add buttons 
     Button Red = new Button("Red"); 
     Button Yellow = new Button("Yellow"); 
     Button Cyan = new Button("Cyan"); 
     Button Magenta = new Button("Magenta"); 
     Button White = new Button("White"); 

     add(Red, BorderLayout.NORTH); 
     add(Yellow, BorderLayout.EAST); 
     add(Cyan, BorderLayout.SOUTH); 
     add(Magenta, BorderLayout.WEST); 
     add(White, BorderLayout.CENTER); 

     Red.addActionListener(this); 
     Yellow.addActionListener(this); 
     Cyan.addActionListener(this); 
     Magenta.addActionListener(this); 
     White.addActionListener(this); 

     //override the windowClosing event 
     addWindowListener(new WindowAdapter() 
     { 
      public void windowClosing(WindowEvent e) 
      { 
       System.exit(0); 
      } 
     }); 

    } 

    public static void main(String[] args) 
    { 
     // set frame properties 
     Buttons f = new Buttons(); 
     f.setTitle("Border Application"); 
     f.setBounds(200, 200, 300, 300); 
     f.setVisible(true); 
    } 
} 

몇 가지 팁하여 작동하도록 : 모든 모든 그리기 작업을 새로 고침에

public void paint(Graphics g) 
{ 
    setBackground(Color.red); 
} 

이 항상 배경 빨간색 페인트, 그래서 당신의 버튼 이벤트입니다 페인트 이벤트에 의해 항상 훼손됩니다. 그래서 생성자로 옮길 수 있습니다.

편집 :

당신은 더이 See this discussion on equal vs contentEquals

if (arg.contentEquals("Yellow")) 
{ 
    setBackground(Color.yellow); 
} 

팁에 같거나 contentEquals을 사용한다 : 당신은 이클립스 또는 Intellj 같은 IDEA를 사용한다, 코드 서식이 엉망이었다.

+0

감사합니다. 그것은 내가 정말로 이해하지 못한 부분이었습니다. 나는 초보자이지만 나는 지금 그것을 더 잘 이해하고 있다고 생각한다. 또한 버튼과 빨강, 노랑 등을 클릭하면 배경이 바뀌도록 배경색을 빨간색으로 설정 한 다음 버튼과 액션 리스너를 추가하라는 안내가있는 과제를 수행하고 있습니다. 내가 처음에 게시 할 때 내 형식에 대해 유감스럽게 생각했지만 코드가 4 칸만큼 제대로 형식화되지 않았기 때문에 왼쪽으로 모두 플러시 한 다음 Ctrl 키를 누릅니다. 나는이 사이트를 처음 접했지만 이제는 그 사실을 알지 못했다. –

+0

나는 답안의 코드가 내 것과 얼마나 흡사 하는지를 좋아한다. – FunctionR

관련 문제