Skip to content

Instantly share code, notes, and snippets.

@bcalmac
Last active May 16, 2016 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcalmac/d62b6fdba38a829fe8a702b98ae659ea to your computer and use it in GitHub Desktop.
Save bcalmac/d62b6fdba38a829fe8a702b98ae659ea to your computer and use it in GitHub Desktop.
Minimal Swing application that draws a line
package util.graphics;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
@SuppressWarnings("WeakerAccess")
public class SwingDrawingExample {
public static void main(String[] args) {
draw("Swing Drawing", 800, 600, (g, s) -> {
g.setColor(Color.blue);
g.drawLine(50, 50, s.width - 50, s.height - 50);
});
}
public static void draw(String title, int width, int height, Draw draw) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.add(new JPanel() {
@Override
public void paint(Graphics g) {
draw.draw((Graphics2D) g, getSize());
}
});
frame.setSize(width, height);
frame.setTitle(title);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
public interface Draw {
void draw(Graphics2D graphics2D, Dimension size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment