登徒梦 2014-03-26 05:12 采纳率: 0%
浏览 4077

如何在JFrame中通过按钮事件载入不同面板?

我写了一个程序,想实现按oval按钮时,绘制圆形,按rectangle时,绘制矩形。
所以我写了两个JPanel的子类oval类和rectangle类。然后在JFrame中 想通过点击
不同按钮实现不同jpanel类的调用,该如何实现?
jframe子类
public class DrawShapeByMouse extends JFrame {
//add two buttons
private JButton button1 = new JButton("Oval");
private JButton button2 = new JButton("Rectangle");
private JPanel ShapeJpanel = new DrawOval();

//Constructors
public DrawShapeByMouse() {
    this.add(ShapeJpanel,BorderLayout.CENTER);
    add(button1,BorderLayout.SOUTH);
    add(button2,BorderLayout.NORTH);

    //给按键注册监听器
    button1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            ShapeJpanel = new DrawOval();
        }
    });

    button2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            ShapeJpanel = new DrawRectangle();
            System.out.println("你好世界!");
        }
    });
}

public static void main(String[] args) {
    DrawShapeByMouse frame = new DrawShapeByMouse();
    frame.setTitle("DrawOvalByMouse");
    frame.setSize(400,400);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

}

oval类
class DrawOval extends JPanel {

private final Color[] color = {Color.red,Color.YELLOW,Color.GREEN,Color.ORANGE};   //填充颜色

private int xCoord = 0;//
private int yCoord = 0;//圆心坐标
private final int radius = 30; //半径
private int num = 0;  //用来控制颜色

//Constructors
public DrawOval() {

    //鼠标点击事件注册监听器并且实现接口
    this.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            xCoord = e.getX();
            yCoord = e.getY();
            num = (int)(Math.random()*color.length);
            repaint();
        }
    });
    this.addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent e) {
            xCoord = e.getX();
            yCoord = e.getY();
            repaint();
        }
    });
}

//绘制面板
protected void paintComponent(Graphics g) {
    //super.paintComponent(g);

    g.setColor(color[num]);
    g.fillOval(xCoord-radius, yCoord-radius,radius,radius);
}

}
rectangle同oval类;

  • 写回答

1条回答 默认 最新

  • zhuggentanjia 2014-06-27 01:47
    关注

    用repaint行不

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog