Heyho, I am kinda stuck at a part in my code. Or more, two parts. For one, the image 'Kiste' should have an invisible background, but it kind of gets one. I haven't found out yet what I could do to solve this.
The way bigger problem is, that when I press any key, most times nothing happens. Only sometimes it moves out of the frame. Does anyone know?
I never worked with keybindings before and I don't really have the time to learn how to use them.
Thank you!
import java.awt.Color; import java.awt.Font; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTextArea; import java.awt.image.*; import java.io.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyListener; public class gui implements KeyListener{ static JFrame jf = new JFrame(); public static JTextArea ta; static JPanel panel = new JPanel(); static JPanel bPanel = new JPanel(); static int screenbreite = 1250; static int screenhoehe = 1000; static int bildhoehe = 800; static int kposbreite = screenbreite/2-100; static int kposhoehe = bildhoehe/2-100; public static void main(String[] args) throws IOException { jf.setSize(screenbreite, screenhoehe); jf.setLocationRelativeTo(null); jf.setBackground(Color.BLACK); jf.setName("Adventure"); jf.setResizable(false); jf.requestFocus(); panel.setBounds(0, 0, screenbreite, bildhoehe); BufferedImage image = ImageIO.read(new File("...")); JLabel label = new JLabel(new ImageIcon(image)); panel.add(label); jf.add(panel); jf.setLayout(null); ta = new JTextArea(); ta.setText("Beispieltext"); ta.setBounds(0, 800, screenbreite, 200); ta.setBackground(Color.gray); ta.setForeground(Color.black); ta.setEditable(false); ta.setVisible(true); ta.setFont(new Font("Times New Roman",Font.BOLD,30)); ta.setLineWrap(true); jf.add(ta); jf.setVisible(true); kistenBewegen(); } public static void kistenBewegen() throws IOException { bPanel.setBounds(kposbreite, kposhoehe, 200, 200); //bPanel.setOpaque(false); BufferedImage kiste = ImageIO.read(new File("...")); JLabel bLabel = new JLabel(new ImageIcon(kiste)); bPanel.add(bLabel); jf.add(bPanel); jf.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_DOWN) { bPanel.setLocation(bPanel.getX(),bPanel.getY()+50); bPanel.repaint(); } if(e.getKeyCode() == KeyEvent.VK_UP) { bPanel.setLocation(bPanel.getX(),bPanel.getY()-50); bPanel.repaint(); } if(e.getKeyCode() == KeyEvent.VK_LEFT) { bPanel.setLocation(bPanel.getX()-50,bPanel.getY()); bPanel.repaint(); } if(e.getKeyCode() == KeyEvent.VK_RIGHT) { bPanel.setLocation(bPanel.getX()+50,bPanel.getY()); bPanel.repaint(); } } }); } }