Draw a line in a JPanel with button click in Java

前端 未结 3 1049
孤城傲影
孤城傲影 2020-11-22 02:07

I want to draw a line in a JPanel. This is my GUI and I want a line in the JPanel in white.

\"enter

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 02:18

    There is a simple answer for triggering graphics: e.g. The following code can be placed inside a click event and used for drawing a few simple objects on a jPanel. jPanel1 in this case was situated on one side of a tabbed jPanel7 and next to the triggering button. To do this in netbeans GUI, the code was placed inside the button action event. Once the usual errors appeared for not having the proper imports, right click on the code and click on "fix imports". Bingo, all is well :-) Warning: the setBackground command for the panel will override the graphics object. If you set the background color without using the graphics object, you will not see your objects!

    Graphics g = jPanel1.getGraphics();  
    g.setColor(Color.blue);
        g.drawLine( 0, 50,  20, 50);
        g.setColor(Color.white); 
        g.fillRect(40, 50,  20, 20); 
        g.setColor(Color.blue); 
        g.drawRect(40, 50,  20, 20); 
        g.drawOval(80, 50,  20, 20); 
        g.setColor(Color.green); 
        g.fillOval(80, 50,  18, 18);   
    

    This restores your faith in true love :-) The difficulty here is that any change or repaint will erase your effort. This approach is specifically discouraged by the Java founders. But in the current rendition of Netbeans Swing, where extending the jPanel is made difficult by locking code changes, this approach could be your only short term solution. A simple persistent graphic extension for the jPanel would be a most welcome addition to the current Netbeans Swing environment, a graphics panel. This would allow you to drag and drop the graphics panel and then get on with the event driven use of that panel. 40 other IDE's already have this, it seems Java has been slow to add this feature.

提交回复
热议问题