Grid 객체가 인스턴스화되면 JFrame 및 JPanel이 만들어집니다. 사각형은 JPanel에 그려져 사각형 격자를 만듭니다. 이상적으로, 창 크기를 조정하면 그리드의 크기가 조정됩니다.ComponentAdapter를 사용하여 Panel (작동하지 않음)의 크기를 조정하려고 시도
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
public class Grid {
private int lines;
private int space;
public static final int DEFAULT_LINES = 5;
public static final int DEFAULT_SPACE = 5;
private JPanel panel = new GridPanel();
private JFrame frame;
public Grid(String name, int lines, int space) {
this.frame = new JFrame(name);
this.lines = lines;
this.space = space;
this.frame.setSize((lines * space), (lines * space));
}
private class GridPanel extends JPanel {
private int start = 0;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int end = (lines * space);
g.setColor(Color.BLACK);
for (int i = 0; i < lines; i++) {
int crawl = (space * i);
g.drawLine(start, crawl, end, crawl);
g.drawLine(crawl, start, crawl, end);
}
}
}
/*private class GridHandler extends ComponentAdapter {
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
setSpace();
frame.repaint();
frame.revalidate();
}
}*/
public void setSpace() {
space = (frame.getSize().width * frame.getSize().height)/lines;
}
public void run() {
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(panel);
//frame.addComponentListener(new GridHandler());
frame.setVisible(true);
}
}
public class Run {
public static final int ONE_LINES = 15;
public static final int ONE_SPACE = 20;
public static final int TWO_LINES = 35;
public static final int TWO_SPACE = 16;
public static void main(String[] args) {
Grid grid1 = new Grid("Grid One", ONE_LINES, ONE_SPACE);
Grid grid2 = new Grid("Grid Two", TWO_LINES, TWO_SPACE);
grid1.run();
grid2.run();
}
}
이 두 파일 만 사용됩니다. 핸들러는 현재 주석 처리되었으며, 코드는 예상 한대로 처리합니다. 그리드가있는 두 개의 창이 생성됩니다. 그러나 핸들러가 구현되면 그리드가 더 이상 나타나지 않습니다. 핸들러에 대한 올바른 구현은 무엇입니까?
왜 그냥 구성 요소의'width'와'height'를 사용 토록'paintComponent'가 호출 될 때 격자 크기를 계산? [이 예를 들어] (http://stackoverflow.com/questions/34036216/drawing-java-grid-using-swing/34036397#34036397)과 같은 것이 있습니까? – MadProgrammer
조언 해 주셔서 감사합니다. 나는 내 솔루션을 아래에 게시했다. (당신이 제안한대로'width'와'height'를 사용한다.) 나는이 방법으로 더 읽기 쉬운 코드를 찾는다. 다시 한 번 감사드립니다! –