0
当实例化网格对象时,会创建JFrame和JPanel。在JPanel上绘制线条以创建方形网格。理想情况下,如果窗口调整大小,网格将会缩放。尝试使用ComponentAdapter调整面板大小(不工作)
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();
}
}
这些是唯一使用的两个文件。 Handler目前已被注释掉,并且代码符合预期。两个带网格的窗口被创建。但是,当处理程序执行时,网格不再显示。处理程序的正确实现是什么?
为什么不直接使用该组件的'width'和'height'和计算网格尺寸当过'paintComponent'叫?像[这个例子](http://stackoverflow.com/questions/34036216/drawing-java-grid-using-swing/34036397#34036397)? – MadProgrammer
谢谢你的建议!我已经在下面发布了我的解决方案(它按照您的建议使用'width'和'height'),我发现代码更具可读性。再次感谢! –