java - How to change colors at paint(Graph) -
i have code paint in jpanel, dont know how change colors outside method paint()
i give code:
public void paint(graphics g) { graphics2d g2 = (graphics2d) g; g2.setcolor(color.red); (shape linea : lineas) { // dibuja todos las elipses g2.draw(linea); } }
i know change color @ method using g2.setcolor(color.red);
want change in actionlistener of menuitem.
simply add color
variable in class , use variable set color on graphics
. more appropriate override paintcomponent
rather paint
, calling super
-method recommended.
see example randomly sets color of panel.
import java.awt.borderlayout; import java.awt.color; import java.awt.dimension; import java.awt.graphics; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.util.random; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.swingutilities; public class testcoloredpanel { private static class coloredpanel extends jpanel { private color color = color.red; @override protected void paintcomponent(graphics g) { super.paintcomponent(g); g.setcolor(getcolor()); g.fillrect(0, 0, getwidth(), getheight()); } public color getcolor() { return color; } public void setcolor(color color) { this.color = color; repaint(); } @override public dimension getpreferredsize() { return new dimension(300, 200); } } protected void initui() { final jframe frame = new jframe(testcoloredpanel.class.getsimplename()); frame.setdefaultcloseoperation(jframe.exit_on_close); final coloredpanel panel = new coloredpanel(); frame.add(panel); jbutton button = new jbutton("click me"); button.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { random r = new random(); panel.setcolor(new color(r.nextint(256), r.nextint(256), r.nextint(256))); } }); frame.add(button, borderlayout.south); frame.pack(); frame.setvisible(true); } public static void main(string[] args) { swingutilities.invokelater(new runnable() { @override public void run() { new testcoloredpanel().initui(); } }); } }
Comments
Post a Comment