repaint()JFrame和JPanel

时间:2016-03-23 08:45:49

标签: java swing

我尝试在ArrayList和另一个JPanel中添加JPanel。然后重新绘制()JPanel所在的JFrame。经过几个小时的尝试,我开始感到疲倦,发现很难思考。我改变了这个程序很多次,可能会有一些我不再看到的简单错误。(错误也可以在我写的英文中找到)。

如果这是不可理解的,我会事先道歉。

的JFrame

RowCount

的JPanel

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class JFrameClassen extends JFrame{

   ArrayList <Bild> somePictures= new <Bild> ArrayList();
   JPanel p;

   public JFrameClassen(){
       super("Window with pictures");

       p = new JPanel();
       p.setBackground(Color.GREEN);
       add(p);
       setBounds(1300, 500, 400, 400);
       setVisible(true);
       setDefaultCloseOperation(EXIT_ON_CLOSE);

   }

   public void addPhoto(String s){

       somePictures.add(new Bild(s));
       p.add(somePictures.get(somePictures.size()-1));

       getContentPane().repaint();

   }

   public void addPhoto(String [] arr){

       for(String s : arr){
       somePictures.add(new Bild(s));
       p.add(somePictures.get(somePictures.size()-1));
    }

    getContentPane().repaint();
}


  public static void main(String[] args) {

    JFrameClassen j = new JFrameClassen();

    String oneArray[] = {"blab.gif", "peli.gif"};

    j.addPhoto(oneArray);
    j.addPhoto("stef.gif");
    j.addPhoto("pear.gif");

   }
  }

MouseAdapter

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class Bild extends JPanel{

   ImageIcon myImage;
   int posX = 50;
   int posY = 50;
   Muslyssnare m = new Muslyssnare(this);

   public Bild(String name){

       myImage= new ImageIcon(name);        
       addMouseListener(m);
       addMouseMotionListener(m);

   }

   public void move(int x, int y){

       posX = x;
       posY = y;
       super.repaint();

   }

   public void paintComponent(Graphics g){
       super.paintComponent(g);

       g.drawImage(myImage.getImage(), posX, posY, this);

   }
}

1 个答案:

答案 0 :(得分:2)

您需要在主JPanel上设置布局。

public JFrameClassen(){
   super("Window with pictures");

   p = new JPanel();
   p.setBackground(Color.GREEN);

   // This will stack your newly created panels.
   p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));

   // This will generate a scroll bar. You may need it 
   JScrollPane pane = new JScrollPane(p);

   add(pane);

   setBounds(1300, 500, 400, 400);
   setVisible(true);
   setDefaultCloseOperation(EXIT_ON_CLOSE);

 }

另请遵循MadProgrammer的建议并调用revalidate / repaint

public void addPhoto(String s){

   somePictures.add(new Bild(s));
   p.add(somePictures.get(somePictures.size()-1));

   getContentPane().revalidate();
   getContentPane().repaint();
}

// Simplify your code. Reuse
public void addPhoto(String [] arr){
   for(String s : arr){
        addPhoto(s);
   }
}

注意:BorderLayout会调整内部面板的大小以占用所有可用宽度。您可以使用其他布局。 更多信息:https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html http://www.oracle.com/technetwork/java/tablelayout-141489.html

注意II:您面临的下一个问题是图像加载。

ImageIcon Loading in Java

How to add an image to a JPanel?