问题描述
- 如何在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类;
解决方案
用repaint行不
时间: 2024-10-22 03:27:17