I’ve been searching for a way to draw a black-and-white array on screen. It’s a simple array, just 20×20. What I plan to do is to draw on an array with the mouse so that each pixel “toggles” from black to white and back when clicked, then pass the array as a set of booleans (or integers) to another function. Currently I’m using Swing. I do remember to have used Swing for drawing on a canvas, but I still can’t find the actual usage. Should I use a canvas, or instead rely on JToggleButtons?
Share
You can simply use a
JFrame(or other Swing component) and override thepaint(Graphics)method to draw a representation of the boolean matrix (note that in the case of a lightweight component such asJPanelyou should overridepaintComponent(Graphics). This will give you the click-and-drag capability you require (which is very difficult to achieve using a grid of individual Swing components).As other people have commented, AWT
Canvasdoesn’t give you anything not provided by Swing components and you’ll see in the example below that I’ve used thecreateBufferStrategymethod also present onJFrameto ensure a non-flicker display.Note that my example is fairly simple in that it toggles every pixel you drag across rather than the click operation establishing whether you’re in “paint” mode or “erase” mode and then exclusively applying black or white pixels for the duration of the drag.