Hallo, ich versuche grade Buttons die Plätze tasuche zu lassen, dabei hab ich zwei Probleme:
1. Ich kann zurzeit nur ein Button bewegen
2. Wie kann ich Button nehmen und mit einem anderen button tauschen alos drag and drop mässig
1. Ich kann zurzeit nur ein Button bewegen
2. Wie kann ich Button nehmen und mit einem anderen button tauschen alos drag and drop mässig
Java:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
public class MoveButton extends JFrame {
public JButton[] buttons = new JButton[64];
public JButton a = new JButton ("Random Button");
JLabel dropLabel;
public MoveButton(String title) {
JFrame f = new JFrame(title);
//Fenster erzeugen
f.setSize(1000, 1000);
f.setResizable(false);
f.setLayout(new GridLayout(0, 8));
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setBackground(Color.GRAY);
//Buttons erzeugen
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
f.add(buttons[i]);
int finalI = i;
buttons[i].addActionListener(e -> System.out.println("Button " + (finalI + 1) + " was activated."));
}
//Buttons bewegen
addMouseMotionListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
buttons[35].setLocation(e.getX(), e.getY());
}
});
buttons[35].addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
buttons[35].setLocation(buttons[35].getX() + e.getX(), buttons[35].getY() + e.getY());
}
});
//Random Button auslöser
f.add(a);
a.addActionListener(e -> actionPerformed1(buttons[35]));
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MoveButton("Raster"));
}
public void actionPerformed1(JButton btn)
{
Image image = new ImageIcon(getClass().getResource("punkt.jpg")).getImage();
ImageIcon icon = new ImageIcon(image.getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_FAST ));
buttons[new Random().nextInt(buttons.length)].setIcon(icon);
}
}