java - JPanel How to create an instance/object -
i keep mixing jframe , jpanel. have code compiles nothings happens , program ends.
this homework assignment requires draw triangle. add button, when button pressed triangle flip upside down. press again return first location.
any assistance great. countless rough draft , i'm trying initiate object view.
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.awt.geom.line2d; import java.awt.color; public class triangle extends jpanel implements actionlistener { jbutton button = new jbutton("just flip it"); public triangle() { add(button); button.addactionlistener(this); } public void actionperformed(actionevent e) { } @override public void paintcomponent(graphics g) { super.paintcomponent(g); g.drawline(125,75,100,200); g.drawline(125,75,150,200); g.drawline(100,200,150,200); } public static void main(string[] args) { triangle frame = new triangle(); frame.setsize(400, 400); frame.setvisible(true); } }
think of jpanel
piece of paper , jframe
book.
if never add piece of paper book, never shown.
so, here steps program running:
- create
jframe
holdjpanel
(triangle) inside it - add logic in
actionlistener
have boolean flag, changedtrue
orfalse
depending on current state , based on repaint pane - have logic inside
paintcomponent(...)
method draws triangle upside down or upside based on state of boolean flag above
so, above in main(...)
method should have
jframe frame = new jframe("my frame"); //initialize triangle here frame.add(triangle); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.pack(); frame.setvisible(true);
your actionperformed()
method should this:
public void actionperformed(actionevent e) { clicked = !clicked; repaint(); }
and paintcomponent()
:
super.paintcomponent(); if (clicked) { //draw upside } else { //draw upside down }
as we're using pack()
instead of setsize(...)
method, should override getpreferredsize()
method of our jpanel
well:
@override public dimension getpreferredsize() { return new dimension(400, 400); }
otherwise small jframe
(and it's practice way)
also don't forget place program on edt (as show in point #2 of answer)
as side note, might want move use shape's api recommended @madprogrammer in this answer
both links above have cool examples , tips, check them out!
Comments
Post a Comment