Java是一種流行的編程語言,廣泛應用于開發各種應用程序。其中,Java的繪圖功能非常強大,可以通過菜單和按鈕控制繪圖,實現各種效果。下面我們來介紹一下如何使用Java用菜單和按鈕控制繪圖。
首先,我們需要創建一個窗口,通過窗口展示我們的繪圖。代碼如下:
import javax.swing.*; import java.awt.*; public class DrawFrame extends JFrame { public DrawFrame() { setTitle("Java繪圖"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setLocationRelativeTo(null); } public static void main(String[] args) { new DrawFrame(); } }
在創建完窗口之后,我們需要在窗口中添加菜單和按鈕,用于控制繪圖。代碼如下:
import javax.swing.*; import java.awt.*; public class DrawFrame extends JFrame { private JMenuBar menuBar; private JMenu fileMenu; private JMenuItem newMenuItem; private JMenuItem quitMenuItem; private JPanel buttonPanel; private JButton drawButton; private JButton clearButton; private DrawPanel drawPanel; public DrawFrame() { setTitle("Java繪圖"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); menuBar = new JMenuBar(); fileMenu = new JMenu("File"); newMenuItem = new JMenuItem("New"); newMenuItem.addActionListener(event ->drawPanel.clear()); quitMenuItem = new JMenuItem("Quit"); quitMenuItem.addActionListener(event ->System.exit(0)); fileMenu.add(newMenuItem); fileMenu.addSeparator(); fileMenu.add(quitMenuItem); menuBar.add(fileMenu); setJMenuBar(menuBar); drawPanel = new DrawPanel(); buttonPanel = new JPanel(); drawButton = new JButton("Draw"); drawButton.addActionListener(event ->drawPanel.draw()); clearButton = new JButton("Clear"); clearButton.addActionListener(event ->drawPanel.clear()); buttonPanel.add(drawButton); buttonPanel.add(clearButton); add(buttonPanel, BorderLayout.NORTH); add(drawPanel, BorderLayout.CENTER); setVisible(true); } public static void main(String[] args) { new DrawFrame(); } }
在菜單和按鈕的代碼中,我們定義了一個DrawPanel類,用于繪圖。它包含draw()方法和clear()方法,分別用于繪圖和清空。下面是DrawPanel的代碼:
import javax.swing.*; import java.awt.*; public class DrawPanel extends JPanel { private static final int WIDTH = 300; private static final int HEIGHT = 200; private boolean isDrawing; private int x1, y1, x2, y2; public DrawPanel() { setPreferredSize(new Dimension(WIDTH, HEIGHT)); setBackground(Color.WHITE); addMouseListener(new MouseHandler()); addMouseMotionListener(new MouseMotionHandler()); } public void draw() { isDrawing = true; repaint(); } public void clear() { isDrawing = false; repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (isDrawing) { g.drawLine(x1, y1, x2, y2); } } private class MouseHandler extends MouseAdapter { @Override public void mousePressed(MouseEvent event) { x1 = event.getX(); y1 = event.getY(); } @Override public void mouseReleased(MouseEvent event) { x2 = event.getX(); y2 = event.getY(); isDrawing = false; repaint(); } } private class MouseMotionHandler extends MouseMotionAdapter { @Override public void mouseDragged(MouseEvent event) { x2 = event.getX(); y2 = event.getY(); isDrawing = true; repaint(); } } }
最后,我們來看看效果。運行程序,點擊Draw按鈕后,可以使用鼠標在繪圖區域內繪制直線。點擊Clear按鈕后,可以清空繪圖區域。