Last active
May 16, 2016 13:51
-
-
Save bcalmac/d62b6fdba38a829fe8a702b98ae659ea to your computer and use it in GitHub Desktop.
Minimal Swing application that draws a line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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