Basically, I have a JFrame
& in this frame there is a JPanel
. On top of panel there are four JLabel
components, lets call them colorLabels
, and on the bottom of panel I have one label (let's call it playerLabel
). I want to implements next thing.
Top colorLabels
need to change their color from time to time (less then second) and they need to, let's say, shoot projectiles on bottom. On bottom playerLabel
need to be move around x-axis so it can block shots.
My problem is that, when I activate SwingWorker
or any thread on colorLabels
so they can shoot projectiles and change color overtime my EDT get blocked so I can not move playLabel
(event doesn't work). I mean they work but at the same time, playerLabel
get back to original position. (EDT blocked)
My question is, how can I split actions on colorLabel
(top labels) from action on playerLabel
(bottom label)?
How to make colorLabels
do their job and to be able to move playerLabel
? Basically, How to unblock EDT and still have or actions going.
EDIT:
static Point click;
static int thisX;
static int xMoved;
static int x;
static Integer elapsed = 0;
public static void main(String[] args) {
JFrame frame = new JFrame();
SpringLayout sp = new SpringLayout();
frame.setLayout(sp);
JLabel label = new JLabel("This is label");
label.setBorder(BorderFactory.createLineBorder(Color.red));
JLabel timeLabel = new JLabel("Time: ");
frame.add(label);
sp.putConstraint(SpringLayout.NORTH, label, 10, SpringLayout.NORTH, frame);
sp.putConstraint(SpringLayout.WEST, label, 10, SpringLayout.WEST, frame);
frame.add(timeLabel);
sp.putConstraint(SpringLayout.NORTH, timeLabel, 100, SpringLayout.NORTH, frame);
sp.putConstraint(SpringLayout.WEST, timeLabel, 100, SpringLayout.WEST, frame);
frame.setSize(600, 400);
frame.setVisible(true);
Timer t = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
elapsed++;
timeLabel.setText("Time: " + elapsed);
}
});
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
click = e.getPoint();
}
});
label.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
thisX = label.getLocation().x;
xMoved = (thisX + e.getX()) - (thisX + click.x);
x = thisX + xMoved;
label.setLocation(x, label.getLocation().y);
label.repaint();
}
});
t.start();
}