网友您好, 请在下方输入框内输入要搜索的题目:
本题的功能是监听鼠标左右键的单击,以及面板中滚动条的添加。在窗口的画板中单击鼠标左键,在单击的位置绘制一个圆,当绘制的圆大于画板的大小时,画板就添加滚动条,在画板中单击鼠标右键,则清除画板中的所有图形。 import javax.swing.*; import javax.swing.event.MouselnputAdapter; import java.awt.*; import java.awt.event.*; import java.util.*; public class java3 extends JPanel{ private Dimension size; private Vector objects; private final Color colors[]={ Color.red,Color.blue,Color.green,Color.or- ange, Color.cyan,Color.magenta,Color.darkGray, Color.yellow); private final int color_n=colors.length; JPanel drawingArea; public java3{ setopaque(true); size=new Dimension(0,0); bjects=new Vector; JLabel instructionsLeft=new JLabel("单击鼠标 左键画圆."); JLabel instructionsRight=new JLabel("单击鼠 标右键清空画板."); JPanel instructionPanel=new JPanel(new Grid- Layout(0,1)); instructionPanel.add(instructionsLeft); instructionPanel.add(instructionsRight); drawingArea=new JPanel{ protected void paintComponent(Graphics g){ super.paintComponent(g); Rectangle rect; for(int i=0;i<objects.size;i++){ rect=(Rectangle)objects.elementAt(i): g.setColor(colors[(i%color_n)]); g.fillOval(rect.X,rect.Y,rect.width,rect. height); } } }; drawingArea.setBackground(Color.white); drawingArea.addMouseListener(new MouseLis- tener); JScrollPane scroller=new JScrollPane(drawing- Area); scroller.setPreferredSize(new Dimension(200, 200)); setLayout(new BorderLayout); add(instructionPanel,BorderLayout.NORTH); add(scroller,BorderLayout.CENTER): } class MyMouseListener extends mouseInputAdapt- er{ final int W=100; final int H=100; public void mouseReleased(MouseEvent e){ boolean changed=false; if(SwingUtilities.isRightMouseButton(e)){ objects.removeAllElements; size.width=0; size.height=0; changed=true; }else{ int X=e.getX-W/z; int Y=e.getY-H/2 if(x<0)x=0; if(y<O)Y=0; Rectangle rect=new Rectangle(X,Y,W,H); objeets.addElement(rect); drawingArea.scrollRectToVisible(rect); int this_width=(x+W+2); if(this width>size.width) {size.width=this_width;changed=true;} int this=height=(y+H+2); if(this_height>size.height) {size.height=this_height;changed=true;} } if(changed){ drawingArea.setPreferredSize(size); drawingArea.revalidateI; } drawingArea.paint; } } public static void main(String args[]){ JFrame. frame=new JFrame("java3"): frame.addWindowListener(new WindowAdapter { public void windowClosing(WindowEvent e) {System.exit(0);} }); frame.setContentPane(new java3); frame.pack; frame.setVisible(true); } }
参考答案