如何翻译绘制的对象

时间:2015-08-24 02:53:36

标签: java graphics

我现在正在进行连接4游戏,并且我正在绘制令牌,我需要通过点击向右或向左按钮等事件进行翻译...这是我的代码

public static Graphics myInstance;

public Executer(){
    setTitle("Connect 4");
    setSize(500,700);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    myInstance = this.getGraphics();
}

public void paint (Graphics g){
    //Drawing the grid
    Color black = new Color(0, 0, 0);
    g.setColor(black);
    //g.drawString("Hi", 50, 50);
    g.drawRect(20, 200, 441, 400);
    for (int i=0;i<7;i++)
        g.drawLine(83 + i*63, 200, 83 + i*63, 600);

    for (int i=0;i<5;i++)
        g.drawLine(20 ,267 + i*67, 461 , 267 + i*67);

    //End Drawing the grid

}

public static void main (String[] args){
    Executer e = new Executer();

    //Drawing Red Tokken
    Color red = new Color(255, 0, 0);
    myInstance.setColor(red);
    myInstance.fillOval(29, 150, 50, 50);
}

我不知道用哪个函数来翻译我已经搜索过但我什么也没找到,或者我应该从头开始清除绘图并重新绘制?

1 个答案:

答案 0 :(得分:0)

建议:

  1. 首先,通过在组件上调用getGraphics()来获取您正在执行的Graphics对象。首先,您的代码几乎可以保证为您提供空引用,从而可能导致NullPointerException。但另一方面,即使你成功了,这样获得的Graphics对象也会很短暂,并且随着你的程序运行,可能会失去功能或null。
  2. 相反,您需要在扩展JPanel或JComponent的类的paintComponent方法中绘制。
  3. 在这里,您将使用JVM为您提供的Graphics对象,该对象应该在paintComponent方法的持续时间内保持稳定
  4. 别忘了在你的覆盖范围内调用超级方法来做家务管理。
  5. 您将需要更改实例字段的状态,可能是一个名为diskColor的字段,然后在paintComponent中使用。这将允许外部类能够更改paintComponent中绘制的颜色。
  6. 另一个选择是使用JLabels持有的ImageIcons来保存你的绘图,实际上这就是我选择的,因为你可以创建一个JLabel网格,给他们MouseListeners,从而允许你的游戏玩
  7. 例如使用ImageIcons:

    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.image.BufferedImage;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ConnectGrid extends JPanel {
        public static final int ROWS = 7;
        public static final int COLS = 6;
        public static final int DIAMETER = 80;
    
        // color of blank icon, placeholder for grid position without disk
        private static final Color BLANK_COLOR = new Color(0, 0, 0, 0);
    
        // all colors -- placeholder, red and yellow
        public static final Color[] COLORS = { BLANK_COLOR, Color.RED, Color.YELLOW };
    
        // ImageIcons mapped to color
        private static final Map<Color, Icon> iconMap = new HashMap<>();
        private static final int GAP = 2;
    
        // JLabel grid that holds the colored icons
        private JLabel[][] labelGrid = new JLabel[ROWS][COLS];
        private Color turn = Color.RED; // whose turn is it?
    
        static {
            // create our colored image icons
            int w = DIAMETER;
            int h = DIAMETER;
            int imgType = BufferedImage.TYPE_INT_ARGB;
            for (Color color : COLORS) {
                BufferedImage img = new BufferedImage(w, h, imgType);
                Graphics2D g2 = img.createGraphics();
                // smooth drawing
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
                // draw the color
                g2.setColor(color);
                g2.fillOval(GAP, GAP, w - 2 * GAP, h - 2 * GAP);
                // draw a black border
                g2.setStroke(new BasicStroke(3f));
                g2.setColor(Color.black);
                g2.drawOval(GAP, GAP, w - 2 * GAP, h - 2 * GAP);
                g2.dispose();
                // create ImageIcon and put in iconMap, mapped to color
                iconMap.put(color, new ImageIcon(img));
            }
        }
    
        public ConnectGrid() {
            // JPanel to hold grid of JLabels
            JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS, GAP, GAP));
            // create grid of JLabels, add to gridPanel JPanel
            // fill labels with blank icon, add MouseListener
            for (int row = 0; row < labelGrid.length; row++) {
                for (int col = 0; col < labelGrid[row].length; col++) {
                    // must swap the row numbers since 0th row is on the bottom
                    labelGrid[ROWS - row - 1][col] = new JLabel(
                            iconMap.get(BLANK_COLOR));
                    gridPanel.add(labelGrid[ROWS - row - 1][col]);
                    labelGrid[ROWS - row - 1][col].addMouseListener(new MyMouse(
                            ROWS - row - 1, col));
                }
            }
    
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(new JButton(new ResetAction("Reset")));
    
            setLayout(new BorderLayout());
            add(gridPanel, BorderLayout.CENTER);
            add(buttonPanel, BorderLayout.PAGE_END);
        }
    
        private class MyMouse extends MouseAdapter {
            private int row;
            private int col;
    
            public MyMouse(int row, int col) {
                this.row = row;
                this.col = col;
            }
    
            @Override
            public void mousePressed(MouseEvent e) {
                JLabel label = (JLabel) e.getSource();
                Icon icon = label.getIcon();
                if (icon != iconMap.get(BLANK_COLOR)) {
                    // if label already has a colored icon, ignore mouse press
                    return;
                }
                // if not at bottom row
                if (row != 0
                // and label below has a blank icon
                        && labelGrid[row - 1][col].getIcon() == iconMap
                                .get(BLANK_COLOR)) {
                    // ignore mouse press
                    return;
                }
                // get color for this turn
                icon = iconMap.get(turn);
                // set label's icon
                label.setIcon(icon);
                // toggle the value of turn
                // TODO: check for win here
                turn = (turn == COLORS[1]) ? COLORS[2] : COLORS[1];
            }
        }
    
        private class ResetAction extends AbstractAction {
            public ResetAction(String name) {
                super(name);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                for (JLabel[] labelRow : labelGrid) {
                    for (JLabel label : labelRow) {
                        label.setIcon(iconMap.get(BLANK_COLOR));
                    }
                }
            }
        }
    
        private static void createAndShowGui() {
            ConnectGrid mainPanel = new ConnectGrid();
    
            JFrame frame = new JFrame("ConnectGrid");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    }