저는 최근에 JLabels 매트릭스를 포함하는 JPanel과 관련된 프로젝트를 마쳤으며, 각각 사용자가 원하는대로 활성 / 비활성 상태가되기 위해 자체 MouseListener가 추가되었습니다. 이 프로젝트는 효과가 있었지만 오래된 컴퓨터에서는 프로젝트가 매우 느리다는 불만을 받았고, 제가 한 방식은 쉽지만 끔찍하게 비효율적이라는 것을 알고 있습니다. 다음은 내가 작성한 코드의 단순화 된 버전입니다.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LifeDriver {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setSize(950, 850);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new LifePanel(40, 50));
frame.setVisible(true);
}
}
class LifePanel extends JPanel {
private Cell[][] grid;
private static int nR, nC;
public LifePanel(int row, int column) {
nR = row;
nC = column;
grid = new Cell[row][column];
setLayout(new GridLayout(row, column, 1, 1));
for (int r = 0; r < row; r++)
for (int c = 0; c < column; c++)
{
grid[r][c] = new Cell();
add(grid[r][c]);
}
}
}
class Cell extends JLabel
{
private boolean alive;
private static boolean mouseDown;
public Cell() {
setOpaque(true);
addMouseListener(new Mouse());
kill();
}
public void revive() {
setAlive(true);
}
public void kill() {
setAlive(false);
}
public void setAlive(boolean arg) {
alive = arg;
if (arg)
setBackground(Color.RED);
else
setBackground(Color.WHITE);
}
private class Mouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
mouseDown = true;
if (alive)
kill();
else
revive();
}
public void mouseReleased(MouseEvent e) {
mouseDown = false;
}
public void mouseEntered(MouseEvent e) {
if (mouseDown)
if (alive)
kill();
else
revive();
}
}
}
내가 다시 갈 내가 하나의 MouseListener를 가질 수 있도록이를 변경하려면 LifePanel
, 그리고 사용 getX()
하고 getY()
, (더 이상 JLabel의 확장)를 클릭 된 "셀"을 결정하고 세포 변화를 색상을 가지고, 다음 패널에 자신을 페인트. 다음과 같은 것 :
class LifePanel extends JPanel {
BufferedImage myImage;
Graphics g;
...
class Mouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
grid[someRow][someColumn].draw(g) //use e.getX() and e.getY()
}
public void mouseEntered(MouseEvent e) {
//similar to above
}
}
}
class Cell {
//other methods
public void draw(Graphics g) {
g.setColor(myColor);
g.fillRect(someX, someY, someWidth, someHeight);
}
}
마우스 클릭이 원래 코드와 동일한 결과를 가져 오도록이 두 상황에서 사용할 적절한 값을 어떻게 결정합니까?
2D 배열이 필요하지 않습니다.
대신 개체 ArrayList
를 포함 하는를 사용 Cell
합니다. Cell
객체는 두 가지 속성을 포함 할 수있다 :
그런 다음 패널의 사용자 정의 페인팅 코드는 ArrayList를 반복하고 각 셀을 페인팅합니다.
MouseListener의 경우 마우스 클릭의 Point를 얻고 ArrayList를 반복하고 Rectangle.contains (...) 메서드를 사용하여 Cell에 마우스 포인트가 포함되어 있는지 확인합니다. 적절한 Cell을 찾으면 처리를합니다.
Custom Painting ApproachesDraw On Component
에 있는 예제를 확인하십시오 . 이 접근 방식을 사용하여 그림을 그리는 개념을 보여줍니다. 마우스 처리를 위해 고유 한 코드를 추가해야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다