Ok, so I am making a monopoly game. I so far have a JFrame, with a JPanel acting as a board. I have loaded all necessary images. I create a Player object which extends JLabel, to represent the player on the board.
I am trying to set the location of (in hopes of moving pieces around the board) Player object (which is a JLabel), on the board (which is a JPanel). I tried the .setLocation method, .setBounds method.
For some reason, no matter what i do the Player object only shows up on the top middle of the JPanel. I was wondering how I could move the Player object on my board.
JFrame code (I attempt to move the JLabel in the bottom of the constructor):
package com.Game.Monopoly;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.miginfocom.swing.MigLayout;
//a class that represent the board (JFrame) and all of it components
public class GameFrame extends JFrame {
private final double SCALE;
// all the graphical components
private Board board;
private JLabel lblPlayerMoney;
private JLabel lblCurrentPlayer;
private JLabel lblDice1;
private JLabel lblDice2;
private JList lstPropertiesList;
private JButton btnEndTurn;
private JButton btnBuyProperty;
private JButton btnRollDice;
// all images needed
private ImageIcon imgDice1;
private ImageIcon imgDice2;
private ImageIcon imgDice3;
private ImageIcon imgDice4;
private ImageIcon imgDice5;
private ImageIcon imgDice6;
private ImageIcon icnAirplane;
// all players
private Player[] playerList;
// all properties
private Property[] propertiesList;
public GameFrame(double scale) {
// SCALE = scale;
SCALE = 1;
// set up the JFrame
setResizable(true);
setTitle("Monopoly");
// etUndecorated(true);
// set size to a scale of 1080p
setSize((int) (1920 * SCALE), (int) (1080 * SCALE));
setLayout(new MigLayout());
loadImages();
// add the components to the frame
board = new Board(SCALE);
board.setPreferredSize(new Dimension((int) (1024 * SCALE),
(int) (1024 * SCALE)));
board.setBackground(Color.BLACK);
add(board, "east, gapbefore 80");
lblCurrentPlayer = new JLabel("Current Player:" + " Player 1");
add(lblCurrentPlayer, "wrap");
lblPlayerMoney = new JLabel("Player1's money:" + "$14000000");
add(lblPlayerMoney, "wrap");
lstPropertiesList = new JList();
add(new JScrollPane(lstPropertiesList),
"span 2 2, grow, height 70:120:200");
btnRollDice = new JButton("Roll Dice");
add(btnRollDice, "wrap");
lblDice1 = new JLabel(imgDice1);
add(lblDice1);
lblDice2 = new JLabel(imgDice1);
add(lblDice2, "wrap");
btnBuyProperty = new JButton("Buy Property");
add(btnBuyProperty, "wrap, top");
btnEndTurn = new JButton("End Turn");
add(btnEndTurn, "aligny bottom");
setUpEventListeners();
loadProperties();
// load players
playerList = new Player[6];
playerList[0] = new Player("Player 1", icnAirplane);
// add Players to the board
board.add(playerList[0]);
playerList[0].setLocation(new Point(500, 230));
}
public static void main(String[] args) {
GameFrame board = new GameFrame(1);
board.setVisible(true);
}
// method to add event listeners
public void setUpEventListeners() {
// roll dice
btnRollDice.addActionListener(new ActionListener() {
// creates an object with an timers to help with rolling dice
class RollDice implements ActionListener {
private Timer time = new Timer(152, this);
private int count = 0;
public void actionPerformed(ActionEvent e) {
count++;
if (count == 21)
time.stop();
int whatDice1 = (int) (Math.random() * 6) + 1;
int whatDice2 = (int) (Math.random() * 6) + 1;
// set the icons of the labels according to the random
// number
if (whatDice1 == 1)
lblDice1.setIcon(imgDice1);
else if (whatDice1 == 2)
lblDice1.setIcon(imgDice2);
else if (whatDice1 == 3)
lblDice1.setIcon(imgDice3);
else if (whatDice1 == 4)
lblDice1.setIcon(imgDice4);
else if (whatDice1 == 5)
lblDice1.setIcon(imgDice5);
else if (whatDice1 == 6)
lblDice1.setIcon(imgDice6);
if (whatDice2 == 1)
lblDice2.setIcon(imgDice1);
else if (whatDice2 == 2)
lblDice2.setIcon(imgDice2);
else if (whatDice2 == 3)
lblDice2.setIcon(imgDice3);
else if (whatDice2 == 4)
lblDice2.setIcon(imgDice4);
else if (whatDice2 == 5)
lblDice2.setIcon(imgDice5);
else if (whatDice2 == 6)
lblDice2.setIcon(imgDice6);
}
public void roll() {
count = 0;
time.start();
}
}
// create a new dice roll object
RollDice roll = new RollDice();
// if the roll dice button is clicked
public void actionPerformed(ActionEvent arg0) {
roll.roll();
}
});
}
// load all images to memory
public void loadImages() {
BufferedImage i = null;
try {
i = ImageIO.read((getClass().getResource("/resources/Dice 1.png")));
imgDice1 = new ImageIcon(i.getScaledInstance(100, 100,
java.awt.Image.SCALE_SMOOTH));
i = ImageIO.read((getClass().getResource("/resources/Dice 2.png")));
imgDice2 = new ImageIcon(i.getScaledInstance(100, 100,
java.awt.Image.SCALE_SMOOTH));
i = ImageIO.read((getClass().getResource("/resources/Dice 3.png")));
imgDice3 = new ImageIcon(i.getScaledInstance(100, 100,
java.awt.Image.SCALE_SMOOTH));
i = ImageIO.read((getClass().getResource("/resources/Dice 4.png")));
imgDice4 = new ImageIcon(i.getScaledInstance(100, 100,
java.awt.Image.SCALE_SMOOTH));
i = ImageIO.read((getClass().getResource("/resources/Dice 5.png")));
imgDice5 = new ImageIcon(i.getScaledInstance(100, 100,
java.awt.Image.SCALE_SMOOTH));
i = ImageIO.read((getClass().getResource("/resources/Dice 6.png")));
imgDice6 = new ImageIcon(i.getScaledInstance(100, 100,
java.awt.Image.SCALE_SMOOTH));
i = ImageIO.read((getClass()
.getResource("/resources/Airplane Icon.png")));
icnAirplane = new ImageIcon(i.getScaledInstance(40, 40,
java.awt.Image.SCALE_SMOOTH));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// load all properties
public void loadProperties() {
propertiesList = new Property[40];
// set up the properties list
// (name, index, isBuyable, price, initial rent)
propertiesList[0] = new Property("Go", 0, false, 0, 0);
propertiesList[1] = new Property("Jacob's Field", 1, true, 600000,
20000);
propertiesList[2] = new Property("Community Chest", 2, false, 0, 0);
propertiesList[3] = new Property("Texas Stadium", 3, true, 600000,
40000);
propertiesList[4] = new Property("Income Tax", 4, false, 0, 0);
propertiesList[5] = new Property("O'Hare International Airport", 5,
true, 2000000, 250000);
propertiesList[6] = new Property("Grand Ole Opry", 6, true, 1000000,
60000);
propertiesList[7] = new Property("Chance", 7, false, 0, 0);
}
}
JPanel Code:
package com.Game.Monopoly;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Board extends JPanel {
private static final long serialVersionUID = 1L;
private Image board;
public Board(double scale) {
this.setPreferredSize(new Dimension((int) (1024 * scale),
(int) (1024 * scale)));
BufferedImage i = null;
try {
i = ImageIO.read((getClass().getResource("/resources/monopoly-board-web.jpg")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board = i.getScaledInstance((int) (1024 * scale), (int) (1024 * scale), java.awt.Image.SCALE_SMOOTH);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(board, 0, 0, this);
}
}
Player Object Code:
package com.Game.Monopoly;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
//a class representing a player with its graphical component
public class Player extends JLabel {
private String playerName;
private int money;
private Property[] propertiesOwned;
public Player(String n, ImageIcon icon) {
playerName = n;
this.setIcon(icon);
}
// changes the amount of money available
public void changeMoney(int amount) {
money = money + amount;
}
public void movePlayer(int x, int y){
this.setLocation(x, y);
}
}
There are a couple of ways you can achieve this, personally, the simplest would be to use custom painting directly and not bother with using Swing based components for the players.
The basic problem you have is JPanel uses a FlowLayout by default, which means that you will always be fighting layout manager. In this case you might consider using a custom layout manager, for example...
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager2;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Monopoly {
public static void main(String[] args) {
new Monopoly();
}
public Monopoly() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MonopolyBoard());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MonopolyBoard extends JPanel {
private List<JLabel> players;
public MonopolyBoard() {
setLayout(new MonopolyBoardLayout());
players = new ArrayList<>(2);
try {
players.add(makePlayer("/Dog.png"));
players.add(makePlayer("/Car.png"));
for (JLabel player : players) {
add(player, new Integer(0));
}
} catch (IOException exp) {
exp.printStackTrace();
}
Timer timer = new Timer(1000, new ActionListener() {
private int count = 0;
private Random rnd = new Random();
#Override
public void actionPerformed(ActionEvent e) {
int playerIndex = count % players.size();
JLabel player = players.get(playerIndex);
MonopolyBoardLayout layout = (MonopolyBoardLayout) getLayout();
int position = layout.getPosition(player);
position += rnd.nextInt(5) + 1;
if (position > 35) {
position -= 35;
}
layout.setPosition(player, position);
revalidate();
repaint();
count++;
}
});
timer.start();
}
protected JLabel makePlayer(String path) throws IOException {
JLabel label = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource(path))), JLabel.CENTER);
return label;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
for (int index = 0; index < 36; index++) {
Rectangle bounds = MonopolyBoardLayoutHelper.getCellBounds(index, width, height);
g2d.draw(bounds);
}
g2d.dispose();
}
}
public static class MonopolyBoardLayoutHelper {
private static Map<Integer, Point> mapBoardCells;
static {
mapBoardCells = new HashMap<>(25);
mapBoardCells.put(10, new Point(0, 8));
mapBoardCells.put(11, new Point(0, 7));
mapBoardCells.put(12, new Point(0, 6));
mapBoardCells.put(13, new Point(0, 5));
mapBoardCells.put(14, new Point(0, 4));
mapBoardCells.put(15, new Point(0, 3));
mapBoardCells.put(16, new Point(0, 2));
mapBoardCells.put(17, new Point(0, 1));
mapBoardCells.put(18, new Point(0, 0));
mapBoardCells.put(0, new Point(9, 9));
mapBoardCells.put(1, new Point(8, 9));
mapBoardCells.put(2, new Point(7, 9));
mapBoardCells.put(3, new Point(6, 9));
mapBoardCells.put(4, new Point(5, 9));
mapBoardCells.put(5, new Point(4, 9));
mapBoardCells.put(6, new Point(3, 9));
mapBoardCells.put(7, new Point(2, 9));
mapBoardCells.put(8, new Point(1, 9));
mapBoardCells.put(9, new Point(0, 9));
mapBoardCells.put(19, new Point(1, 0));
mapBoardCells.put(20, new Point(2, 0));
mapBoardCells.put(21, new Point(3, 0));
mapBoardCells.put(22, new Point(4, 0));
mapBoardCells.put(23, new Point(5, 0));
mapBoardCells.put(24, new Point(6, 0));
mapBoardCells.put(25, new Point(7, 0));
mapBoardCells.put(26, new Point(8, 0));
mapBoardCells.put(27, new Point(9, 0));
mapBoardCells.put(28, new Point(9, 1));
mapBoardCells.put(29, new Point(9, 2));
mapBoardCells.put(30, new Point(9, 3));
mapBoardCells.put(31, new Point(9, 4));
mapBoardCells.put(32, new Point(9, 5));
mapBoardCells.put(33, new Point(9, 6));
mapBoardCells.put(34, new Point(9, 7));
mapBoardCells.put(35, new Point(9, 8));
}
public static Rectangle getCellBounds(int index, int width, int height) {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
int size = Math.min(width, height);
int cellSize = size / 10;
int xOffset = (width - size) / 2;
int yOffset = (height - size) / 2;
Point point = mapBoardCells.get(index);
if (point != null) {
int x = xOffset + (point.x * cellSize);
int y = yOffset + (point.y * cellSize);
bounds = new Rectangle(x, y, cellSize, cellSize);
}
return bounds;
}
}
public static class MonopolyBoardLayout implements LayoutManager2 {
public static final int DEFAULT_CELL_SIZE = 64;
private Map<Component, Integer> cellConstraints;
public MonopolyBoardLayout() {
cellConstraints = new HashMap<>(5);
}
public Integer getPosition(Component comp) {
return cellConstraints.get(comp);
}
public void setPosition(Component comp, int position) {
cellConstraints.put(comp, position);
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints instanceof Integer) {
int cell = (int) constraints;
if (cell >= 0 && cell <= 35) {
cellConstraints.put(comp, cell);
} else {
throw new IllegalArgumentException(constraints + " is not within the bounds of a valid cell reference (0-35)");
}
} else {
throw new IllegalArgumentException(constraints + " is not a valid cell reference (integer within 0-35)");
}
}
#Override
public Dimension maximumLayoutSize(Container target) {
return new Dimension(DEFAULT_CELL_SIZE * 10, DEFAULT_CELL_SIZE * 10);
}
#Override
public float getLayoutAlignmentX(Container target) {
return 0.5f;
}
#Override
public float getLayoutAlignmentY(Container target) {
return 0.5f;
}
#Override
public void invalidateLayout(Container target) {
}
#Override
public void addLayoutComponent(String name, Component comp) {
}
#Override
public void removeLayoutComponent(Component comp) {
cellConstraints.remove(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
return new Dimension(DEFAULT_CELL_SIZE * 10, DEFAULT_CELL_SIZE * 10);
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return new Dimension(DEFAULT_CELL_SIZE * 10, DEFAULT_CELL_SIZE * 10);
}
#Override
public void layoutContainer(Container parent) {
int width = parent.getWidth();
int height = parent.getHeight();
Map<Integer, List<Component>> components = new HashMap<>(25);
for (Component child : parent.getComponents()) {
Integer cell = cellConstraints.get(child);
if (cell != null) {
List<Component> children = components.get(cell);
if (children == null) {
children = new ArrayList<>(4);
components.put(cell, children);
}
children.add(child);
} else {
child.setBounds(0, 0, 0, 0);
}
}
for (Map.Entry<Integer, List<Component>> entry : components.entrySet()) {
int index = entry.getKey();
Rectangle bounds = MonopolyBoardLayoutHelper.getCellBounds(index, width, height);
List<Component> comp = entry.getValue();
int xDelta = 0;
int yDelta = 0;
int availableWidth = bounds.width;
int availableHeight = bounds.height;
switch (comp.size()) {
case 2:
availableWidth /= 2;
xDelta = availableWidth;
break;
case 3:
case 4:
availableWidth /= 2;
xDelta = availableWidth;
availableHeight /= 2;
yDelta = availableHeight;
break;
}
int x = bounds.x;
int y = bounds.y;
for (int count = 0; count < comp.size() && count < 4; count++) {
Component child = comp.get(count);
child.setSize(availableWidth, availableHeight);
child.setLocation(x, y);
x += xDelta;
if (x >= bounds.x + bounds.width) {
x = bounds.x;
y += yDelta;
}
}
}
}
}
}
As you can see, this becomes real complicated real quick. This example currently only allows 4 players per cell, so if you want more, then you're going to have to create your own algorithim
Related
I have a program that retrieves data, where each retrieval can not be determined its completion time. My idea would be to make a progress that keeps repeating and flagging if the capture is complete.
my current source code, method from main class:
public JComponent makeUI(boolean displayProgressBar) {
if(displayProgressBar){
jpbCircularProg.setUI(new principal.ProgressCircleUI());
jpbCircularProg.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
//Border emptyBorder = BorderFactory.createEmptyBorder();
//jpbCircularProg.setBorder(emptyBorder);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setFont(jpbCircularProg.getFont().deriveFont(24f));
jpbCircularProg.setForeground(Color.ORANGE);
if(jpbCircularProg.isVisible()==false){
jpbCircularProg.setVisible(true);
}
(new Timer(10, e -> {// percepat
System.out.println("progressbar on :");
int iv = Math.min(100, jpbCircularProg.getValue() + 1);
jpbCircularProg.setValue(iv);
if(jpbCircularProg.getValue()==100){
jpbCircularProg.setValue(1);
}
})).start();
}else{
if(jpbCircularProg.isVisible()==true){
jpbCircularProg.setVisible(false);
}
(new Timer(10, e -> {// percepat
System.out.println("progressbar on :");
int iv = Math.min(100, jpbCircularProg.getValue() + 1);
jpbCircularProg.setValue(iv);
if(jpbCircularProg.getValue()==100){
jpbCircularProg.setValue(0);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setVisible(false);
}
})).start();
}
jPanel2.setOpaque(false);
jPanel2.add(jpbCircularProg);
return jPanel2;
}
ProgressCircleUI.java:
public class ProgressCircleUI extends BasicProgressBarUI {
#Override
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
#Override public void paint(Graphics g, JComponent c) {
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - b.right - b.left;
int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
// draw the cells
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(progressBar.getForeground());
double degree = 360 * progressBar.getPercentComplete();
double sz = Math.min(barRectWidth, barRectHeight);
double cx = b.left + barRectWidth * .5;
double cy = b.top + barRectHeight * .5;
double or = sz * .5;
double ir = or * .5; //or - 20;
Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
Shape outer = new Arc2D.Double(
cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
Area area = new Area(outer);
area.subtract(new Area(inner));
g2.fill(area);
g2.dispose();
// Deal with possible text painting
if (progressBar.isStringPainted()) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
}
}
}
Source code diatassaya get from a website then i modified a bit. I give the loop and the result is successful, but when the data retrieval more than once circular progress cycle becomes very fast and always increase faster for next data retrieval. I tried by using setIntermedinate (true) but it seems to ProgressBar not a Circular. Please help.
but when the data retrieval more than once circular progress cycle becomes very fast and always increase faster for next data retrieval
You're not stopping the timer, in fact, you seem to be using a second Timer to hide the progress bar ... for some reason.
This means, each time you want to use the progress indicator, you create ANOTHER Timer, which creates a bunch of competing Timers all changing the state and interfering with each other.
A better and simpler solution would be to create a single Timer and simply stop/start it as need, for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.plaf.basic.BasicProgressBarUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JProgressBar jpbCircularProg;
private Timer timer;
public TestPane() {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int iv = Math.min(100, jpbCircularProg.getValue() + 1);
jpbCircularProg.setValue(iv);
if (jpbCircularProg.getValue() == 100) {
jpbCircularProg.setValue(1);
}
}
});
jpbCircularProg = new JProgressBar();
jpbCircularProg.setUI(new ProgressCircleUI());
jpbCircularProg.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
//Border emptyBorder = BorderFactory.createEmptyBorder();
//jpbCircularProg.setBorder(emptyBorder);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setFont(jpbCircularProg.getFont().deriveFont(24f));
jpbCircularProg.setForeground(Color.ORANGE);
if (jpbCircularProg.isVisible() == false) {
jpbCircularProg.setVisible(true);
}
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = GridBagConstraints.REMAINDER;
add(jpbCircularProg, gbc);
JButton toggle = new JButton("Toggle");
toggle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.restart();
}
}
});
add(toggle, gbc);
}
}
public class ProgressCircleUI extends BasicProgressBarUI {
#Override
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
#Override
public void paint(Graphics g, JComponent c) {
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - b.right - b.left;
int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
// draw the cells
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(progressBar.getForeground());
double degree = 360 * progressBar.getPercentComplete();
double sz = Math.min(barRectWidth, barRectHeight);
double cx = b.left + barRectWidth * .5;
double cy = b.top + barRectHeight * .5;
double or = sz * .5;
double ir = or * .5; //or - 20;
Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
Shape outer = new Arc2D.Double(
cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
Area area = new Area(outer);
area.subtract(new Area(inner));
g2.fill(area);
g2.dispose();
// Deal with possible text painting
if (progressBar.isStringPainted()) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
}
}
}
}
Since you're trying to display this as a "intermediate" progress bar, it would be better to wrap up the animation functionality into the UI delegate itself.
The following example makes use of the "intermediate" state of the JProgressBar to self animate the progress, managing the Timer state itself
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.beans.PropertyChangeEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.plaf.basic.BasicProgressBarUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JProgressBar jpbCircularProg;
public TestPane() {
jpbCircularProg = new JProgressBar();
jpbCircularProg.setUI(new ProgressCircleUI());
jpbCircularProg.setIndeterminate(true);
jpbCircularProg.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
//Border emptyBorder = BorderFactory.createEmptyBorder();
//jpbCircularProg.setBorder(emptyBorder);
jpbCircularProg.setStringPainted(true);
jpbCircularProg.setFont(jpbCircularProg.getFont().deriveFont(24f));
jpbCircularProg.setForeground(Color.ORANGE);
if (jpbCircularProg.isVisible() == false) {
jpbCircularProg.setVisible(true);
}
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = GridBagConstraints.REMAINDER;
add(jpbCircularProg, gbc);
JButton toggle = new JButton("Toggle");
toggle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jpbCircularProg.setIndeterminate(!jpbCircularProg.isIndeterminate());
}
});
add(toggle, gbc);
}
}
public class ProgressCircleUI extends BasicProgressBarUI {
private Timer timer;
private Handler handler = new Handler();
#Override
public void installUI(JComponent c) {
initTimer();
super.installUI(c);
}
protected void initTimer() {
if (timer == null) {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int iv = Math.min(100, progressBar.getValue() + 1);
progressBar.setValue(iv);
if (progressBar.getValue() == 100) {
progressBar.setValue(1);
}
progressBar.repaint();
}
});
}
}
#Override
protected void startAnimationTimer() {
timer.restart();
}
#Override
protected void stopAnimationTimer() {
timer.stop();
}
private void initIndeterminateValues() {
initTimer();
// we only bother installing the HierarchyChangeListener if we
// are indeterminate
progressBar.addHierarchyListener(handler);
// start the animation thread if necessary
if (progressBar.isDisplayable()) {
startAnimationTimer();
}
}
/**
* Invoked by PropertyChangeHandler.
*/
private void cleanUpIndeterminateValues() {
// stop the animation thread if necessary
if (progressBar.isDisplayable()) {
stopAnimationTimer();
}
progressBar.setValue(0);
progressBar.removeHierarchyListener(handler);
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if ("indeterminate" == prop) {
if (progressBar.isIndeterminate()) {
initIndeterminateValues();
} else {
//clean up
cleanUpIndeterminateValues();
}
progressBar.repaint();
}
}
#Override
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
#Override
public void paint(Graphics g, JComponent c) {
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - b.right - b.left;
int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
// draw the cells
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(progressBar.getForeground());
double degree = 360 * progressBar.getPercentComplete();
double sz = Math.min(barRectWidth, barRectHeight);
double cx = b.left + barRectWidth * .5;
double cy = b.top + barRectHeight * .5;
double or = sz * .5;
double ir = or * .5; //or - 20;
Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
Shape outer = new Arc2D.Double(
cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
Area area = new Area(outer);
area.subtract(new Area(inner));
g2.fill(area);
g2.dispose();
// Deal with possible text painting
if (progressBar.isStringPainted() && !progressBar.isIndeterminate()) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
}
}
protected class Handler implements HierarchyListener {
public void hierarchyChanged(HierarchyEvent he) {
if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
if (progressBar.isIndeterminate()) {
if (progressBar.isDisplayable()) {
startAnimationTimer();
} else {
stopAnimationTimer();
}
}
}
}
}
}
}
I'm looking for some help regarding a Java program I'm writing. I need to display a simple bar graph consisting of rectangles based off of data saved in an array that has been generated by a JList selection event. However, nothing is drawn in the JPanel and I cannot figure out how to fix it.
List Selection Event (For reference)
try
{
BufferedReader in = new BufferedReader((new FileReader("scores.txt")));
String sLine;
while ((sLine = in.readLine()) != null)
{
vecAthlete.addElement(new Stage3_DataFile(sLine));
}
String[] saAthlete = new String[vecAthlete.size()];
for (int iI = 0; iI < vecAthlete.size(); iI++)
saAthlete[iI] = vecAthlete.get(iI).sName;
jList_Athlete.setListData(saAthlete);
jList_Athlete.setSelectedIndex(0);
// Reading input line by line
// Close file
in.close();
}
catch (IOException e)
{
System.out.println("ERROR: Could not read text file!");
}
jList_Athlete.addListSelectionListener(new javax.swing.event.ListSelectionListener()
{
public void valueChanged(javax.swing.event.ListSelectionEvent e)
{
double[][] daRun = new double[2][7];
final double dScoreUsed = 5;
double dMinScoreRun1 = 10, dMaxScoreRun1 = 0;
double dMinScoreRun2 = 10, dMaxScoreRun2 = 0;
double dTotalRun1 = 0, dTotalRun2 = 0;
jLabel_Athlete.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sName);
jLabel_Country.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sCountry);
jLabel_Run1_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[0]);
jLabel_Run1_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[1]);
jLabel_Run1_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[2]);
jLabel_Run1_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[3]);
jLabel_Run1_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[4]);
jLabel_Run1_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[5]);
jLabel_Run1_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[6]);
jLabel_Run2_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[0]);
jLabel_Run2_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[1]);
jLabel_Run2_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[2]);
jLabel_Run2_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[3]);
jLabel_Run2_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[4]);
jLabel_Run2_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[5]);
jLabel_Run2_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[6]);
daRun[0][0] = Double.parseDouble(jLabel_Run1_Score_1.getText());
daRun[0][1] = Double.parseDouble(jLabel_Run1_Score_2.getText());
daRun[0][2] = Double.parseDouble(jLabel_Run1_Score_3.getText());
daRun[0][3] = Double.parseDouble(jLabel_Run1_Score_4.getText());
daRun[0][4] = Double.parseDouble(jLabel_Run1_Score_5.getText());
daRun[0][5] = Double.parseDouble(jLabel_Run1_Score_6.getText());
daRun[0][6] = Double.parseDouble(jLabel_Run1_Score_7.getText());
daRun[1][0] = Double.parseDouble(jLabel_Run2_Score_1.getText());
daRun[1][1] = Double.parseDouble(jLabel_Run2_Score_2.getText());
daRun[1][2] = Double.parseDouble(jLabel_Run2_Score_3.getText());
daRun[1][3] = Double.parseDouble(jLabel_Run2_Score_4.getText());
daRun[1][4] = Double.parseDouble(jLabel_Run2_Score_5.getText());
daRun[1][5] = Double.parseDouble(jLabel_Run2_Score_6.getText());
daRun[1][6] = Double.parseDouble(jLabel_Run2_Score_7.getText());
for(int i = 0; i < 7; i++)
{
if(daRun[0][i] <= dMinScoreRun1)
{
dMinScoreRun1 = daRun[0][i];
}
if(daRun[0][i] >= dMaxScoreRun1)
{
dMaxScoreRun1 = daRun[0][i];
}
dTotalRun1 += daRun[0][i];
}
dTotalRun1 = (dTotalRun1 - dMinScoreRun1 - dMaxScoreRun1) / dScoreUsed;
jLabel_TotalRun1.setText(String.valueOf(dTotalRun1));
jLabel_Run1AddInfo.setText("Min Score: " + (dMinScoreRun1) + ", Max Score: " + (dMaxScoreRun1));
for(int i = 0; i < 7; i++)
{
if(daRun[1][i] <= dMinScoreRun2)
{
dMinScoreRun2 = daRun[1][i];
}
if(daRun[1][i] >= dMaxScoreRun2)
{
dMaxScoreRun2 = daRun[1][i];
}
dTotalRun2 += daRun[1][i];
}
dTotalRun2 = (dTotalRun2 - dMinScoreRun2 - dMaxScoreRun2) / dScoreUsed;
jLabel_TotalRun2.setText(String.valueOf(dTotalRun2));
jLabel_Run2AddInfo.setText("Min Score: " + (dMinScoreRun2) + ", Max Score: " + (dMaxScoreRun2));
if(dTotalRun1 >= dTotalRun2)
jLabel_FinalScore.setText(String.valueOf(dTotalRun1));
else
jLabel_FinalScore.setText(String.valueOf(dTotalRun2));
jPanel_Graph.repaint();
}
});
JPanel Definitions
JPanel jPanel_Graph = new JPanel();
jPanel_Graph.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
jPanel_Graph.setBounds(729, 159, 700, 200);
frame.getContentPane().add(jPanel_Graph);
img = new BufferedImage(jPanel_Graph.getWidth(),
jPanel_Graph.getHeight(),
BufferedImage.TYPE_INT_RGB);
g2dimg = (Graphics2D)img.getGraphics();
// Draw a filled white coloured rectangle on the entire area to clear it.
g2dimg.setPaint(Color.WHITE);
g2dimg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
JPanel Drawing Event
class myJPanel extends JPanel
{
private Rectangle2D.Double rectangle;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < 7; i++)
{
dHeight = daRun[0][i];
rectangle = new Rectangle2D.Double(dX, dY, dWidth, dHeight);
g2dimg.setPaint(Color.red);
g2dimg.draw(rectangle);
g2dimg.fill(rectangle);
dX += dXIncrement;
g2dimg.drawImage(img, 0, 0, null);
}
}
}
Thanks in advance!
So, from what I can tell, there is no way for your "graph" to know what it should paint. The basic idea is, your "graph" should be focused on painting the data/model, so you need some way to tell it when the data changes.
There are lots of ways you might do this, for example, you could devise a model, which you add/remove data to, which could trigger updates that the graph pane listeners for and then updates itself with the new data.
Or you just pass the data you want updated directly to the graph pane, which in this case, might the simplest solution available to you
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private GraphPane graphPane;
public TestPane() {
setLayout(new BorderLayout());
DefaultListModel<Double> listmodel = new DefaultListModel<>();
for (int index = 0; index < 100; index++) {
listmodel.addElement(Math.random());
}
graphPane = new GraphPane();
add(graphPane);
JList<Double> listData = new JList<>(listmodel);
add(new JScrollPane(listData), BorderLayout.WEST);
listData.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
graphPane.setData(listData.getSelectedValuesList().toArray(new Double[0]));
}
});
}
}
public class GraphPane extends JPanel {
private Double[] data;
public void setData(Double[] data) {
this.data = data;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (data != null && data.length > 0) {
Graphics2D g2d = (Graphics2D) g.create();
double barWidth = getWidth() / (double)data.length;
int xPos = 0;
for (Double value : data) {
double height = (getHeight() - 1) * value;
Rectangle2D bar = new Rectangle2D.Double(xPos, getHeight() - height, barWidth, height);
g2d.setColor(Color.GREEN);
g2d.fill(bar);
g2d.setColor(Color.BLACK);
g2d.draw(bar);
xPos += barWidth;
}
g2d.dispose();
}
}
}
}
I am making a launcher and I want to have a customized ProgressBar.
I have done some research and it's possible with JavaFX(Never did something with it) and it's possible with replacing the UI.
I am looking for a bar with rounded edges and a rounded fill.
Something like this:
package gui;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private final JPanel contentPane;
final JFrame frame = new JFrame();
int pX,pY;
/**
* Launch the application.
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
final Gui frame = new Gui();
frame.setVisible(true);
} catch (final Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gui() {
this.setTitle("Exile Launcher");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(0, 0, 1000, 563);
this.contentPane = new JPanel();
this.contentPane.setBorder(null);
this.setContentPane(this.contentPane);
this.contentPane.setLayout(null);
this.setUndecorated(true);
this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width/2-this.getSize().width/2, Toolkit.getDefaultToolkit().getScreenSize().height/2-this.getSize().height/2);
int X = 24;
int Y = 40;
final JButton HomeButton = new JButton();
HomeButton.setFocusPainted(false);
HomeButton.setBorder(null);
HomeButton.setContentAreaFilled(false);
HomeButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/0.png")));
HomeButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/0_h.png")));
HomeButton.setBounds(new Rectangle(X, Y, 50, 50));
this.contentPane.add(HomeButton);
HomeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
try {
Desktop.getDesktop().browse(new URL("http://www.google.nl").toURI());
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
});
Y += 60;
final JButton ForumButton = new JButton();
ForumButton.setFocusPainted(false);
ForumButton.setBorder(null);
ForumButton.setContentAreaFilled(false);
ForumButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/1.png")));
ForumButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/1_h.png")));
ForumButton.setBounds(new Rectangle(X, Y, 50, 50));
this.contentPane.add(ForumButton);
Y += 60;
final JButton VoteButton = new JButton();
VoteButton.setFocusPainted(false);
VoteButton.setBorder(null);
VoteButton.setContentAreaFilled(false);
VoteButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/4.png")));
VoteButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/4_h.png")));
VoteButton.setBounds(new Rectangle(X, Y, 50, 50));
this.contentPane.add(VoteButton);
final JButton CloseButton = new JButton();
CloseButton.setFocusPainted(false);
CloseButton.setBorder(null);
CloseButton.setContentAreaFilled(false);
CloseButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Close.png")));
CloseButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Close_h.png")));
CloseButton.setBounds(new Rectangle(875, 0, 27, 28));
this.contentPane.add(CloseButton);
CloseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
System.exit(0);
}
});
final JButton MinimizeButton = new JButton();
MinimizeButton.setFocusPainted(false);
MinimizeButton.setBorder(null);
MinimizeButton.setContentAreaFilled(false);
MinimizeButton.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Minimize.png")));
MinimizeButton.setRolloverIcon(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Minimize_h.png")));
MinimizeButton.setBounds(new Rectangle(850, -1, 27, 28));
this.contentPane.add(MinimizeButton);
MinimizeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
setState(Frame.ICONIFIED);
}
});
final JProgressBar ProgressBar = new JProgressBar();
ProgressBar.setLocation(150, 500);
ProgressBar.setSize(600, 50);
ProgressBar.setValue(50);
getContentPane().add(ProgressBar);
final JLabel backgroundLabel = new JLabel(new ImageIcon(this.getClass().getClassLoader().getResource("Images/Background.png")));
backgroundLabel.setBounds(new Rectangle(0, 0, 1000, 563));
getContentPane().add(backgroundLabel);
JPanel titleBar = new JPanel();
titleBar.setBounds(0, 0, 1000, 25);
contentPane.add(titleBar);
titleBar.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me)
{
// Get x,y and store them
pX=me.getX();
pY=me.getY();
}
});
titleBar.addMouseMotionListener(new MouseAdapter(){
public void mouseDragged(MouseEvent me)
{
setLocation(getLocation().x+me.getX()-pX,getLocation().y+me.getY()-pY);
}
});
}
}
There are a number of ways you might achieve this, one of the better ways would be to create a custom ProgressBarUI delegate which paints itself the way you want, for example...
public class FancyProgressBar extends BasicProgressBarUI {
#Override
protected Dimension getPreferredInnerVertical() {
return new Dimension(20, 146);
}
#Override
protected Dimension getPreferredInnerHorizontal() {
return new Dimension(146, 20);
}
#Override
protected void paintDeterminate(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int iStrokWidth = 3;
g2d.setStroke(new BasicStroke(iStrokWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.setColor(progressBar.getBackground());
g2d.setBackground(progressBar.getBackground());
int width = progressBar.getWidth();
int height = progressBar.getHeight();
RoundRectangle2D outline = new RoundRectangle2D.Double((iStrokWidth / 2), (iStrokWidth / 2),
width - iStrokWidth, height - iStrokWidth,
height, height);
g2d.draw(outline);
int iInnerHeight = height - (iStrokWidth * 4);
int iInnerWidth = width - (iStrokWidth * 4);
double dProgress = progressBar.getPercentComplete();
if (dProgress < 0) {
dProgress = 0;
} else if (dProgress > 1) {
dProgress = 1;
}
iInnerWidth = (int) Math.round(iInnerWidth * dProgress);
int x = iStrokWidth * 2;
int y = iStrokWidth * 2;
Point2D start = new Point2D.Double(x, y);
Point2D end = new Point2D.Double(x, y + iInnerHeight);
float[] dist = {0.0f, 0.25f, 1.0f};
Color[] colors = {progressBar.getBackground(), progressBar.getBackground().brighter(), progressBar.getBackground().darker()};
LinearGradientPaint p = new LinearGradientPaint(start, end, dist, colors);
g2d.setPaint(p);
RoundRectangle2D fill = new RoundRectangle2D.Double(iStrokWidth * 2, iStrokWidth * 2,
iInnerWidth, iInnerHeight, iInnerHeight, iInnerHeight);
g2d.fill(fill);
g2d.dispose();
}
#Override
protected void paintIndeterminate(Graphics g, JComponent c) {
super.paintIndeterminate(g, c); //To change body of generated methods, choose Tools | Templates.
}
}
Normally you might be tempered to register this as the default look and feel delegate of all JProgressBars, but typically, I would install only on those instance of JProgressBar you really wanted it, that comes down to you.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.LinearGradientPaint;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.basic.BasicProgressBarUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.BLACK);
JProgressBar fancyPB = new JProgressBar();
fancyPB.setUI(new FancyProgressBar());
JProgressBar normalPB = new JProgressBar();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(fancyPB, gbc);
add(normalPB, gbc);
Timer timer = new Timer(250, new ActionListener() {
private int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
fancyPB.setValue(count);
normalPB.setValue(count);
count++;
if (count >= 100) {
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
}
public class FancyProgressBar extends BasicProgressBarUI {
#Override
protected Dimension getPreferredInnerVertical() {
return new Dimension(20, 146);
}
#Override
protected Dimension getPreferredInnerHorizontal() {
return new Dimension(146, 20);
}
#Override
protected void paintDeterminate(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int iStrokWidth = 3;
g2d.setStroke(new BasicStroke(iStrokWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.setColor(progressBar.getBackground());
g2d.setBackground(progressBar.getBackground());
int width = progressBar.getWidth();
int height = progressBar.getHeight();
RoundRectangle2D outline = new RoundRectangle2D.Double((iStrokWidth / 2), (iStrokWidth / 2),
width - iStrokWidth, height - iStrokWidth,
height, height);
g2d.draw(outline);
int iInnerHeight = height - (iStrokWidth * 4);
int iInnerWidth = width - (iStrokWidth * 4);
double dProgress = progressBar.getPercentComplete();
if (dProgress < 0) {
dProgress = 0;
} else if (dProgress > 1) {
dProgress = 1;
}
iInnerWidth = (int) Math.round(iInnerWidth * dProgress);
int x = iStrokWidth * 2;
int y = iStrokWidth * 2;
Point2D start = new Point2D.Double(x, y);
Point2D end = new Point2D.Double(x, y + iInnerHeight);
float[] dist = {0.0f, 0.25f, 1.0f};
Color[] colors = {progressBar.getBackground(), progressBar.getBackground().brighter(), progressBar.getBackground().darker()};
LinearGradientPaint p = new LinearGradientPaint(start, end, dist, colors);
g2d.setPaint(p);
RoundRectangle2D fill = new RoundRectangle2D.Double(iStrokWidth * 2, iStrokWidth * 2,
iInnerWidth, iInnerHeight, iInnerHeight, iInnerHeight);
g2d.fill(fill);
g2d.dispose();
}
#Override
protected void paintIndeterminate(Graphics g, JComponent c) {
super.paintIndeterminate(g, c); //To change body of generated methods, choose Tools | Templates.
}
}
}
If you want to install the look and feel delegate as the default delegate, take a look at this answer for more details (scroll down a little, it's there)
Object fileButton = null;
if("Analyze Text File".equals(command)) {
JFileChooser filechooser;
JFileChooser chooser = new JFileChooser();
int returnVal = filechooser.showOpenDialog(getParent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = filechooser.getSelectedFile();
String Stext = (String) readFileAsString(file); //String text = textInput.getText();
Map<Integer, Integer> counts = getCounts(text);
int width = counts.size() * BAR_WIDTH;
int max = maxCount(counts);
int height = max * INCREMENT + 100;
int horizon = height - 25;
HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
//panel.setBorder(new LineBorder(Color.BLACK, 2));
JOptionPane.showMessageDialog(null, panel);
i am creating a java applet where it counts the frequency/occurence of X words, i have worked out how to do the array to work out the frequency depending on what the user inputs, i need to now create a bar chart that adapts to whatever the user inputs, i have wrote up a code for my bar chart but i dont know how to connect it to my array code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.net.URL;
import java.io.*;
import java.util.HashMap;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Map;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class assignment_work extends JApplet implements ActionListener {
JTextArea textInput; // User Input.
JLabel wordCountLabel; // To display number of words.
JLabel meanLabel; // To display the mean.
public void init() {
// This code from here is the customisation of the Applet, this includes background colour, text colour, text back ground colour, labels and buttons
setBackground(Color.black);
getContentPane().setBackground(Color.black);
textInput = new JTextArea();
textInput.setWrapStyleWord(true);
JPanel ui = new JPanel();
ui.setLayout(Layout(-1));
/* Creating Analyze and Reset buttons */
JButton chartButton = new JButton("Bar Chart");
chartButton.addActionListener(this);
ui.add(chartButton);
JPanel panel = new JPanel(new BorderLayout())
//panel.add(chartButton, BorderLayout.SOUTH);
/* Labels telling the user what to do or what the program is outputting */
wordCountLabel.setBackground(Color.black);
wordCountLabel.setForeground(Color.red);
wordCountLabel.setOpaque(true);
meanLabel.setBackground(Color.white);
meanLabel.setForeground(Color.black);
meanLabel.setOpaque(true);
watermark.setLayout(new BorderLayout());
watermark.setBackground(Color.darkGray);
/* Border for Applet. */
getContentPane().setLayout( new BorderLayout());
getContentPane().add(ui, BorderLayout.CENTER);
/* Scroll bar for the text area where the user will input the text they wish to analyse. */
JScrollPane scroller = new JScrollPane( textInput );
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(ui, BorderLayout.NORTH);
}
class CustomCanvas extends Canvas {
public CustomCanvas() {
setBackground(Color.darkGray);
setPreferredSize(new Dimension(100, 100));
}
public void paint(Graphics g) {
int x [] = {20,20,10,10,40,40,30,30};
int y [] = {40,20,20,10,10,20,20,40};
int n = 8;
g.setColor(Color.black);
g.fillPolygon(x,y,n);
int wpoint [] = {45,65,85,75,70,60,55};
int zpoint [] = {40,10,40,40,30,30,40};
int npoint = 7;
g.setColor(Color.black);
g.fillPolygon(wpoint,zpoint,npoint);
int a [] = {60,65,70};
int b [] = {25,20,25};
int npoints = 3;
g.setColor(Color.darkGray);
g.fillPolygon(a,b,npoints);
}
}
private int maxCount(Map<Integer, Integer> counts) {
counts.values()) {
if (num > max) {
max = num;
}
}
return max;
}
public class Panel extends JPanel {
int width;
Map<Integer> count;
public Histogram(int width, Map<Integer, Integer> counts, int horizon) {
this.width = width;
this.dimHeight = dimHeight;
this.horizon = horizon;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 10;
for (Map.Entry<Int> entry : counts.entrySet()) {
int height = entry.getValue() * INCREMENT;
int y = horizon - height;
g.drawString(entry.getValue() + " Frequency", x, y -2);
x += BAR_WIDTH;
}
}
public Dimension getPreferredSize() {
return new Dimension(width, dimHeight);
}
}
public static Map<Int> getCounts(String Input) {
Map<Integer> map = new HashMap<Int>();
String[] array = Input.split("[\\s.,;:!?()");
for (String array) {
Int size;
if (!map(size)) {
map.put(size, 1);
} else {
map.put(map.get(size) + 1);
}
}
return;
}
// Text analysis end
public void actionPerformed(java.awt.event.ActionEvent e) {
if (command.equals("commands")) {
{
final graph<Int> Lengths = new graph<Int>();
String array = Input.Text().split(");
for (int i = 10; i < array.length; i) {
final int Length = array[0].length();
if( Length.Set().container(Length ) ) {
Integer currentNumberOfOccurences = wordLengths.get(wordLength);
currentNumberOfOccurences;
wordLengths.put(wordLength, currentNumberOfOccurences);
}
wordLengths.put(wordLength, 1);
}
double total =10;
double total = 10;
for (final Int length : Lengths.Set()) {
final Int occurrences = Lengths.get(length);
Length = tLength + (length * occurrencers );
totalOccurrences += occurrences;
}
final mean = aLength / lOccurrences;
aLabel.Text("mean word length is: " + (eLength / wOccurrences) );
// System.out.println("mean word length is: " + (total / length) );
}
String array = textInput.getText().split(" ");
int maxWordLength = 0;
wordLength = array[i].length();
if (wordLength > maxWordLength) {
maxWordLength = wordLength;
}
int[] intArray = new int[maxWordLength + 1];
for (int i = 0; i < array.length; i++) {
intArray[array[i].length()]++;
}
for (int i = 1; i < intArray.length; i++) {
out.printf("%d word(s) of length %d<br>", intArray[i], i)
}
else if (command.equals("Reset")) {
textInput.setText("");
textInput.requestFocus();
}
Object chartButton = null;
if (e.getSource() == chartButton) {
String text = textInput.getText();
HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
//panel.setBorder(new LineBorder(Color.BLACK, 2));
JOptionPane.showMessageDialog(null, panel);
}
};
}
Update
Using JFileCHooser
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
Here's what you want to do to create the dynamic size from the input.
You need to get the number of entries in the map, then multiply it by whatever you want the width of each bar to be.
You need to get the highest value in the map and multiply that by you increment (to draw) amount and create the height from that.
You create a new JPanel with dimension based on the height and width from the previous two points.
Iterate through the map the draw the bars.
I do the things above in the actionPerformed of a button and I add the JPanel to a JOptionPane. Let me know if you need clarification on anything.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Histogram {
private static final int BAR_WIDTH = 50;
private static final int INCREMENT = 10;
public Histogram() {
final JTextArea textArea = new JTextArea(5, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JButton go = new JButton("Histogram-me!");
JPanel panel = new JPanel(new BorderLayout());
panel.add(textArea, BorderLayout.CENTER);
panel.add(go, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = textArea.getText();
Map<Integer, Integer> counts = getCounts(text);
int width = counts.size() * BAR_WIDTH;
int max = maxCount(counts);
int height = max * INCREMENT + 100;
int horizon = height - 25;
HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
//panel.setBorder(new LineBorder(Color.BLACK, 2));
JOptionPane.showMessageDialog(null, panel);
}
});
}
private int maxCount(Map<Integer, Integer> counts) {
int max = 0;
for (Integer num : counts.values()) {
if (num > max) {
max = num;
}
}
return max;
}
public class HistogramPanel extends JPanel {
int width;
int dimHeight;
int horizon;
Map<Integer, Integer> counts;
public HistogramPanel(int width, Map<Integer, Integer> counts, int dimHeight, int horizon) {
this.width = width;
this.counts = counts;
this.dimHeight = dimHeight;
this.horizon = horizon;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 10;
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
int height = entry.getValue() * INCREMENT;
int y = horizon - height;
g.fillRect(x, y, BAR_WIDTH - 10, height);
g.drawString(entry.getKey() + " chars", x, horizon + 10);
g.drawString(entry.getValue() + " times", x, y -2);
x += BAR_WIDTH;
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, dimHeight);
}
}
public static Map<Integer, Integer> getCounts(String input) {
Map<Integer, Integer> map = new HashMap<>();
String[] array = input.split("[\\s.,;:!?(){}]+");
for (String s : array) {
Integer size = s.length();
if (!map.containsKey(size)) {
map.put(size, 1);
} else {
map.put(size, map.get(size) + 1);
}
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Histogram histogram = new Histogram();
}
});
}
}
I am trying to make a JPanel slide in from the side using this class i made:
public class AnimationClass {
private int i;
private int y;
private JPanel panel;
private int xTo;
private Timer timer;
private int xFrom;
synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;
panel.setSize(width, height);
timer = new Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
for (int i = xFrom; i > xTo; i--) {
panel.setLocation(i, y);
panel.repaint();
i--;
timer.stop();
timer.setDelay(100);
if (i >= xTo) {
timer.stop();
}
}
timer.stop();
}
});
timer.start();
}
}
Well, i dont know what the problem is. I've tried a lot of different things, but i doesn't seem like I can get it to work.
The timer should be changing the location on each tick, until it is in place, instead, on each tick, you're running through a for-next loop, which is blocking the EDT until the loop finishes, preventing from updating the UI
Update with example
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestAnimatedPane {
public static void main(String[] args) {
new TestAnimatedPane();
}
public TestAnimatedPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel panel;
public TestPane() {
setLayout(null);
panel = new JPanel();
panel.setBackground(Color.RED);
add(panel);
Dimension size = getPreferredSize();
Rectangle from = new Rectangle(size.width, (size.height - 50) / 2, 50, 50);
Rectangle to = new Rectangle((size.width - 50) / 2, (size.height - 50) / 2, 50, 50);
Animate animate = new Animate(panel, from, to);
animate.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public static class Animate {
public static final int RUN_TIME = 2000;
private JPanel panel;
private Rectangle from;
private Rectangle to;
private long startTime;
public Animate(JPanel panel, Rectangle from, Rectangle to) {
this.panel = panel;
this.from = from;
this.to = to;
}
public void start() {
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long duration = System.currentTimeMillis() - startTime;
double progress = (double)duration / (double)RUN_TIME;
if (progress > 1f) {
progress = 1f;
((Timer)e.getSource()).stop();
}
Rectangle target = calculateProgress(from, to, progress);
panel.setBounds(target);
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(0);
startTime = System.currentTimeMillis();
timer.start();
}
}
public static Rectangle calculateProgress(Rectangle startBounds, Rectangle targetBounds, double 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, double 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 int calculateProgress(int startValue, int endValue, double fraction) {
int value = 0;
int distance = endValue - startValue;
value = (int)Math.round((double)distance * fraction);
value += startValue;
return value;
}
public static Dimension calculateProgress(Dimension startSize, Dimension targetSize, double 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;
}
}
Update
I should have added this in last night (1 year who didn't want to go to bed, 2 parents that did, say no more...)
Animation is complex topic, especially when you start looking at variable speed (the example is static).
Instead of reinventing the wheel, you should seriously consider taking a look at...
Timing Framework - This is base animation framework, that makes no assumptions about how you might like to use it.
Trident - Similar to the Timing Framework, but also has support for Swing based components (via reflection) build in
Universal Tween Engine
This well-factored example easily admits the variation below. It leverages the enclosed panel's preferred size in a JLayeredPane.
/**
* #see https://stackoverflow.com/a/16322007/230513
* #see https://stackoverflow.com/a/16316345/230513
*/
public class TestPane extends JLayeredPane {
private static final int WIDE = 200;
private static final int HIGH = 5 * WIDE / 8; // ~1/phi
private JPanel panel;
public TestPane() {
panel = new JPanel();
panel.setBackground(Color.RED);
panel.add(new JButton("Test"));
add(panel);
Dimension size = panel.getPreferredSize();
int half = HIGH / 2 - size.height / 2;
Rectangle from = new Rectangle(size);
from.translate(WIDE, half);
Rectangle to = new Rectangle(size);
to.translate(0, half);
panel.setBounds(from);
Animate animate = new Animate(panel, from, to);
animate.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(WIDE, HIGH);
}
}
There are a number of problems in the OP's code. As MadProrammer points, should only be moving one step per timer tick. Here is a simple,tested correction to the OPs code which moves the JPanel one pixel at a time, 25 times a second. Note the comments:
synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;
panel.setSize(width, height);
// timer runs 25 times per second
timer = new Timer(40, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Must 'remember' where we have slid panel to by using instance variable rather than automatic variable
// Only move one step at a time.
// No need to restart timer, it continues to run until stopped
if (xFrom > xTo){
xFrom = xFrom - 1;
panel.setLocation(xFrom, y);
panel.repaint();
} else {
timer.stop();
}
panel.setLocation(xFrom, y);
panel.repaint();
}
});
timer.start();
}
example to slid Anything
package TestingPackage;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ToggleBtn extends JPanel {
JFrame frame;
JPanel panelOut;
JLabel labelOn;
JLabel labelOff;
JButton btn;
int count = 1;
public ToggleBtn() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(500, 300, 300, 300);
frame.setLayout(null);
panelOut = new JPanel(null);
panelOut.setBounds(50, 100, 120, 30);
panelOut.setBackground(Color.gray);
frame.add(panelOut);
btn = new JButton("::");
btn.setBounds(0, 0, 60, 30);
panelOut.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
startThread();
}
});
labelOn = new JLabel("ON");
labelOn.setBounds(0, 0, 60, 30);
panelOut.add(labelOn);
labelOff = new JLabel("OFF");
labelOff.setBounds(60, 0, 60, 30);
panelOut.add(labelOff);
frame.setVisible(true);
}
public void startThread() {
count++;
new Move().start();
}
public static void main(String[] args) {
new ToggleBtn();
}
class Move extends Thread {
#Override
public void run() {
if (count % 2 == 0) {
System.out.println("if");
for (int i = 0; i <= 60; i++) {
try {
Thread.sleep(3);
} catch (InterruptedException ex) {
Logger.getLogger(ToggleBtn.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setBounds(i, 0, 60, 30);
}
} else {
System.out.println("else");
for (int i = 60; i >= 0; i--) {
try {
Thread.sleep(3);
} catch (InterruptedException ex) {
Logger.getLogger(ToggleBtn.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setBounds(i, 0, 60, 30);
}
}
}
}
}