import java.awt.Font; import java.awt.Graphics; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; public class SnapBug extends JPanel implements ComponentListener { private static final long serialVersionUID = 1L; private final JFrame frm; // for displaying output in frame private final JTextArea consoleText = new JTextArea(); private int width; private int height; private static final int SIZE = 10;// it is for the grid public SnapBug(JFrame frm) { this.frm = frm; width = frm.getSize().width; height = frm.getSize().height; JTabbedPane tab = new JTabbedPane(); tab.addTab("consoleText", new JScrollPane(this.consoleText)); tab.addTab("paint", this); initializeConsoleText(); addComponentListener(this); frm.add(tab); } private void initializeConsoleText() { consoleText.setEditable(false); consoleText.setFont(new Font("Monospaced", Font.PLAIN, 12)); consoleText.setTabSize(4); } // so that you can see what effect to paint method public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < width; i += SIZE) { g.drawLine(i, 0, i, height); } for (int j = 0; j < height; j += SIZE) { g.drawLine(0, j, width, j); } } public void componentResized(ComponentEvent ce) { width = frm.getSize().width; height = frm.getSize().height; println("width: " + width + "\t height: " + height); } public void componentMoved(ComponentEvent ce) { } public void componentHidden(ComponentEvent ce) { } public void componentShown(ComponentEvent ce) { } public void println(String message) { consoleText.append(message + "\n"); System.out.println(message); consoleText.setCaretPosition(consoleText.getDocument().getLength()); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame obj = new JFrame("SnapBug"); obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int base = 350; double ratio = (Math.pow(5, 0.5) + 1) / 2; obj.setSize((int) (base * ratio), base); obj.setLocationRelativeTo(null); new SnapBug(obj); obj.setVisible(true); } }); } }