在我的程序中,我有以下代码:
package io.github.AdmiralSbs.DiceWars;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Scanner;
public class HexDisplay extends JPanel {
private static final long serialVersionUID = 1L;
public static final int SIZE = 200;
private int height;
private int width;
private Hex[][] hex;
private BufferedImage myImage;
private Graphics drawer;
public HexDisplay(File f) throws IOException {
Scanner key = new Scanner(f);
int[] temp = commaSplit(key.nextLine());
height = temp[0];
width = temp[1];
hex = new Hex[width][height];
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
//temp = commaSplit(key.nextLine());
if (h % 2 == 0)
hex[w][h] = new Hex((int) (SIZE * (w + 0.5)),
(int) (SIZE * (h + 0.5)), SIZE);
else
hex[w][h] = new Hex((int) (SIZE * (w + 1.5)),
(int) (SIZE * (h + 0.5)), SIZE);
System.out.println(hex[w][h].getX() + " " + hex[w][h].getY());
}
}
key.close();
starting();
ImageIO.write(myImage, "jpg", new File("outPic.jpg"));
}
public void starting() {
setPreferredSize(new Dimension(400,400));
setLayout(new FlowLayout());
myImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
drawer = myImage.getGraphics();
drawer.setColor(Color.BLUE);
drawer.fillRect(0, 0, 400, 400);
drawStuff(drawer);
repaint();
}
public int[] commaSplit(String s) {
String[] str = s.split(",");
int[] ret = new int[str.length];
for (int i = 0; i < str.length; i++) {
ret[i] = Integer.parseInt(str[i]);
}
return ret;
}
public void paintComponents(Graphics g) {
g.drawImage(myImage, 0, 0, this);
System.out.println("Painted");
}
public void drawStuff(Graphics g) {
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
hex[w][h].draw(g);
}
}
System.out.println("Drew");
revalidate();
repaint();
paintComponents(g);
}
}
我期望发生的是包含此JPanel的帧显示图像,但事实并非如此。所有System.out.println()方法都按预期调用,我可以将图像保存为.jpg文件。但是,图像不会显示在GUI中。可以做些什么?
答案 0 :(得分:4)
你有一个错字:
paintComponent
应为super.paintComponent(g);
。
并且应该包含对super方法的调用:
<ImageView
android:id="@android:id/empty"
android:layout_width="120sp"
android:layout_height="130sp"
android:layout_gravity="center"
android:gravity="center"
android:src="@drawable/flower" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingTop="120sp"
android:text="Warning" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingTop="200sp"
android:text="Click Me" />
作为方法的第一行