Draw something on Swing JComponent |
package javaswingdrawing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; /** * @web http://java-buddy.blogspot.com/ */ public class JavaSwingDrawing extends JComponent { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { createAndShowGUI(); }); } @Override public void paint(Graphics g) { Graphics2D graphics2d = (Graphics2D)g; int w = getWidth(); int h = getHeight(); graphics2d.setColor(Color.red); graphics2d.fillOval(w/4, h/4, w/2, h/2); graphics2d.setColor(Color.blue); graphics2d.fillRect(w/2, h/2, w/4, h/4); } private static void createAndShowGUI() { JFrame myFrame = new JFrame(); myFrame.setTitle("java-buddy.blogspot.com"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(new Dimension(400, 300)); myFrame.setLayout(new BorderLayout()); myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER); myFrame.setVisible(true); } }
Next:
- Implement MouseAdapter for JComponent
- Detect mousePressed and mouseDragged with MouseAdapter
More:
- Display JTable data in line chart using JComponent
No comments:
Post a Comment