2013-07-24 2 views
0

JPanel, JFrame 및 그래픽 클래스의 전체 구조를 이해하고 확장 및 재정의하는 데 어려움을 겪고 있습니다. 그래픽 클래스를 추가하고 내 버튼을 추가 할 때까지 내 JPanel/JFrame에 더 이상 표시되지 않을 때까지 모든 것이 작동하는 것처럼 보였습니다. 나는 그것이 overriding 또는 super와 관련이 있다고 알았다? 그러나 나는 정말로 약간의 설명이 필요하다. 정말 고마워!그래픽 클래스가 JFrame/JPanel을 재정의하는 것 같습니다.

나는 쉽게 볼 수 있도록 코드를 좁혔습니다.

import java.awt.Color; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Image; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.border.TitledBorder; 

public class windowBuild extends JFrame { 

    private static final long serialVersionUID = 1L; 
    private JPanel contentPane; 
    private int energy = 4; 
    private JButton btnClaw = new JButton("Claw"); 
    private Image bg; 
    private boolean loaded = false; 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       windowBuild frame = new windowBuild(); 
       frame.setVisible(true); 

      } 
     }); 
    } 

    private class ButtonHandler implements ActionListener { 

     public void actionPerformed(ActionEvent e) { 
      String which = e.getActionCommand(); 
      if (which.equals("Claw")) { 
       energy = energy - 1; 
       System.out 
         .println("Player one's dragon clawed the opponent. Dragon's energy is now at: " 
           + energy); 
      } 

     } 

    } 

    public void loadImage() { 
     bg = new ImageIcon("C:\\res\\dragonDuelBackground.jpeg").getImage(); 
     loaded = true; 
     repaint(); 
    } 

    public windowBuild() { 
     ButtonHandler bh; 
     System.out.println("Starting frame..."); 
     bh = new ButtonHandler(); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 800, 600); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new TitledBorder(null, "Dragon Duel", 
       TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN)); 
     setContentPane(contentPane); 
     contentPane.setLayout(null); 

     btnClaw.setBounds(273, 511, 109, 39); 
     contentPane.add(btnClaw); 
     btnClaw.addActionListener(bh); 

    } 
//******************************************************************** 
// public void paint(Graphics g) { 
//  if (loaded) { 
//   g.drawImage(bg, 400, 400, null); 
//  } 
// } 
//***************Uncomment this and the code won't work anymore********** 
} 

답변

2

의 주석이와 코드는 더 이상

상위 수준 컨테이너 (JFrame의, JDialog를 ...)의() 페인트를 무시하지 마십시오 작동하지 않습니다. 커스텀 페인팅은 JPanel (또는 JComponent)의 paintComponent() 메소드를 오버라이드 (override)함으로써 행해진 다. 그런 다음 프레임에 패널을 추가합니다. super.paintComponent (...)를 호출하는 것을 잊지 마십시오.

자세한 내용 및 예는 Custom Painting 자습서의 스윙 튜토리얼을 참조하십시오.

+0

자습서 아주 좋은를 사용하지 않을 수 있습니다. 감사. – jdawg495

2
  1. JFrame에서 직접 확장하지 마십시오. 프레임에 새로운 기능을 추가하지 않고 프레임을 추가 할 수 없으면 UI의 재사용 가능성을 제한합니다.
  2. 최상위 컨테이너 인 paint을 덮어 쓰지 마십시오. . 좋은 이유가 많이 있지만, 주된 문제는 프레임 컨테이너가 당신이하는 일을 칠할 수있는 여러 가지 레이어 (JLayeredPane, contentPane)입니다.
  3. 페인트 체인이 손상되지 않도록 반드시 super.paintXxx을 호출해야합니다.

대신에 별도의 클래스 (예 : JPanel에서 확장)를 만들고 paintComponent 메서드를 재정의하십시오. 또는 더 나은 여전히. 이미지를 표시하려면 JLabel을 사용하십시오.

자세한 내용은 Performing Custom PaintingPainting in AWT and Swing을 참조하십시오. 이미지가

로드되지 않습니다 그래서 또한

, 나는 또한 당신이 때 할 수있는 Exception을 던질 것이다, A가 ImageIO를 사용 Reading/Loading an Image 읽어 걸릴 것이 좋습니다 것입니다, 당신은 loadImage를 호출하는 경우가 표시되지 않습니다 't은 단순히 자동으로 간단한 예제와 함께 업데이트

실패 후 ImageIcon 훨씬 더 유용합니다 이미지 파일을 읽고

당신은 더 나은 아주 좋은 이유가 PS-

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.border.TitledBorder; 

public class TestGraphics { 

    public static void main(String[] args) { 
     new TestGraphics(); 
    } 

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

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private int energy = 4; 
     private JButton btnClaw = new JButton("Claw"); 
     private BufferedImage bg; 

     public TestPane() { 
      setBackground(Color.WHITE); 
      try { 
       bg = ImageIO.read(new File("dragon.gif")); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 

      ButtonHandler bh; 
      bh = new ButtonHandler(); 
      setBorder(new TitledBorder(null, "Dragon Duel", 
        TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN)); 
      setLayout(new BorderLayout()); 

      JPanel buttonPane = new JPanel(); 
      buttonPane.setOpaque(false); 
      buttonPane.add(btnClaw); 

      add(buttonPane, BorderLayout.SOUTH); 
      btnClaw.addActionListener(bh); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return bg == null ? new Dimension(200, 200) : new Dimension(bg.getWidth(), bg.getHeight()); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      if (bg != null) { 
       Graphics2D g2d = (Graphics2D) g.create(); 
       int x = (getWidth() - bg.getWidth())/2; 
       int y = (getHeight() - bg.getHeight())/2; 
       g2d.drawImage(bg, x, y, this); 
       g2d.dispose(); 
      } 
     } 

     private class ButtonHandler implements ActionListener { 

      public void actionPerformed(ActionEvent e) { 
       String which = e.getActionCommand(); 
       if (which.equals("Claw")) { 
        energy = energy - 1; 
        System.out 
          .println("Player one's dragon clawed the opponent. Dragon's energy is now at: " 
          + energy); 
       } 

      } 
     } 
    } 
} 

(210)는 레이아웃 매니저

+0

감사! 그것은 많은 도움이되었습니다. – jdawg495

+0

코드를 변경하고 나를 보여줄 수 있습니까? 나는 네가하는 말을 이해하지만, 이제 나는 주 수업 시간이나 장소에 넣는 것과 고투하고있다. – jdawg495

관련 문제