1

我从 c:\book\ 复制了图像文件夹并将其放在 src 文件夹中,但图片没有加载到 Labelp2.add(new JLabel(icon2));或 Button 上JButton j2=new JButton(icon2);。一切都在解决接受图片。我是初学者,我不知道有什么问题!

import javax.swing.*;
import javax.swing.ImageIcon;

import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

import java.awt.*;
public class TestBorderLayout extends JFrame{

private ImageIcon icon = new ImageIcon("image/ca.gif");
private ImageIcon icon2 = new ImageIcon("image.card/1.png");
public TestBorderLayout(){


 Border lineBorder = new LineBorder(Color.BLACK, 2);    

JButton j1=new JButton("Test1");
 j1.setBackground(new Color(200,0,0));
 j1.setForeground(Color.CYAN);

 JButton j2=new JButton(icon2);

 JButton j3=new JButton("Test3");
 j3.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 12));


JPanel p1=new JPanel();
p1.setBorder(new TitledBorder("One Button"));
p1.add(j1);
p1.add(new TextField("250000000"));
JPanel p2=new JPanel();
p2.add(new JLabel(icon2));


p2.setBorder(new TitledBorder("Two Buttons"));
p2.add(j2);

p2.add(j3);

add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.NORTH);


}

public static void main(String[] args){

    TestBorderLayout frame=new TestBorderLayout();
    frame.setTitle("Border");
    frame.setSize(200,300);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}

}
4

1 回答 1

2

反而

new ImageIcon("image/ca.gif");

new ImageIcon(getClass().getResource("/image/ca.gif"));

此 getResource 使用该路径返回资源的 URL(在 jar 打包文件中,或类路径上的文件中)。您可以使用相对路径,相对于类的包。


评论:

在构造函数结束时,我会这样做:

setTitle("Border");
setSize(200,300);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();

该包进行布局。但是你的代码没问题。

于 2012-12-15T14:37:46.187 回答