我对在Java中创建单人纸牌游戏的方法提出了一些疑问。
在Swing中处理卡片的最佳方法是什么?我如何拖动它们,将它们捕捉到正确位置的最佳方法是什么?
答案 0 :(得分:1)
将它们捕捉到的最佳方式是什么? 他们的正确职位?
Overlap Layout可能对此有所帮助。
答案 1 :(得分:1)
拖动多张图片的最佳方法是什么?我已经使用Java2D将两个图像绘制到JPanel,但我只能拖动其中一个。我会附上我的源代码。我的解决方案的问题是我需要重新绘制整个窗口,即使我只是在操纵一个元素。是否可以处理卡片的对象,而不是它们的图像?因此,当我移动一张卡片时,我会移动对象的视觉呈现,而不是图像(就像我现在一样。)
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Java2d_MainPanel extends JPanel{
private static BufferedImage img = new logic.GetBufferedImage().getImage();
private JButton knapp = new JButton("Nytt bilde");
private JButton knapp2 = new JButton("Nytt bilde2");
private static BufferedImage img2 = new logic.GetBufferedImage().getImage2();
//coordinates for image 1
private int x1 = 0;
private int y1 = 0;
//coordinates for image 2
private int x2 = 50;
private int y2 = 50;
public Java2d_MainPanel(){
add(knapp);
add(knapp2);
knapp.addActionListener(new ButtonHandler());
knapp2.addActionListener(new ButtonHandler2());
addMouseMotionListener(new MouseMotionHandler());
}
public void newImage(ActionEvent e){
if(e.getSource().equals(knapp)){
img = new logic.GetBufferedImage().getImage();
repaint();
}
else if(e.getSource().equals(knapp2)){
img2 = new logic.GetBufferedImage().getImage2();
repaint();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
newPaint(g2d);
}
public void newPaint(Graphics2D g2d){
g2d.drawImage(img, x1, y1, null);
g2d.drawImage(img2, x2, y2,null);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rabbits");
frame.add(new Java2d_MainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 640);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseDragged(MouseEvent e) {
x1 = e.getX()-(img.getWidth()/2);
y1 = e.getY()-(img.getHeight()/2);
repaint();
}
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
newImage(e);
}
}
class ButtonHandler2 implements ActionListener{
public void actionPerformed(ActionEvent e) {
newImage(e);
}
}
}