Skip to content

Instantly share code, notes, and snippets.

@avshabanov
Created August 8, 2022 02:44
Show Gist options
  • Save avshabanov/54eb907ff5830a662373e1eccf2d953f to your computer and use it in GitHub Desktop.
Save avshabanov/54eb907ff5830a662373e1eccf2d953f to your computer and use it in GitHub Desktop.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
private static void createFrameAndDraw(Consumer<Graphics2D> g2dCallback) {
final JFrame frame = new JFrame("Demo Paint");
frame.setBounds(0, 0, 640, 480);
frame.setLayout(null);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
// close frame handler
final Runnable closeCallback = frame::dispose;
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeCallback.run();
}
});
// Panel added
final JPanel pane = new JPanel();
pane.setBounds(0, 0, 640, 480);
pane.setLayout(null);
frame.add(pane);
// this Canvas added
final Canvas canvas = new Canvas();
canvas.setBounds(pane.getBounds());
pane.add(canvas);
//canvas.setIgnoreRepaint(true); // active painting only on canvas, does this apply to swing?
canvas.requestFocus(); // get focus for keys
// double buffering to avoid flickering
canvas.createBufferStrategy(2);
BufferStrategy bufferStrategy = canvas.getBufferStrategy();
for (int i = 0; i < 1; ++i) {
final Graphics2D g2d = (Graphics2D) bufferStrategy.getDrawGraphics();
// Wipe with black color
g2d.setColor(Color.gray);
g2d.fillRect(0, 0, 640, 480);
g2d.setColor(Color.blue);
g2d.drawString("Draw Something", 10, 10);
g2dCallback.accept(g2d);
// finally, we've completed drawing so clear up the graphics
// and flip the buffer over
g2d.dispose();
bufferStrategy.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment