プロが教えるわが家の防犯対策術!

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

public class R11Sample1 extends JFrame {
Rect r1 = new Rect(Color.red, 100, 100, 80, 60);
Rect r2 = new Rect(new Color (0.5f, 1f, 0f, 0.7f), 150, 120, 60, 90);
Oval = new Oval(Color.blue, 60, 50, 10, 10);
JPanel panel = new JPanel() {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
r1.draw(g2); r2.draw(g2);
}
};
public R11Sample1() {
setSize(400, 350); setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(panel);
}
public static void main(String[] args) { new R11Sample1().setVisible

(true); }
}

class Rect {
Paint pat;
int xpos, ypos, width, height;
public Rect(Paint p, int x, int y, int w, int h) {
pat = p; xpos = x; ypos = y; width = w; height = h;
}
public void draw(Graphics2D g) {
g.setPaint(pat);
g.fillRect(xpos-width/2, ypos-height/2, width, height);
}
}


class Oval {
Paint pat;
int xpos, ypos, radius;
public Oval(Paint p, int x, int y, int width, int height) {
pat = p; xpos = x; ypos = y; width = w; height = h;
}
public void draw(Graphics2D g) {
g.setPaint(pat);
g.fillOval(xpos-width/2, ypos-height/2, width, height);
}
}

これでコンパイルすると、
Identifierがありません
といわれました。
どこを直せばいいのでしょうか。
また、全体的に間違ったところがあったら教えてください。

A 回答 (1件)

どこを・・・といっても、ちょこちょこと細かな間違いが・・・。


とりあえず、動くものを。(クラス名はこちらでチェックする関係で変えてあります)

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

public class SampleApp extends JFrame {
Rect r1; // フィールドではnewしない
Rect r2;
Oval o1;
JPanel panel;

public void init() { // 初期化処理をメソッドにまとめた
r1 = new Rect(Color.red, 100, 100, 80, 60);
r2 = new Rect(new Color(0.5f, 1f, 0f, 0.7f), 150, 120, 60, 90);
o1 = new Oval(Color.blue, 60, 50, 10, 10);
panel = new JPanel() {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
r1.draw(g2);
r2.draw(g2);
}
};
}

public SampleApp() {
init(); // 初期化処理を呼び出す
setSize(400, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(panel);
}

public static void main(String[] args) {
new SampleApp().setVisible

(true);
}
}

class Rect {
Paint pat;
int xpos, ypos, width, height;

public Rect(Paint p, int x, int y, int w, int h) {
pat = p;
xpos = x;
ypos = y;
width = w;
height = h;
}

public void draw(Graphics2D g) {
g.setPaint(pat);
g.fillRect(xpos - width / 2, ypos - height / 2, width, height);
}
}

class Oval {
Paint pat;
int xpos, ypos, width, height, radius; // width,heightが抜けてる

public Oval(Paint p, int x, int y, int w, int h) { // 仮引数名を修正
pat = p;
xpos = x;
ypos = y;
width = w;
height = h;
}

public void draw(Graphics2D g) {
g.setPaint(pat);
g.fillOval(xpos - width / 2, ypos - height / 2, width, height);
}

修正点
・フィールドでnewしてインスタンスを設定していますが、これは単純にnewするだけなら可能ですが、newの引数内に更にnewでインスタンスを作成したり、無名クラスでメソッドを埋め込んだりといったことはできません。
 こうした処理は、本来コンストラクタで行うべきことです。とりあえず、どうしたいのかわからないのでinitというメソッドにまとめてコンストラクタから呼び出す形にしてありますが、最終的にはコンストラクタでまとめるべきでしょう。

・他、フィールドで用意すべき変数が未定義だったり、メソッドの仮引数の名前と実際に利用している変数名が違ったりと、細かなところでミスが目立ちました。
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!