| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 509 人关注过本帖
标题:想通过点击不同按钮实现不同jpanel类的调用,该如何实现?
只看楼主 加入收藏
haiboself
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:193
专家分:196
注 册:2013-10-23
结帖率:100%
收藏
 问题点数:0 回复次数:0 
想通过点击不同按钮实现不同jpanel类的调用,该如何实现?
我写了一个程序,想实现按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类;

搜索更多相关主题的帖子: private public 如何 
2014-03-26 13:13
快速回复:想通过点击不同按钮实现不同jpanel类的调用,该如何实现?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.028893 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved