Java repaint()JFrame和JPanel
我尝试在ArrayList和另一个JPanel中添加JPanel。然后重新绘制()JPanel所在的JFrame。经过几个小时的尝试,我开始感到疲劳,难以思考。我更改了很多次程序,可能有一些简单的错误我已经看不见了。(错误也可能在我写的英语中找到) 如果这是不可理解的,我提前道歉 JFrameJava repaint()JFrame和JPanel,java,swing,Java,Swing,我尝试在ArrayList和另一个JPanel中添加JPanel。然后重新绘制()JPanel所在的JFrame。经过几个小时的尝试,我开始感到疲劳,难以思考。我更改了很多次程序,可能有一些简单的错误我已经看不见了。(错误也可能在我写的英语中找到) 如果这是不可理解的,我提前道歉 JFrame import javax.swing.*; import java.awt.*; import java.util.ArrayList; public class JFrameClassen exten
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");
}
}
捕鼠器
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Muslyssnare extends MouseAdapter implements MouseMotionListene{
Bild oneImage;
public Muslyssnare(Bild b){
oneImage = b;
}
public void mouseClicked (MouseEvent e) {
System.out.println("(" + e.getX() + "," + e.getY() + ")");
}
public void mouseDragged (MouseEvent e) {
int x = e.getX();
int y = e.getY();
oneImage.move(x, y);
}
}
您需要在主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);
}
也要遵循程序员的建议并调用重新验证/重新绘制
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
将调整内部面板的大小,以占据所有可用宽度。您可以使用其他布局。
更多信息:
注二:您将面临的下一个问题是图像加载
您面临的确切问题是什么?请致电
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);
}
}