2016-06-13 3 views
0

제목에서 알 수 있듯이, 몇 개의 버튼이있는 프로그램을 만들려고합니다. 각 버튼에는 클릭 할 때 그림이 표시됩니다. 그러나 그림이 here 인 그래픽 클래스를 사용하지 않고이 컨테이너를 전역으로 만들지 않고도 가능한지 알고 싶습니다. 그러나 이것을 시도했지만 내 프로그램이 내 패널에 이미지를 추가하지 않는 것 같습니다.이미지를 표시하려면 JButton을 클릭하십시오.

import javax.swing.*; 

import java.awt.*; 
import java.awt.event.*; 

public class PhotoAlbum extends JFrame implements ActionListener{ 

private JPanel imagePanel; 
private JPanel labelPanel; 
public PhotoAlbum(){ 
    super(); 
    Container contentPane = getContentPane(); 
    setSize(1800, 1000); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 

    setTitle("Button Demo"); //Theme here 
    contentPane.setBackground(Color.blue); 
    contentPane.setLayout(new BorderLayout()); 

    createButtons(contentPane); 
    instruction(contentPane); 
    createImageLabel(contentPane); 
} 

public void instruction(Container contentPane){ 
    JPanel instruction = new JPanel(); 
    instruction.setLayout(new FlowLayout()); 
    instruction.setBackground(Color.yellow); 
    Font fontType1 = new Font("Comic Sans MS", Font.BOLD, 40); 
    JLabel instruction1 = new JLabel("Click on the button to view a" 
      + " photo."); 
    instruction1.setForeground(Color.BLUE); 
    instruction1.setFont(fontType1); 
    instruction.add(instruction1); 
    contentPane.add(instruction, BorderLayout.SOUTH); 
} 

public void createButtons(Container contentPane){ 
    labelPanel = new JPanel(); 
    labelPanel.setBackground(Color.pink); 
    labelPanel.setLayout(new GridLayout(9,1)); 

    String[] imageLabel = new String[9]; 
    imageLabel[0] = "Image 1"; 
    imageLabel[1] = "Image 2"; 
    imageLabel[2] = "Image 3"; 
    imageLabel[3] = "Image 4"; 
    imageLabel[4] = "Image 5"; 
    imageLabel[5] = "Image 6"; 
    imageLabel[6] = "Image 7"; 
    imageLabel[7] = "Image 8"; 
    imageLabel[8] = "Exit"; 

    Color[] color = new Color[9]; 
    color[0] = Color.cyan; 
    color[1] = new Color(242, 121, 234); 
    color[2] = Color.red; 
    color[3] = Color.green; 
    color[4] = Color.blue; 
    color[5] = new Color(1, 255, 248); 
    color[6] = Color.magenta; 
    color[7] = new Color(205, 255, 1); 
    color[8] = new Color(205, 255, 1); 

    Font fontType = new Font("Times New Roman", Font.BOLD, 30); 


    JButton[] button = new JButton[9]; 
    for (int i=0; i<button.length; i++) 
    { 
     button[i] = new JButton(imageLabel[i]); 
     button[i].addActionListener(this); 
     button[i].setBackground(color[i]); 
     button[i].setFont(fontType); 
     labelPanel.add(button[i]); 
    } 

    contentPane.add(labelPanel, BorderLayout.WEST); 
} 

public void createImageLabel(Container contentPane){ 
    imagePanel = new JPanel(); 
    imagePanel.setBackground(Color.magenta); 
    contentPane.add(imagePanel, BorderLayout.CENTER); 
} 

public void actionPerformed(ActionEvent event){ 
    String actionCommand = event.getActionCommand(); 
    if(actionCommand.equals("Image 1")) { 
     JLabel addImage = new JLabel(); 
     ImageIcon image = new ImageIcon("picture1.jpg"); 
     addImage.setIcon(image); 
     imagePanel.add(addImage); 
     imagePanel.setBackground(Color.yellow); 
    } 

    else if(actionCommand.equals("Exit")) 
     System.exit(0); 
    else System.out.println("Error in button interface."); 

} 

public static void main(String[] args) 
{ 
    PhotoAlbum buttonGui= new PhotoAlbum(); 
    buttonGui.setVisible(true); 
} 


} 
+2

수행 된 작업에서 레이블을 만들고 추가하는 것보다 (쉬운) 접근 방법은 GUI를 구성 할 때 수행하는 것입니다. 텍스트 나 이미지가없는 라벨은 사용자에게 보이지 않습니다. 버튼을 클릭 할 때 기존 라벨의 아이콘을 설정합니다. –

+1

'new ImageIcon ("picture1.jpg");'애플리케이션 리소스는 배포 시점까지 임베디드 리소스가 될 것이므로 지금 당장 액세스하는 것이 현명하다. [tag : embedded-resource]는 파일이 아닌 URL로 액세스해야합니다. [info. URL을 구성하는 방법은 임베디드 리소스 페이지 (http://stackoverflow.com/tags/embedded-resource/info)를 참조하십시오. –

+0

"GUI가 구성 될 때"라는 말은 코드 시작 부분에 의미합니까? 또한, 버튼을 클릭했을 때 처음에는 이미지가 표시되지 않지만 버튼을 누른 후 창을 최대화/최소화하면 이미지가 표시된다는 사실을 알았을 때 그냥 테스트 해보았습니다. 그게 내 문제와 관련이 있는지 나는 모른다. – blaze077

답변

0

앤드류는 자신의 의견 제안으로 : 여기

는 코드입니다. 아래 코드를 리펙토링하십시오.

if(actionCommand.equals("Image 1")) { 
    JLabel addImage = new JLabel(); 
    URL url = getClass().getResource("picture1.jpg"); 
    if (url != null) { 
     ImageIcon image = new ImageIcon(url); 
     addImage.setIcon(image); 
     imagePanel.add(addImage); 
     imagePanel.setBackground(Color.yellow); 
     this.revalidate(); 
    } 
} 

그리고 Picture1.jpg는 PhotoAlbum.java가있는 곳과 같습니다.

그렇지 않으면 코드가 정상적으로 작동합니다. 큰 이미지가 제대로 표시되지 않더라도.

+0

그것은'{'와'} '사이의'if (actionCommand.equals ("Image 1"))'에 있어야합니다. 그러나 이것을 사용하려고했는데 배경이 노란색으로 바뀌지 만 이미지는 추가되지 않습니다. – blaze077

+0

@ blaze077 중단 점을 넣고 URL이 null이 아닌지 확인할 수 있습니까? 귀하의 코드가 나를 위해 작동하고 이미지를 표시합니다. – Beniton

+0

나는 브레이크 포인트에 익숙하지 않다. 나는 그들을 추가하는 방법을 알고 있지만 URL이 null인지 아닌지 확인하는 방법을 모르겠습니다. – blaze077

관련 문제