【发布时间】:2018-12-02 15:38:21
【问题描述】:
package gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class gui7 implements ActionListener {
JFrame frame=new JFrame();
JButton button=new JButton("Click me");
public static void main(String args[]) {
gui7 a=new gui7();
a.go();
}
public void actionPerformed(ActionEvent event) {
frame.repaint(); //to call paintcomponent
}
public void go() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new gui7());
gui8 f=new gui8();
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.getContentPane().add(BorderLayout.CENTER,f);
frame.setSize(300,300);
frame.setVisible(true);
}
}
package gui;
import java.awt.*;
import javax.swing.*;
public class gui8 extends JPanel {
public void paintComponent(Graphics g) {
g.fillRect(0, 0, this.getWidth(),this.getHeight());
//创建随机颜色的代码
int red=(int)(Math.random()*255);
int blue=(int)(Math.random()*255);
int green=(int)(Math.random()*255);
Color rand=new Color(red,blue,green);
g.setColor(rand);
g.fillOval(70, 70, 100, 100);
}
}
【问题讨论】:
-
每次调整 JFrame 大小时都会重新绘制椭圆形,这是期望的行为吗?
标签: java jframe components jbutton paint