小编典典
这是一个相对简单的概念(没有冒犯性)。
首先,请勿将代码与JApplet和混合使用JFrame。如果您想在这两种媒介中使用您的应用程序,请将逻辑分成一个单独的
组件(如JPanel),您可以轻松地将其添加到其中。您真的不应该将顶级容器添加到另一个顶级容器(在框架中添加小程序)-太麻烦了。
请避免改写paint顶层容器的方法(如JApplet),而改用自定义组件(如JPanel)并改写它的paintComponent方法。
在您的示例中,您应该打电话super.paint而不是super.paintComponents。paint做重要的工作,您不想跳过
它-但您应该使用JComponent#paintComponent
MouseListener应当添加到您对管理鼠标事件感兴趣的组件中。因为clicked从不添加到任何容器,所以
它将永远不会收到鼠标事件。
Take a look at
public class SimplePaint03 {
public static void main(String[] args) {
new SimplePaint03();
}
public SimplePaint03() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private List grid;
private List fill;
public PaintPane() {
grid = new ArrayList<>(5);
fill = new ArrayList<>(5);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
for (Shape shape : grid) {
if (shape.contains(e.getPoint())) {
if (fill.contains(shape)) {
fill.remove(shape);
} else {
fill.add(shape);
}
}
}
repaint();
}
});
int colWidth = 200 / 50;
int rowHeight = 200 / 50;
for (int row = 0; row < 50; row++) {
for (int col = 0; col < 50; col++) {
grid.add(new Rectangle(colWidth * col, rowHeight * row, colWidth, rowHeight));
}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
for (Shape cell : fill) {
g2d.fill(cell);
}
g2d.setColor(Color.BLACK);
for (Shape cell : grid) {
g2d.draw(cell);
}
}
}
}
Additional
Information from one paint cycle to another is not maintained. You are
required to repaint the component exactly the way you want it to appear. This
means you will need to maintain a list of click points that can be repainted
at any time.
2020-09-18