在图形中导入图像

时间:2014-02-05 09:51:39

标签: java image swing import

我有以下代码,在加载JLabel之后,我正在努力做什么。如何显示它并给出它放置位置的坐标?我在网上尝试了一些解决方案,但他们似乎没有通过提供诸如“找不到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")));

    }
}

P.S。

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

来管理自己修复它
 ImageIcon myImage = new ImageIcon(...);
            myImage.paintIcon(this, paper, ...,...);

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

查看Performing Custom Painting2D Graphics