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 は、そのパスを使用して、リソース (jar パック ファイルまたはクラス パス上のファイル) への URL を返します。クラスのパッケージに相対的な相対パスを使用できます。


述べる:

コンストラクターの最後で、次のようにします。

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

そのパックがレイアウトを行います。しかし、あなたのコードは大丈夫です。

于 2012-12-15T14:37:46.187 に答える