请教JAVA的一个画图问题!!!

来源:百度知道 编辑:UC知道 时间:2024/05/20 09:11:12
请问我想在j1中点Draw后在j2中画出来,这段代码应该怎么修改?

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class ShortTest4 extends JFrame implements ActionListener{

JButton jb1 = new JButton("Draw");

public ShortTest4()
{
setLayout(new GridLayout(1,2));
JPanel j1 = new JPanel();
JPanel j2 = new JPanel();
jb1.addActionListener(this);
j1.add(jb1);
add(j1);
add(j2);
}

public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawOval(0,0,this.getWidth(),this.getHeight());
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jb1)
{

}
}

public static void main(String[] args)
{
ShortTest4 m = new S

改了一下,详细见注释:

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ShortTest4 extends JFrame implements ActionListener {

boolean paint = false;
JButton jb1;
JPanel j1;
JPanel j2;

public ShortTest4() {
//用于添加panel
Container contentPane = this.getContentPane();
//不用layout也可以,这个layout是左右布局,我用的上下布局
//setLayout(new GridLayout(1, 2));
j1 = new JPanel();
jb1 = new JButton("Draw");
jb1.addActionListener(this);
j1.add(jb1);
j2 = new JPanel(){
//paint方法定义到这里
public void paint(Graphics g) {
//这句很关键,没这句画出来的图是乱的
super.paint(g);
//判断是否画图,开始paint为false,不画
if(paint) {
g.setColor(Color.red);