2012-11-02 2 views
1

내 마지막 게시물 Java Button Width에서 다음 이미지를 추가하고 배경색을 설정하려고합니다. Ive는 내가 할 때마다 몇 가지 시도를했습니다. 그것은 항상 저에게 오류를줍니다.스윙 - GUI에 이미지 추가

내가

setBackground(args); 

img = addImage("image.png"); 

그들은 나를 위해 일을 해달라고을 시도했습니다. 누군가 제게 손을 좀주세요.

좋아, 나는 Disha가 만든 게시물을 시도했다. 그리고 애플릿은 아직도 당신이 찾고있는

http://pastebin.com/iijj7fSr

답변

4

, Java Naming Conventions 학습 할 그들에 충실하십시오 의미 .

JPanel을 추가 했으므로 JFrame에 배경색을 제공하려면

interfaceFrame.setBackground(Color.black); 

지금 true로 JPanel의 불투명 속성을 설정해야하고 같은과 같은 하나 개의 배경 색상 설정 : 따라서 당신은 서면으로 하나 개의 배경 색상을 얻을 수없는 내부

setOpaque(true); 
setBackground(Color.BLUE); 

당신의 MenuPane 클래스의 생성자입니다.여기 여기

은 수정 된 코드입니다 :

이제
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Gmine { 
     JFrame interfaceFrame; 
     JButton singleplayerButton, multiplayerButton, optionsButton, quitButton; 


     public Gmine() { 
      EventQueue.invokeLater(new Runnable() { 
       @Override 
       public void run() { 
        try { 
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
        } catch (ClassNotFoundException ex) { 
        } catch (InstantiationException ex) { 
        } catch (IllegalAccessException ex) { 
        } catch (UnsupportedLookAndFeelException ex) { 
        } 

        interfaceFrame = new JFrame("G-Mine"); 
        interfaceFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        interfaceFrame.setLayout(new BorderLayout()); 
        interfaceFrame.setSize(800,500); 
        //interfaceFrame.setBackground(Color.black); 
        interfaceFrame.add(new MenuPane()); 
        interfaceFrame.setLocationRelativeTo(null); 
        interfaceFrame.setVisible(true); 
       } 
      }); 
     } 

     public class MenuPane extends JPanel { 

      public MenuPane() { 
       setLayout(new GridBagLayout()); 

       setOpaque(true); 
       setBackground(Color.BLUE); 

       singleplayerButton = new JButton("SinglePLayer"); 
       multiplayerButton = new JButton("MultiPlayer"); 
       optionsButton = new JButton("Options"); 
       quitButton = new JButton("Quit"); 

       GridBagConstraints gbc = new GridBagConstraints(); 
       gbc.gridx = 0; 
       gbc.gridy = 0; 
       gbc.fill = GridBagConstraints.HORIZONTAL; 
       gbc.ipadx = 20; 
       gbc.ipady = 20; 

       add(singleplayerButton, gbc); 
       gbc.gridy++; 
       add(multiplayerButton, gbc); 
       gbc.gridy++; 
       add(optionsButton, gbc); 
       gbc.gridy++; 
       add(quitButton, gbc); 
      } 
     } 
     public static void main(String[] args) { 
      new Gmine(); 
     } 
} 

당신이 어떻게 add images to your Project in Java이 답을 볼 수 있습니다 당신이이 작은 샘플 코드에서 도움을받을 수 있습니다 프로젝트에 이미지를 추가하기 위해 어떤 다음과 같다 :

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.net.URL; 
import javax.imageio.ImageIO; 
import javax.swing.*; 

public class PaintingExample 
{ 
    private CustomPanel contentPane; 
    private JTextField userField; 
    private JPasswordField passField; 
    private JButton loginButton; 

    private void displayGUI() 
    { 
     JFrame frame = new JFrame("Painting Example"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     contentPane = new CustomPanel();   

     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new PaintingExample().displayGUI(); 
      } 
     }); 
    } 
} 

class CustomPanel extends JPanel 
{ 
    private BufferedImage image; 

    public CustomPanel() 
    { 
     setOpaque(true); 
     setBorder(BorderFactory.createLineBorder(Color.BLACK, 5)); 
     try 
     { 
      /* 
      * Since Images are Application Resources, 
      * it's always best to access them in the 
      * form of a URL, instead of File, as you are doing. 
      * Uncomment this below line and watch this answer 
      * of mine, as to HOW TO ADD IMAGES TO THE PROJECT 
      * https://stackoverflow.com/a/9866659/1057230 
      * In order to access images with getClass().getResource(path) 
      * here your Directory structure has to be like this 
      *     Project 
      *     | 
      *   ------------------------ 
      *   |      | 
      *  bin     src 
      *   |      | 
      *  ---------    .java files    
      *  |  |     
      * package image(folder) 
      * (or    | 
      * .class  404error.jpg 
      * files, if 
      * no package 
      * exists.) 
      */ 
      //image = ImageIO.read(
      //  getClass().getResource(
      //    "/image/404error.jpg")); 
      image = ImageIO.read(new URL(
         "http://gagandeepbali.uk.to/" + 
           "gaganisonline/images/404error.jpg")); 
     } 
     catch(IOException ioe) 
     { 
      System.out.println("Unable to fetch image."); 
      ioe.printStackTrace(); 
     } 
    } 

    /* 
    * Make this one customary habbit, 
    * of overriding this method, when 
    * you extends a JPanel/JComponent, 
    * to define it's Preferred Size. 
    * Now in this case we want it to be 
    * as big as the Image itself. 
    */ 
    @Override 
    public Dimension getPreferredSize() 
    { 
     return (new Dimension(image.getWidth(), image.getHeight())); 
    } 

    /* 
    * This is where the actual Painting 
    * Code for the JPanel/JComponent 
    * goes. Here we will draw the image. 
    * Here the first line super.paintComponent(...), 
    * means we want the JPanel to be drawn the usual 
    * Java way first, then later on we will 
    * add our image to it, by writing the other line, 
    * g.drawImage(...). 
    */ 
    @Override 
    protected void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     g.drawImage(image, 0, 0, this); 
    } 
} 

는 아래에 주어진 주석 라인을 수행하고 지정된 위치에 이미지를 추가

image = ImageIO.read(
     getClass().getResource(
       "/image/404error.jpg")); 

의심되는 부분이 있으면 질문을 던지십시오. 내 경계에 있다면 정보를 제공해 드리겠습니다.

1

, 검은 색이 아닌 같은 색상이 솔루션 유지 :

  1. 에 아이콘을 추가 com.icon

  2. 처럼라는 패키지를 만듭니다 해당 패키지 (복사/붙여 넣기)

  3. 버튼에 아이콘을 추가합니다 :

    button.setIcon(new ImageIcon(NameOfClass.class.getResource("/com/icon/nameOfIcon.png"))); 
    

P.S. 그들이 .png 형식인지 확인하십시오.