【问题标题】:Import Image in Graphics在图形中导入图像
【发布时间】:2014-03-01 16:16:14
【问题描述】:

我有以下代码,但在加载 JLabel 后,我正在苦苦思索该怎么做。如何显示它并为其提供放置位置的坐标?我在网上尝试了一些解决方案,但它们似乎并没有通过给出诸如“Cant find getCodeBased”之类的错误来工作。有人可以帮忙吗?我还是一个初学者,所以请不要苛刻。

    import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.awt.Image;

public class ChessBoard extends JFrame implements ActionListener
{
    private JButton button;
    private JPanel panel;
    JLayeredPane layeredPane;

    public static void main(String[] args)
    {
        ChessBoard demo = new ChessBoard();
        demo.setSize(900,900);
        demo.createGUI();
        demo.setVisible(true);
    }

    private void createGUI()
    {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container window = getContentPane();
        window.setLayout(new FlowLayout());

        panel = new JPanel();
        panel.setPreferredSize(new Dimension(800,800));
        panel.setBackground(Color.white);
        window.add(panel);

        button = new JButton("start");
        window.add(button);
        button.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
        int xLeft;
        int yTop;
        Graphics paper = panel.getGraphics();
        paper.setColor(Color.black);
        paper.fillRect(0,0,800,800);
        paper.setColor(Color.white);
        xLeft = 0;
        for (int i = 100; i < 800; i += 100)
        {
            paper.drawLine(i,0,i,800);
        } 
        for (int i = 100; i < 800; i += 100)
        {
            paper.drawLine(0, i, 800, i);
        }

        for (int j = 1; j < 9; j++)
        {
            paper.setColor(new Color(238, 221, 187));
            for (int k = 100 * ((j+1) % 2); k < 800; k+=200)
            {
                paper.fillRect (k, (j-1) * 100, 100, 100);
            }
            paper.setColor(new Color(204,136,68));
            for (int i = 100 * (j%2); i < 800; i+=200)
            {
                paper.fillRect(i, (j-1) * 100, 100, 100);
            }
        }
    }

    public void paint(Graphics g)
    {
        JLabel piece = new JLabel( new ImageIcon(getClass().getResource("Rooka8.png")));

    }
}

附:

通过尝试在 ActionPerformed 方法中发布下面的代码以及import java.awt.Image;

,我自己设法解决了这个问题
 ImageIcon myImage = new ImageIcon(...);
            myImage.paintIcon(this, paper, ...,...);

【问题讨论】:

  • public class ChessBoard.. 哦,我remember you。如果您要忽略我和 Marco13 的合理建议,我担心您会花费很长时间来创建损坏的 GUI。祝你好运,我还有其他人可以帮忙。

标签: java image swing import


【解决方案1】:

您可以像按钮和面板一样全局声明 JLabel 变量。然后在 createGUI 中实例化它并将其添加到面板的特定位置以显示它。希望这会有所帮助

【讨论】:

    【解决方案2】:
    • 不要使用 getGraphics,这不是在 Swing 中完成自定义绘制的方式
    • 不要覆盖顶级容器的绘制并始终调用 super.paintXxx 来维护绘制链

    看看Performing Custom Painting2D Graphics

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 2017-08-17
      • 2021-07-28
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2021-05-18
      相关资源
      最近更新 更多