I have a short script made in swing, people keep telling me that I need to use Key bindings to get the Jlabel to move but I can't figure out how to do it. anyone have any idea on how to implement Key bindings in a way it works that does not use a Key Listener or that will be a problem if I add a button?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;
public class Screen extends JFrame {
private JPanel contentPane;
int x,y;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen frame = new Screen();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Screen() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, "p1");
panel.setLayout(null);
JButton btnPlay = new JButton("Play");
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CardLayout c =(CardLayout)(contentPane.getLayout());
c.show(contentPane, "p2");
}
});
btnPlay.setBounds(185, 164, 53, 23);
panel.add(btnPlay);
JLabel lblGame = new JLabel("Game");
lblGame.setHorizontalAlignment(SwingConstants.CENTER);
lblGame.setBounds(189, 28, 46, 14);
panel.add(lblGame);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, "p2");
panel_1.setLayout(null);
JLabel player = new JLabel("P");
player.setHorizontalAlignment(SwingConstants.CENTER);
player.setFont(new Font("Tahoma", Font.BOLD, 27));
player.setForeground(Color.BLACK);
player.setBackground(Color.BLACK);
player.setBounds(x, y, 51, 40);
panel_1.add(player);
}
}
As with most things, start having a look at the tutorials, How to Use Key Bindings, as pretty much any answer is simply going to be based on these
You could do something as simple as this...
Disclaimer...
As I have, repeatedly, told either you or your fellow class mates, you shouldn't be using components this way. Instead, you should be following a custom painting route, which will provide you with greater flexibility and far less issues in the long run.
You should also be making appropriate use layout managers. These will safe you a lot of hair and time.
See Laying Out Components Within a Container for more details