猿问

JFrame frame;的位置为什么放在此处?

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;


public class SimpleGui3C implements ActionListener {

JFrame frame;  //这里要放在这里

public static void main(String[] args) {

SimpleGui3C gui = new SimpleGui3C();

gui.go();

}

public void go(){

frame = new JFrame();//JFrame frame = new JFrame();  写成这样子,不要上面的JFrame frame;怎么就报错了

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button = new JButton("Change color");

button.addActionListener(this);

MyDrawPanel drawPanel = new MyDrawPanel();

frame.getContentPane().add(BorderLayout.SOUTH, button);

frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

frame.setSize(300,300);

frame.setVisible(true);

}

public void actionPerformed(ActionEvent event) {

frame.repaint();

}


}

import java.awt.*;

import javax.swing.JPanel;


public class MyDrawPanel extends JPanel {

public void paintComponent(Graphics g){

g.fillRect(0, 0, this.getWidth(), this.getHeight());

int red = (int)(Math.random() * 255);

int green = (int)(Math.random() * 255);

int blue = (int)(Math.random() * 255);

Color randomColor = new Color(red, green, blue);

g.setColor(randomColor);

g.fillOval(70, 70, 100, 100);

}

}



慕粉3355806
浏览 1693回答 1
1回答

王大厉

 actionPerformed(ActionEvent event) 因为你这个方法用到了 frame
随时随地看视频慕课网APP

相关分类

Java
我要回答