我目前正在尝试创建一个 Java GUI 程序,该程序根据终端中给出的参数生成图像。例如,如果我在命令行 java Draw Image1
中获得参数,我想为其他人绘制我的图像 1 等。如何获取命令参数并在 paintComponent
中使用它?以下是我尝试执行的示例:
import javax.swing.*;
import java.awt.*;
public class Draw extends JPanel
{
public Draw()
{
this.setSize(800,800);
JPanel drawing = new JPanel();
this.add(drawing);
this.setVisible(true);
}
protected void paintComponent(Graphics g)
{
if (args[0].equals("Image1")) // won't work
{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("image/myimage.jpg");
g.drawImage(myImage, 0, 0, this);
}
else
{
// draw image 2
}
}
public static void main(String[] args)
{
// create new Jframe
JFrame frame = new JFrame("Draw");
frame.add(new Draw());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
最佳答案
更改此:
frame.add(new Draw());
对此:
frame.add(new Draw(args));
然后让您的构造函数接受一个字符串数组参数并使用它来设置类字段。
public class Draw extends JPanel
{
private String[] params
public Draw(String params)
{
this.params = params;
this.setSize(800,800); // this generally should be avoided
JPanel drawing = new JPanel();
this.add(drawing);
this.setVisible(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g); // this should be out of the if block
if (params != null && params.length > 0 && params[0].equals("Image1")) {
// ..... etc
编辑:安德鲁是对的,我没有仔细阅读你的代码。在构造函数中读取图像并在 PaintCompnent 方法中的图像中使用它
例如,
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
@SuppressWarnings("serial")
public class Draw extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = PREF_W;
private BufferedImage image;
public Draw(String[] params) throws IOException {
if (params != null && params.length > 0) {
image = ImageIO.read(new File(params[0]));
}
// this.setSize(800,800);
JPanel drawing = new JPanel();
drawing.setOpaque(false); // may need this
this.add(drawing);
this.setVisible(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, null);
} else {
}
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
// not sure if you want to size it to the image or not
if (image != null) {
int w = image.getWidth();
int h = image.getHeight();
return new Dimension(w, h);
} else {
return new Dimension(PREF_W, PREF_H);
}
}
public static void main(String[] args) {
// create new Jframe
JFrame frame = new JFrame("Draw");
try {
frame.add(new Draw(args));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setSize(500,500);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
关于java - 如何在paintComponent方法中使用命令参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26959864/