问题描述
我想用NetBeans编写界面画图程序,用户可在文本框中输入参数,点画图按钮后,程序会根据参数在面板上绘制矩形。绘图一般是在自定义的JPanel的派生类中重载paintComponent(Graphicscomp)函数,可按钮和文本框在框架上而不在这个面板上,想请教高手:1怎样将用户输入的参数传给这个函数?2怎样把这个面板的类型改为我定义的派生类名,而不是从组件面板中拖动过来后默认的JPanel类
解决方案
解决方案二:
如果你要自定义JPanel的派生类中重载paintComponent(Graphicscomp)函数,就不可以直接定义paintComponent(Graphicscomp,intx,inty)之类的函数;因为这样就不可以重载了;所以这里我是在JPanel的派生类MyPanel中定义属性intx;inty;intwidth;inthieght;利用属性的get和set的方法来实现参数的传递;具体程序:MyPanel类:importjava.awt.*;importjavax.swing.*;publicclassMyPanelextendsJPanel{privateintx;privateinty;privateintheight;privateintwidth;publicMyPanel(intx,inty,intwidth,intheight){this.x=x;this.y=y;this.width=width;this.height=height;}publicvoidsetheigth(intheigth){this.height=heigth;}publicvoidsetwidth(intwidth){this.width=width;}publicvoidsetx(intx){this.x=x;}publicvoidsety(inty){this.y=y;}publicintgetx(){returnthis.x;}publicintgety(){returnthis.y;}publicintgetheight(){returnheight;}publicintgetwidth(){returnwidth;}@OverrideprotectedvoidpaintComponent(Graphicsg){super.paintComponent(g);g.drawRect(x,y,width,height);//g.drawr}}
解决方案三:
实现窗体:importjava.awt.*;importjavax.swing.*;importjava.awt.event.*;publicclassRectJFrameextendsjavax.swing.JFrame{publicRectJFrame(){initComponents();jp=newMyPanel(0,0,0,0);jPanel1.add(jp);}@SuppressWarnings("unchecked")//<editor-folddefaultstate="collapsed"desc="GeneratedCode">//////////////////因为字数太多啦唯有把设计窗体的函数删了privatevoidinitComponents(){}privatevoidjButton1ActionPerformed(java.awt.event.ActionEventevt){//TODOaddyourhandlingcodehere://repaint();Graphicsg=jPanel1.getGraphics();jp.setx(Integer.parseInt(jTextField1.getText()));jp.sety(Integer.parseInt(jTextField2.getText()));jp.setwidth(Integer.parseInt(jTextField3.getText()));jp.setheigth(Integer.parseInt(jTextField4.getText()));System.out.println(jp.getx()+""+jp.gety()+""+jp.getwidth()+""+jp.getheight());jp.paintComponent(g);}privatevoidjTextField1ActionPerformed(java.awt.event.ActionEventevt){//TODOaddyourhandlingcodehere:}/***@paramargsthecommandlinearguments*/publicstaticvoidmain(Stringargs[]){java.awt.EventQueue.invokeLater(newRunnable(){publicvoidrun(){newRectJFrame().setVisible(true);}});}//Variablesdeclaration-donotmodifyprivatejavax.swing.JButtonjButton1;privatejavax.swing.JLabeljLabel1;privatejavax.swing.JLabeljLabel2;privatejavax.swing.JLabeljLabel3;privatejavax.swing.JLabeljLabel4;privatejavax.swing.JPaneljPanel1;privatejavax.swing.JTextFieldjTextField1;privatejavax.swing.JTextFieldjTextField2;privatejavax.swing.JTextFieldjTextField3;privatejavax.swing.JTextFieldjTextField4;//EndofvariablesdeclarationprivateMyPaneljp;}