マウスを動かしたときに座標をSwing上に表示するプログラムを作りましたが、下の画像のように数字が重複してうまく表示されません。Swing上には座標値の他に格子状の図形が表示されていますが、これを除いて試してみたところ正しく表示されます。もし解決方法が分かれば教えて下さい。ソースコードは画像の下に記載してあります。
Java
import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; class Panel extends JPanel { final int width = 1000; final int height = 700; int Row = 20;//盤面の最大行 int Column = 25;//盤面の最大列 int square = 16; //マス目の1辺の長さ int mx, my; JLabel label = new JLabel("x =" + mx + ", y =" + my); public Panel() { setPreferredSize(new Dimension(width, height)); addMouseMotionListener(new MouseActionPerformed()); add(label); } class MouseActionPerformed implements MouseMotionListener { public void mouseMoved(MouseEvent e) { mx = e.getX(); my = e.getY(); label.setText("x =" + mx + ", y =" + my); } public void mouseDragged(MouseEvent e) { } } public void paintComponent(Graphics g) { g.setColor(Color.black); //盤面の枠部分の描写 if (Row % 2 == 0) { if (Column % 2 == 1) { for (int i = 0; i <= Row; i++) { g.drawLine(width / 2 - square * Row / 2 - square * 5 / 2 - square * 10, height / 2 - square * (Row - 2 * i) / 2, width / 2 + square * Row / 2 + square * 5 / 2, height / 2 - square * (Row - 2 * i) / 2); } } else { for (int i = 0; i <= Row; i++) { g.drawLine(width / 2 - square * Row / 2 - square * 10, height / 2 - square * (Row - 2 * i) / 2, width / 2 + square * Row / 2, height / 2 - square * (Row - 2 * i) / 2); } } } if (Row % 2 == 1) { for (int i = 0; i <= Row / 2; i++) { g.drawLine(width / 2 - (square / 2 + square * Column / 2) - square * 10, height / 2 - (square / 2 + square * i), width / 2 + (square * Column / 2), height / 2 - (square / 2 + square * i)); g.drawLine(width / 2 - (square / 2 + square * Column / 2) - square * 10, height / 2 + square / 2 + square * i, width / 2 + (square * Column / 2), height / 2 + square / 2 + square * i); } } if (Column % 2 == 0) { for (int i = 0; i <= Column; i++) { g.drawLine(width / 2 - square * (Column - 2 * i) / 2, height / 2 - square * Column / 2 - square * 10, width / 2 - square * (Column - 2 * i) / 2, height / 2 + square * Column / 2); } } if (Column % 2 == 1) { for (int i = 0; i <= Column / 2; i++) { g.drawLine((width / 2 - square / 2) - square * i, height / 2 - (square * 10 + square * Row / 2), (width / 2 - square / 2) - square * i, height / 2 + square * Row / 2); g.drawLine((width / 2 + square / 2) + square * i, height / 2 - (square * 10 + square * Row / 2), (width / 2 + square / 2) + square * i, height / 2 + square * Row / 2); } } } } class Main { public static void main(String[] args) { JFrame f = new JFrame(); f.getContentPane().setLayout(new FlowLayout()); Panel PicrossD = new Panel(); f.getContentPane().add(PicrossD); f.pack(); f.setResizable(false); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }
まだ回答がついていません
会員登録して回答してみよう