Currently in this project, I'm able to select the specific grid and change it to a blue background with the SHIFT key being hold.
Right now, I would like to select multiple grids and assign new background color all at once.
How can I do so?
Source code:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.LineBorder;
//based on #trashgod code from http://stackoverflow.com/a/7706684/714968
public class FocusingPanel extends JFrame {
private static final long serialVersionUID = 1L;
private int elements = 10;
private List<GridPanel> list = new ArrayList<GridPanel>();
private final JFrame mainFrame = new JFrame();
private final JPanel fatherPanel = new JPanel();
public FocusingPanel() {
fatherPanel.setLayout(new GridLayout(elements, elements));
for (int i = 0; i < elements * elements; i++) {
int row = i / elements;
int col = i % elements;
GridPanel gb = new GridPanel(row, col);
list.add(gb);
fatherPanel.add(gb);
}
mainFrame.setLayout(new BorderLayout(5, 5));
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.add(fatherPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
}
private GridPanel getGridPanel(int r, int c) {
int index = r * elements + c;
return list.get(index);
}
private class GridPanel extends JPanel {
private int row;
private int col;
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
public GridPanel(int row, int col) {
this.row = row;
this.col = col;
this.setBackground(Color.red);
this.setBorder(new LineBorder(Color.black,1));
this.addMouseListener(new MouseListener() {
//*#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
if(e.isShiftDown()){
setBackground(Color.blue);
}
}
#Override
public void mouseReleased(MouseEvent e) {
//setBackground(Color.green);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
//setBackground(Color.red);
}
});
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FocusingPanel focusingPanel = new FocusingPanel();
}
});
}
}
Related
I have created a checkers game interface using java and placed pieces in each position on the game board but at the moment I am having trouble moving the pieces from one square to another.
How to moving checkers pieces in board game?
Below is source code that I've tried:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chackergame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
/**
*
* #author wenda
*/
public class CheckerGame extends JFrame {
private final int ROWS = 8;
private final int COLL = 8;
private final JPanel[][] square = new JPanel[8][8];
private JPanel backgroundPanel;
private final JLabel statusBar = new JLabel(" Red turn to play");
private JLabel lbPieces = new JLabel();
private boolean inDrag = false;
public CheckerGame() {
//Add a chess board to the Layered Pane
backgroundPanel = new JPanel();
backgroundPanel.setLayout(new GridLayout(8, 8, 0, 0));
add(backgroundPanel, BorderLayout.CENTER);
add(statusBar, BorderLayout.SOUTH);
createSquare();
addPieces();
setIconImage(PiecesIcon.iconGame.getImage());
setTitle("Java Checkers");// set title game
setSize(500, 500);
//setResizable(false);
setLocationRelativeTo(null);
setLocationByPlatform(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void createSquare() {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLL; col++) {
JPanel cell = new JPanel();
if ((row + col) % 2 == 1) {
cell.setBackground(new Color(99, 164, 54));
// cell.setBackground(Color.BLACK);
}
if ((row + col) % 2 == 0) {
cell.setBackground(new Color(247, 235, 164));
// cell.setBackground(Color.WHITE);
}
square[row][col] = cell;
backgroundPanel.add(square[row][col]);
}
}
}
/**
* Add pieces to the board
*/
private void addPieces() {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLL; col++) {
lbPieces = new JLabel();
lbPieces.setHorizontalAlignment(SwingConstants.CENTER);
//lb.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
if ((row + col) % 2 == 1) {
if (row < 3) {
lbPieces.setIcon(PiecesIcon.redPiece);
} else if (row > 4) {
lbPieces.setIcon(PiecesIcon.whitePiece);
}
}
square[row][col].setLayout(new BorderLayout());
square[row][col].add(lbPieces, BorderLayout.CENTER);
} // end of for col loop
} // end of for row loop
} // end of addPieces method
public class MouseInput extends MouseAdapter {
#Override
public void mousePressed(MouseEvent evt) {
}
#Override
public void mouseReleased(MouseEvent evt) {
}
#Override
public void mouseClicked(MouseEvent evt) {
}
#Override
public void mouseDragged(MouseEvent evt) {
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new CheckerGame();
}
}
The basic question is about dragging a component (in this case a JLable) from any source container (a JPanel) to any other one.
Every such container can be a source of the dragged component or a drop-target for it. so it needs to support both. Such JPanel is implemented in the following DragDropPane class.
To write this code I borrowed from MadProgrammer's answer which shows a solution for one source and one target.
It is a one-file mre : the entire code can be copy-pasted to LabelDnD.java file, and run. It demonstrates dragging a JLabel from panel to panel. Please note the comments:
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LabelDnD{
private static final int ROWS = 5, COLS = 5, GAP = 4;
private Component makeContent() {
JPanel content = new JPanel(new GridLayout(ROWS,COLS, GAP,GAP));
content.setBorder(BorderFactory.createLineBorder(content.getBackground(), GAP));
for(int i = 0; i < ROWS*COLS ; i++){
content.add(new DragDropPane(String.valueOf(i)));
}
return content;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("Label Drag & Drop");
f.add(new LabelDnD().makeContent());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.pack();
f.setVisible(true);
});
}
}
class DragDropPane extends JPanel implements DragGestureListener, DragSourceListener {
private static final int W = 50, H = 50;
private JComponent dragable;
public DragDropPane(String text) {
setBackground(Color.white);
setPreferredSize(new Dimension(W, H));
setBorder(BorderFactory.createLineBorder(Color.blue, 1));
var label = new JLabel(text, JLabel.CENTER);
setContent(label);
new MyDropTargetListener(this);
DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
this, DnDConstants.ACTION_COPY, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
public void setContent(JComponent component) {
removeAll();
dragable = component;
add(component);
repaint();
}
//-->DragGestureListener implementation
#Override
public void dragGestureRecognized(DragGestureEvent dge) {
// Create our transferable wrapper
Transferable transferable = new TransferableComponent(dragable);
// Start the "drag" process...
DragSource ds = dge.getDragSource();
ds.startDrag(dge, Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR), transferable, this);
remove(dragable);
revalidate(); repaint();
}
//-->DragSourceListener implementation
#Override
public void dragEnter(DragSourceDragEvent dsde) {}
#Override
public void dragOver(DragSourceDragEvent dsde) {}
#Override
public void dropActionChanged(DragSourceDragEvent dsde) {}
#Override
public void dragExit(DragSourceEvent dse) {}
#Override
public void dragDropEnd(DragSourceDropEvent dsde) {
// If the drop was not successful, we need to
// return the component back to it's previous
// parent
if (!dsde.getDropSuccess()) {
setContent(dragable);
}
}
}
class MyDropTargetListener extends DropTargetAdapter {
private final DragDropPane target;
public MyDropTargetListener(DragDropPane target) {
this.target = target;
new DropTarget(target, DnDConstants.ACTION_COPY, this, true, null);
}
#Override
public void drop(DropTargetDropEvent event) {
try {
var tr = event.getTransferable();
var component = (JComponent) tr.getTransferData(TransferableComponent.component);
if (event.isDataFlavorSupported(TransferableComponent.component)) {
event.acceptDrop(DnDConstants.ACTION_COPY);
target.setContent(component);
event.dropComplete(true);
} else {
event.rejectDrop();
}
} catch (Exception e) {
e.printStackTrace();
event.rejectDrop();
}
}
}
class TransferableComponent implements Transferable {
protected static final DataFlavor component =
new DataFlavor(JComponent.class, "A Component");
protected static final DataFlavor[] supportedFlavors = {
component
};
private final JComponent componentToTransfer;
public TransferableComponent(JComponent componentToTransfer) {
this.componentToTransfer = componentToTransfer;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
return supportedFlavors;
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(component);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (flavor.equals(component)) return componentToTransfer;
else throw new UnsupportedFlavorException(flavor);
}
}
I'm working on a vertical scrolling game, and I'm using a thread to generate new enemies every 2 seconds. Each enemy is an image in a JPanel. For some reason, The generated enemies are not showing up in the JFrame, but they are present. When the player collides with one of the enemies, all the enemies show up.
This is the main class:
package asteroidblaster;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
public class Main extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public Main() {
initUI();
}
private void initUI() {
add(new Board());
setResizable(false);
pack();
setTitle("Alien Blaster");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame ex = new Main();
ex.setVisible(true);
});
}
}
This is the main game logic:
package asteroidblaster;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Board extends JPanel {
private static final long serialVersionUID = 1L;
private final int B_WIDTH = 1500;
private final int B_HEIGHT = 700;
private final int REFRESH_TIME = 150;
private AlienShip alien;
private PlayerShip player;
private ArrayList<AlienShip> enemies = new ArrayList<AlienShip>();
private Timer alienScrollTimer, mainTimer;
public Board() {
initBoard();
}
private void initBoard() {
setBackground(Color.BLACK);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
setPlayer();
initAlienTimer();
gameLoop();
}
private void initAlienTimer() {
alienScrollTimer = new Timer(25, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(AlienShip as : enemies) {
as.scrollShip();
}
repaint();
}
});
alienScrollTimer.start();
}
private void setPlayer() {
player = new PlayerShip();
add(player);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
player.followMouse(e.getX(), e.getY());
//checkCollision();
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
}
});
}
private void checkCollision() {
for(AlienShip as : enemies) {
if(player.getBounds().intersects(as.getBounds()))
player.setVisible(false);
}
}
private Thread alienGenerator() {
for(int i = 0; i < 3; i++) { //these two are being drawn
alien = new AlienShip();
add(alien);
enemies.add(alien);
}
return new Thread(new Runnable() {
#Override
public void run() {
int sleepTime = 2000;
while(true) {
try {
Thread.sleep(sleepTime);
} catch(InterruptedException e) {
System.out.println(e);
}
alien = new AlienShip();
add(alien);
enemies.add(alien);
System.out.println("Enemies: " + enemies.size());
}
}
});
}
private void gameLoop() {
alienGenerator().start();
mainTimer = new Timer(REFRESH_TIME, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
checkCollision();
repaint();
}
});
mainTimer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
This is the AlienShip class:
package asteroidblaster;
import java.util.Random;
import java.awt.*;
import javax.swing.*;
public class AlienShip extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String ALIEN_SHIP_FILE = "images/alienShip.jpg";
private final int PANEL_WIDTH = 224, PANEL_HEIGHT = 250;
private int panelX, panelY;
private Image alienShipImage;
public AlienShip() {
initAlienShip();
}
private void loadImage() {
alienShipImage = Toolkit.getDefaultToolkit().getImage(ALIEN_SHIP_FILE);
}
public int getX() {
return panelX;
}
public int getY() {
return panelY;
}
private void setY(int yCoord) {
panelY = yCoord;
}
private int setX() {
Random r = new Random();
int rand = r.nextInt(14) + 1;
return panelX = rand * 100;
}
private void initAlienShip() {
panelX = setX();
panelY = 0;
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
setBackground(Color.BLUE);
loadImage();
}
#Override
public Rectangle getBounds() {
return new Rectangle(panelX, panelY, PANEL_WIDTH, PANEL_HEIGHT);
}
public void scrollShip() {
setY(getY() + 1);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(alienShipImage, 0, 0, null);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
I have multiple images representing players. Each image is stored in a label, which then is added to a JPanel. Then I simply add that JPanel to JFrame to display all players on the screen.
I have to mouse click on a location on screen and move the current player's label to that location.
I added a MouseListener event to every label, but I can't figure out how to focus on one label at a time, so that for example when I click my mouse on the window, current label moves to that location, and then the focus is set on another label, so that when I click again on screen different label moves.
For example:
// in main GUI
private JLabel activePiece = null;
private Player activePlayer = null;
// in JLabel's MouseListener
public void mousePressed(MouseEvent mEvt) {
JLabel currentPiece = (JLabel) mEvt.getSource();
if (activePlayer.holds(currentPiece)) {
// they've pressed on one of the current Player's pieces
activePiece = currentPiece;
}
}
// in main GUI's MouseListener
public void mousePressed(MouseEvent mEvt) {
if (activePlayer != null && activePiece != null) {
activePiece.setLocation(mEvt.getPoint());
activePlayer = //.... next active player;
revalidate();
repaint();
}
}
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class PlayerMover extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private static final Border ACTIVE_BORDER = BorderFactory.createLineBorder(Color.RED);
private static final Border INACTIVE_BORDER = BorderFactory.createLineBorder(Color.BLUE.brighter());
private Player[] players = { new Player("John"), new Player("Bill"),
new Player("Boudreaux"), new Player("Thibodeaux") };
private int currentPlayerIndex = 0;
private Player currentPlayer = players[currentPlayerIndex];
private JTextField currentPlayerField = new JTextField(currentPlayer.getName(), 20);
private JLabel currentPiece = null;
private Random random = new Random();
public PlayerMover() {
currentPlayerField.setEditable(false);
JPanel northPanel = new JPanel();
northPanel.add(currentPlayerField);
JPanel gamePanel = new JPanel(null) {
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
};
PlayerLabelListener playerLabelListener = new PlayerLabelListener();
for (Player player : players) {
JLabel playerLabel = new JLabel(player.getName(), SwingConstants.CENTER);
int labelW = playerLabel.getPreferredSize().width + 10;
int labelH = playerLabel.getPreferredSize().height + 10;
playerLabel.setSize(new Dimension(labelW, labelH));
playerLabel.setOpaque(true);
playerLabel.setBorder(INACTIVE_BORDER);
int x = random.nextInt(PREF_W - playerLabel.getPreferredSize().width);
int y = random.nextInt(PREF_H - playerLabel.getPreferredSize().height);
playerLabel.setLocation(x, y);
player.setPlayerLabel(playerLabel);
playerLabel.addMouseListener(playerLabelListener);
playerLabel.addMouseMotionListener(playerLabelListener);
gamePanel.add(playerLabel);
}
currentPlayer.getPlayerLabel().setBorder(ACTIVE_BORDER);
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(gamePanel, BorderLayout.CENTER);
}
public void nextPlayer() {
currentPlayerIndex++;
currentPlayerIndex %= players.length;
currentPlayer = players[currentPlayerIndex];
currentPlayerField.setText(currentPlayer.getName());
currentPiece = null;
for (Player player : players) {
player.getPlayerLabel().setBorder(INACTIVE_BORDER);
}
currentPlayer.getPlayerLabel().setBorder(ACTIVE_BORDER);
}
private class PlayerLabelListener extends MouseAdapter {
private Point pressLoc;
#Override
public void mousePressed(MouseEvent evt) {
if (evt.getButton() != MouseEvent.BUTTON1) {
return;
}
JLabel pressedPiece = (JLabel) evt.getSource();
if (currentPlayer.holds(pressedPiece)) {
currentPiece = pressedPiece;
pressLoc = evt.getPoint();
}
}
#Override
public void mouseDragged(MouseEvent mEvt) {
if (currentPiece == null) {
return;
}
dragPiece(mEvt);
}
private void dragPiece(MouseEvent mEvt) {
Container cont = currentPiece.getParent();
int deltaX = mEvt.getLocationOnScreen().x - pressLoc.x - cont.getLocationOnScreen().x;
int deltaY = mEvt.getLocationOnScreen().y - pressLoc.y - cont.getLocationOnScreen().y;
currentPiece.setLocation(deltaX, deltaY);
cont.revalidate();
cont.repaint();
}
#Override
public void mouseReleased(MouseEvent mEvt) {
if (currentPiece == null) {
return;
}
dragPiece(mEvt);
nextPlayer();
}
}
private static void createAndShowGui() {
PlayerMover mainPanel = new PlayerMover();
JFrame frame = new JFrame("PlayerMover");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Player {
private String name;
private JLabel playerLabel;
public Player(String name) {
this.name = name;
}
public boolean holds(JLabel label) {
return label == playerLabel;
}
public String getName() {
return name;
}
public JLabel getPlayerLabel() {
return playerLabel;
}
public void setPlayerLabel(JLabel playerLabel) {
this.playerLabel = playerLabel;
}
}
I have recently started Java and wondered if it was possible to make Animations whilst using GridBag Layout.
Are these possible and how? Any tutorials, help and such would be greatly appreciated :)
In order to perform any kind of animation of this nature, you're going to need some kind of proxy layout manager.
It needs to determine the current position of all the components, the position that the layout manager would like them to have and then move them into position.
The following example demonstrates the basic idea. The animation engine use is VERY basic and does not include features like slow-in and slow-out fundamentals, but uses a linear approach.
public class TestAnimatedLayout {
public static void main(String[] args) {
new TestAnimatedLayout();
}
public TestAnimatedLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestAnimatedLayoutPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestAnimatedLayoutPane extends JPanel {
public TestAnimatedLayoutPane() {
setLayout(new AnimatedLayout(new GridBagLayout()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Value:"), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(new JComboBox(), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridwidth = 2;
add(new JScrollPane(new JTextArea()), gbc);
gbc.gridwidth = 0;
gbc.gridy++;
gbc.gridx++;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
add(new JButton("Click"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class AnimatedLayout implements LayoutManager2 {
private LayoutManager2 proxy;
private Map<Component, Rectangle> mapStart;
private Map<Component, Rectangle> mapTarget;
private Map<Container, Timer> mapTrips;
private Map<Container, Animator> mapAnimators;
public AnimatedLayout(LayoutManager2 proxy) {
this.proxy = proxy;
mapTrips = new WeakHashMap<>(5);
mapAnimators = new WeakHashMap<>(5);
}
#Override
public void addLayoutComponent(String name, Component comp) {
proxy.addLayoutComponent(name, comp);
}
#Override
public void removeLayoutComponent(Component comp) {
proxy.removeLayoutComponent(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
return proxy.preferredLayoutSize(parent);
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return proxy.minimumLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
Timer timer = mapTrips.get(parent);
if (timer == null) {
System.out.println("...create new trip");
timer = new Timer(125, new TripAction(parent));
timer.setRepeats(false);
timer.setCoalesce(false);
mapTrips.put(parent, timer);
}
System.out.println("trip...");
timer.restart();
}
protected void doLayout(Container parent) {
System.out.println("doLayout...");
mapStart = new HashMap<>(parent.getComponentCount());
for (Component comp : parent.getComponents()) {
mapStart.put(comp, (Rectangle) comp.getBounds().clone());
}
proxy.layoutContainer(parent);
LayoutConstraints constraints = new LayoutConstraints();
for (Component comp : parent.getComponents()) {
Rectangle bounds = comp.getBounds();
Rectangle startBounds = mapStart.get(comp);
if (!mapStart.get(comp).equals(bounds)) {
comp.setBounds(startBounds);
constraints.add(comp, startBounds, bounds);
}
}
System.out.println("Items to layout " + constraints.size());
if (constraints.size() > 0) {
Animator animator = mapAnimators.get(parent);
if (animator == null) {
animator = new Animator(parent, constraints);
mapAnimators.put(parent, animator);
} else {
animator.setConstraints(constraints);
}
animator.restart();
} else {
if (mapAnimators.containsKey(parent)) {
Animator animator = mapAnimators.get(parent);
animator.stop();
mapAnimators.remove(parent);
}
}
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
proxy.addLayoutComponent(comp, constraints);
}
#Override
public Dimension maximumLayoutSize(Container target) {
return proxy.maximumLayoutSize(target);
}
#Override
public float getLayoutAlignmentX(Container target) {
return proxy.getLayoutAlignmentX(target);
}
#Override
public float getLayoutAlignmentY(Container target) {
return proxy.getLayoutAlignmentY(target);
}
#Override
public void invalidateLayout(Container target) {
proxy.invalidateLayout(target);
}
protected class TripAction implements ActionListener {
private Container container;
public TripAction(Container container) {
this.container = container;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("...trip");
mapTrips.remove(container);
doLayout(container);
}
}
}
public class LayoutConstraints {
private List<AnimationBounds> animationBounds;
public LayoutConstraints() {
animationBounds = new ArrayList<AnimationBounds>(25);
}
public void add(Component comp, Rectangle startBounds, Rectangle targetBounds) {
add(new AnimationBounds(comp, startBounds, targetBounds));
}
public void add(AnimationBounds bounds) {
animationBounds.add(bounds);
}
public int size() {
return animationBounds.size();
}
public AnimationBounds[] getAnimationBounds() {
return animationBounds.toArray(new AnimationBounds[animationBounds.size()]);
}
}
public class AnimationBounds {
private Component component;
private Rectangle startBounds;
private Rectangle targetBounds;
public AnimationBounds(Component component, Rectangle startBounds, Rectangle targetBounds) {
this.component = component;
this.startBounds = startBounds;
this.targetBounds = targetBounds;
}
public Rectangle getStartBounds() {
return startBounds;
}
public Rectangle getTargetBounds() {
return targetBounds;
}
public Component getComponent() {
return component;
}
public Rectangle getBounds(float progress) {
return calculateProgress(getStartBounds(), getTargetBounds(), progress);
}
}
public static Rectangle calculateProgress(Rectangle startBounds, Rectangle targetBounds, float progress) {
Rectangle bounds = new Rectangle();
if (startBounds != null && targetBounds != null) {
bounds.setLocation(calculateProgress(startBounds.getLocation(), targetBounds.getLocation(), progress));
bounds.setSize(calculateProgress(startBounds.getSize(), targetBounds.getSize(), progress));
}
return bounds;
}
public static Point calculateProgress(Point startPoint, Point targetPoint, float progress) {
Point point = new Point();
if (startPoint != null && targetPoint != null) {
point.x = calculateProgress(startPoint.x, targetPoint.x, progress);
point.y = calculateProgress(startPoint.y, targetPoint.y, progress);
}
return point;
}
public static Dimension calculateProgress(Dimension startSize, Dimension targetSize, float progress) {
Dimension size = new Dimension();
if (startSize != null && targetSize != null) {
size.width = calculateProgress(startSize.width, targetSize.width, progress);
size.height = calculateProgress(startSize.height, targetSize.height, progress);
}
return size;
}
public static int calculateProgress(int startValue, int endValue, float fraction) {
int value = 0;
int distance = endValue - startValue;
value = (int) ((float) distance * fraction);
value += startValue;
return value;
}
public class Animator implements ActionListener {
private Timer timer;
private LayoutConstraints constraints;
private int tick;
private Container parent;
public Animator(Container parent, LayoutConstraints constraints) {
setConstraints(constraints);
timer = new Timer(16, this);
timer.setRepeats(true);
timer.setCoalesce(true);
this.parent = parent;
}
private void setConstraints(LayoutConstraints constraints) {
this.constraints = constraints;
}
public void restart() {
tick = 0;
timer.restart();
}
protected void stop() {
timer.stop();
tick = 0;
}
#Override
public void actionPerformed(ActionEvent e) {
tick += 16;
float progress = (float)tick / (float)1000;
if (progress >= 1f) {
progress = 1f;
timer.stop();
}
for (AnimationBounds ab : constraints.getAnimationBounds()) {
Rectangle bounds = ab.getBounds(progress);
Component comp = ab.getComponent();
comp.setBounds(bounds);
comp.invalidate();
comp.repaint();
}
parent.repaint();
}
}
}
Update
You could also take a look at AurelianRibbon/Sliding-Layout
This is the program which i did long time back when i just started my Java classes.I did simple animations on different tabs on JTabbedPane (change the path of images/sound file as required),hope this helps:
UPDATE:
Sorry about not following concurrency in Swing.
Here is updated answer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ClassTestHello extends JApplet {
private static JPanel j1;
private JLabel jl;
private JPanel j2;
private Timer timer;
private int i = 0;
private int[] a = new int[10];
#Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
start();
paint();
}
});
}
public void paint() {
jl = new JLabel("hiii");
j1.add(jl);
a[0] = 1000;
a[1] = 800;
a[2] = 900;
a[3] = 2000;
a[4] = 500;
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if(i % 2 == 0)
jl.setText("hiii");
else
jl.setText("byee");
i++;
if(i > 4)
i=0;
timer.setDelay(a[i]);
}
};
timer = new Timer(a[i], actionListener);
timer.setInitialDelay(0);
timer.start();
}
#Override
public void start() {
j1 = new JPanel();
j2 = new JPanel();
JTabbedPane jt1 = new JTabbedPane();
ImageIcon ic = new ImageIcon("e:/guitar.gif");
JLabel jLabel3 = new JLabel(ic);
j2.add(jLabel3);
jt1.add("one", j1);
jt1.addTab("hii", j2);
getContentPane().add(jt1);
}
}
I was a problem with drawing rectangle using mouse. I have solve my problem and I get results what I want. But I have a small problem. If I want to start draw rectangle when I click mouse button, text in my button change. This is small difference but I don't want see this. Here is code:
package draw;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
public class Selection extends JPanel
implements ChangeListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int WIDE = 640;
private static final int HIGH = 640;
private List<Node> nodes = new ArrayList<Node>();
private Point mousePt = new Point(WIDE / 2, HIGH / 2);
private Rectangle mouseRect = new Rectangle();
private boolean selecting = false;
public static void main(String[] args) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("GraphPanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Selection gp = new Selection();
gp.add(new JButton("Button"));
f.add(new JScrollPane(gp), BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
Selection() {
this.setPreferredSize(new Dimension(WIDE, HIGH));
this.addMouseListener(new MouseHandler());
this.addMouseMotionListener(new MouseMotionHandler());
}
#Override
public void paintComponent(Graphics g) {
g.setColor(new Color(0x00f0f0f0));
g.fillRect(0, 0, getWidth(), getHeight());
for (Node n : nodes) {
n.draw(g);
}
if (selecting) {
g.setColor(Color.BLACK
);
((Graphics2D) g).setComposite(AlphaComposite.getInstance(rule, alpha));
g.fillRect(mouseRect.x, mouseRect.y,
mouseRect.width, mouseRect.height);
g.drawRect(mouseRect.x, mouseRect.y,
mouseRect.width, mouseRect.height);
}
}
int rule = AlphaComposite.SRC_OVER;
float alpha = 0.9F;
private class MouseHandler extends MouseAdapter {
#Override
public void mouseReleased(MouseEvent e) {
selecting = false;
mouseRect.setBounds(0, 0, 0, 0);
if (e.isPopupTrigger()) {
}
e.getComponent().repaint();
}
#Override
public void mousePressed(MouseEvent e) {
mousePt = e.getPoint();
Node.selectNone(nodes);
selecting = true;
e.getComponent().repaint();
}
}
private class MouseMotionHandler extends MouseMotionAdapter {
Point delta = new Point();
#Override
public void mouseDragged(MouseEvent e) {
if (selecting) {
mouseRect.setBounds(
Math.min(mousePt.x, e.getX()),
Math.min(mousePt.y, e.getY()),
Math.abs(mousePt.x - e.getX()),
Math.abs(mousePt.y - e.getY()));
} else {
delta.setLocation(
e.getX() - mousePt.x,
e.getY() - mousePt.y);
mousePt = e.getPoint();
}
e.getComponent().repaint();
}
}
/** A Node represents a node in a graph. */
private static class Node {
private Color color;
private boolean selected = false;
private Rectangle b = new Rectangle();
/** Draw this node. */
public void draw(Graphics g) {
g.setColor(this.color);
if (selected) {
g.setColor(Color.darkGray);
g.drawRect(b.x, b.y, b.width, b.height);
}
}
/** Mark this node as slected. */
public void setSelected(boolean selected) {
this.selected = selected;
}
/** Select no nodes. */
public static void selectNone(List<Node> list) {
for (Node n : list) {
n.setSelected(false);
}
}
}
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
}
}
I think that can be a problem with place where I implement my button. I use eclipse SDK.
Can you help me?
Change your main to this. The reason is that you are setting alpha to < 1 for the entire panel and so the button is getting lighter shade. Simply move the button out of the panel and you are set.
public static void main(String[] args) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("GraphPanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JButton button = new JButton("Button");
panel.add(button, BorderLayout.PAGE_START);
Selection gp = new Selection();
panel.add(gp, BorderLayout.CENTER);
f.add(new JScrollPane(panel), BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}