Show BarChar In JTable Column In Java - java

I have JTable in that I need to Show Chart but i have tired several Code but not able to achieve waht i wanted to make. here what i have tried so far
http://www.jroller.com/Thierry/entry/swing_barchart_rendering_in_a
and i want to achieve according to this image
but how ever i dont get any Render-er for same.
Please Any suggestion will be welcomed.

I would try 3 columns table. For the middle column I would use a custom renderer - a JPanel with JLabels on it. The labels could have different columns and sizes.
The TableModel should keep datasource for the bars and preparing renderer component means reading the cell value, extracting barchar data from the cell and setting colors/sizes for the JLabels in the JPanel (renderer component)

Okay, here's an idea...
Instead of using a JTable, you could create a layout manager which would calculate the offsets and allow for elements to overlap "columns"
Prototype example - !! DO NOT USE IN PRODUCTION !!
This is an EXAMPLE only and should be used to LEARN from, do not try using this in production, there is a lot that needs to improved, such as a proper event notification API
This example makes use of the JIDE Common Layer API (the JideScrollPane in particular), you can get a copy from here
import com.jidesoft.swing.JideScrollPane;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager2;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
public class WorkSheetReport {
public static final Color WORKING_HOURS_COLOR = new Color(93, 89, 88);
public static final Color LUNCH_HOURS_COLOR = new Color(215, 142, 27);
public static final Color OTHER_HOURS_COLOR = new Color(30, 141, 213);
public static void main(String[] args) {
new WorkSheetReport();
}
public WorkSheetReport() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultTimeSheetReport report = new DefaultTimeSheetReport();
report.add(createTimeSheet(
"NWD/Full"));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 12.5),
new DefaultTimeEntry(WorkType.LUNCH, 12.5, 13.25),
new DefaultTimeEntry(WorkType.WORK, 13.25, 18),
new DefaultTimeEntry(WorkType.OTHER, 18, 18.5),
new DefaultTimeEntry(WorkType.WORK, 18.5, 20.5)));
report.add(createTimeSheet(
"0.5UUPL",
new DefaultTimeEntry(WorkType.WORK, 10, 12.5),
new DefaultTimeEntry(WorkType.LUNCH, 12.5, 17.75),
new DefaultTimeEntry(WorkType.OTHER, 17.75, 18),
new DefaultTimeEntry(WorkType.WORK, 18, 20)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 11, 13),
new DefaultTimeEntry(WorkType.LUNCH, 13, 13.5),
new DefaultTimeEntry(WorkType.WORK, 13.5, 17.75),
new DefaultTimeEntry(WorkType.OTHER, 17.75, 18),
new DefaultTimeEntry(WorkType.WORK, 18, 20.5)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 12.75),
new DefaultTimeEntry(WorkType.LUNCH, 12.75, 13.5),
new DefaultTimeEntry(WorkType.WORK, 13.5, 17.5),
new DefaultTimeEntry(WorkType.OTHER, 17.5, 17.75),
new DefaultTimeEntry(WorkType.WORK, 17.75, 20.5)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 9.75, 12),
new DefaultTimeEntry(WorkType.LUNCH, 12, 12.5),
new DefaultTimeEntry(WorkType.WORK, 12.5, 17.25),
new DefaultTimeEntry(WorkType.OTHER, 17.25, 17.75),
new DefaultTimeEntry(WorkType.WORK, 17.75, 20)));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 11.75),
new DefaultTimeEntry(WorkType.LUNCH, 11.75, 12.25),
new DefaultTimeEntry(WorkType.WORK, 12.25, 17.5),
new DefaultTimeEntry(WorkType.OTHER, 17.5, 18),
new DefaultTimeEntry(WorkType.WORK, 18, 20.25)));
report.add(createTimeSheet(
"NWD/Full"));
report.add(createTimeSheet(
"Present",
new DefaultTimeEntry(WorkType.WORK, 10, 12.5),
new DefaultTimeEntry(WorkType.LUNCH, 12.5, 13.5),
new DefaultTimeEntry(WorkType.WORK, 13.5, 18),
new DefaultTimeEntry(WorkType.OTHER, 18, 18.5),
new DefaultTimeEntry(WorkType.WORK, 18.5, 20.5)));
TimeSheetReportPane pane = new TimeSheetReportPane(report);
JFrame frame = new JFrame("Testing");
frame.getContentPane().setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JideScrollPane sp = new JideScrollPane(pane);
sp.setColumnHeadersHeightUnified(true);
frame.add(sp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected TimeSheet createTimeSheet(String name, TimeEntry... entries) {
DefaultTimeSheet ts = new DefaultTimeSheet(name);
for (TimeEntry entry : entries) {
ts.add(entry);
}
return ts;
}
protected static String format(double time) {
time *= 60 * 60; // to seconds
int hours = (int) Math.floor(time / (60 * 60));
double remainder = time % (60 * 60);
int mins = (int) Math.floor(remainder / 60);
int secs = (int) Math.floor(time % 60);
return hours + ":" + mins + ":" + secs;
}
public class TimeSheetReportPane extends JPanel {
private TimeSheetReport report;
private int columnWidth;
private int rowHeight;
public TimeSheetReportPane(TimeSheetReport report) {
this.report = report;
setLayout(new GridBagLayout());
setBackground(Color.BLACK);
FontMetrics fm = getFontMetrics(UIManager.getFont("Label.font"));
columnWidth = fm.stringWidth("0000");
rowHeight = fm.getHeight() + 8;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 0, 1, 0);
int count = 0;
for (TimeSheet ts : report) {
Color color = getColorForSheet(count);
TimeSheetPane pane = new TimeSheetPane(this, ts);
pane.setBackground(color);
add(pane, gbc);
count++;
}
gbc.weighty = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
public Color getColorForSheet(int index) {
Color endColor = Color.GRAY;
Color startColor = Color.DARK_GRAY;
double progress = (double) index / (double) getReport().size();
return blend(startColor, endColor, progress);
}
public TimeSheetReport getReport() {
return report;
}
public int getRowHeight() {
return rowHeight;
}
public int getColumnWidth() {
return columnWidth;
}
#Override
public void addNotify() {
super.addNotify();
configureEnclosingScrollPane();
}
protected void configureEnclosingScrollPane() {
Container parent = getParent();
if (parent instanceof JViewport) {
JViewport viewport = (JViewport) parent;
parent = viewport.getParent();
if (parent instanceof JideScrollPane) {
JideScrollPane sp = (JideScrollPane) parent;
sp.setRowFooterView(new RowFooter(this));
}
if (parent instanceof JScrollPane) {
JScrollPane sp = (JScrollPane) parent;
JLabel leftHeader = new JLabel("Status");
leftHeader.setForeground(Color.WHITE);
leftHeader.setBackground(Color.BLACK);
leftHeader.setOpaque(true);
leftHeader.setHorizontalAlignment(JLabel.CENTER);
leftHeader.setVerticalAlignment(JLabel.TOP);
leftHeader.setBorder(new EdgeBorder(EdgeBorder.Edge.RIGHT, Color.WHITE, Color.BLACK));
sp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, leftHeader);
JLabel rightHeader = new JLabel("Working Hr");
rightHeader.setForeground(Color.WHITE);
rightHeader.setBackground(Color.BLACK);
rightHeader.setOpaque(true);
rightHeader.setHorizontalAlignment(JLabel.CENTER);
rightHeader.setBorder(new EdgeBorder(EdgeBorder.Edge.LEFT, Color.WHITE, Color.BLACK));
sp.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, rightHeader);
sp.setRowHeaderView(new RowHeader(this));
sp.setColumnHeaderView(new ColumnHeader(this));
}
}
}
}
public class ColumnHeader extends JPanel {
private TimeSheetReportPane reportPane;
public ColumnHeader(TimeSheetReportPane tsrp) {
reportPane = tsrp;
setBackground(Color.BLACK);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.ipady = 8;
Border border = new MatteBorder(0, 0, 0, 1, Color.GRAY);
for (int hour = 8; hour < 25; hour++) {
JLabel label = new JLabel(Integer.toString(hour)) {
#Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.width = reportPane.getColumnWidth();
return dim;
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
};
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(Color.WHITE);
label.setBorder(border);
add(label, gbc);
}
gbc.weightx = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
}
public class RowHeader extends JPanel {
private TimeSheetReportPane reportPane;
public RowHeader(TimeSheetReportPane tsrp) {
reportPane = tsrp;
setBackground(Color.BLACK);
setLayout(new GridBagLayout());
TimeSheetReport tsr = reportPane.getReport();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 16;
gbc.ipady = 2;
gbc.insets = new Insets(0, 0, 1, 0);
int index = 0;
for (TimeSheet ts : tsr) {
JLabel label = new JLabel(ts.getName()) {
#Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.height = reportPane.getRowHeight();
return dim;
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
};
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(Color.WHITE);
label.setBackground(reportPane.getColorForSheet(index));
label.setOpaque(true);
add(label, gbc);
index++;
}
gbc.weighty = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
}
public class RowFooter extends JPanel {
private TimeSheetReportPane reportPane;
public RowFooter(TimeSheetReportPane tsrp) {
reportPane = tsrp;
setBackground(Color.BLACK);
setLayout(new GridBagLayout());
TimeSheetReport tsr = reportPane.getReport();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 36;
gbc.ipady = 2;
gbc.insets = new Insets(0, 0, 1, 0);
int index = 0;
for (TimeSheet ts : tsr) {
double time = ts.getWorkingHours();
String workHrs = "";
if (time > 0) {
workHrs = format(time);
}
JLabel label = new JLabel(workHrs) {
#Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.height = reportPane.getRowHeight();
return dim;
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
};
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(Color.WHITE);
label.setBackground(reportPane.getColorForSheet(index));
label.setOpaque(true);
add(label, gbc);
index++;
}
gbc.weighty = 1;
JPanel fill = new JPanel();
fill.setOpaque(false);
add(fill, gbc);
}
}
public static class EdgeBorder implements Border {
public enum Edge {
LEFT,
RIGHT
}
private Edge edge;
private Color startColor;
private Color endColor;
public EdgeBorder(Edge edge, Color startColor, Color endColor) {
this.edge = edge;
this.startColor = startColor;
this.endColor = endColor;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
int xPos = x;
switch (edge) {
case RIGHT:
xPos = x + (width - 1);
}
LinearGradientPaint lgp = new LinearGradientPaint(
new Point(x, 0),
new Point(x, height),
new float[]{0, 1},
new Color[]{startColor, endColor});
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(lgp);
g2d.drawLine(xPos, y, xPos, y + height);
}
#Override
public Insets getBorderInsets(Component c) {
int left = edge == Edge.LEFT ? 1 : 0;
int right = edge == Edge.RIGHT ? 1 : 0;
return new Insets(0, left, 0, right);
}
#Override
public boolean isBorderOpaque() {
return false;
}
}
/**
* Blend two colors.
*
* #param color1 First color to blend.
* #param color2 Second color to blend.
* #param ratio Blend ratio. 0.5 will give even blend, 1.0 will return color1,
* 0.0 will return color2 and so on.
* #return Blended color.
*/
public static Color blend(Color color1, Color color2, double ratio) {
float r = (float) ratio;
float ir = (float) 1.0 - r;
float rgb1[] = new float[3];
float rgb2[] = new float[3];
color1.getColorComponents(rgb1);
color2.getColorComponents(rgb2);
float red = rgb1[0] * r + rgb2[0] * ir;
float green = rgb1[1] * r + rgb2[1] * ir;
float blue = rgb1[2] * r + rgb2[2] * ir;
if (red < 0) {
red = 0;
} else if (red > 255) {
red = 255;
}
if (green < 0) {
green = 0;
} else if (green > 255) {
green = 255;
}
if (blue < 0) {
blue = 0;
} else if (blue > 255) {
blue = 255;
}
Color color = null;
try {
color = new Color(red, green, blue);
} catch (IllegalArgumentException exp) {
exp.printStackTrace();
}
return color;
}
public class TimeSheetPane extends JPanel {
private final JPanel timeEntriesPane;
public TimeSheetPane(TimeSheetReportPane reportPane, TimeSheet ts) {
timeEntriesPane = new JPanel(new TimeSheetLayoutManager(reportPane.getColumnWidth(), reportPane.getRowHeight()));
timeEntriesPane.setBackground(Color.BLACK);
setBorder(new EmptyBorder(1, 0, 1, 0));
setLayout(new BorderLayout());
add(timeEntriesPane);
for (TimeEntry te : ts) {
JLabel label = createLabel(te.getType().getColor());
String startTime = format(te.getStartTime());
String duration = format(te.getDuration());
label.setToolTipText("<html>StartTime: " + startTime + "<br>Duration: " + duration);
timeEntriesPane.add(label, te);
}
}
protected JLabel createLabel(Color color) {
JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground(color);
return label;
}
}
public class TimeSheetLayoutManager implements LayoutManager2 {
private Map<Component, TimeEntry> mapConstraints;
private int colWidth;
private int rowHeight;
public TimeSheetLayoutManager(int colWidth, int rowHeight) {
mapConstraints = new HashMap<>(25);
this.colWidth = colWidth;
this.rowHeight = rowHeight;
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints instanceof TimeEntry) {
mapConstraints.put(comp, (TimeEntry) constraints);
} else {
throw new IllegalArgumentException(
constraints == null ? "Null is not a valid constraint"
: constraints.getClass().getName() + " is not a valid TimeEntry constraint"
);
}
}
#Override
public Dimension maximumLayoutSize(Container target) {
return preferredLayoutSize(target);
}
#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) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void removeLayoutComponent(Component comp) {
mapConstraints.remove(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
return new Dimension(colWidth * (24 - 8), rowHeight);
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
int width = parent.getWidth() - (insets.left + insets.right);
int height = rowHeight;
int hourWidth = colWidth;
int offset = 8;
for (Component comp : mapConstraints.keySet()) {
TimeEntry te = mapConstraints.get(comp);
double startTime = te.getStartTime();
double duration = te.getDuration();
startTime -= offset;
int x = (int) Math.round(startTime * hourWidth);
int unitWidth = (int) Math.round(duration * hourWidth);
comp.setLocation(x, insets.top);
comp.setSize(unitWidth, height);
}
}
}
public enum WorkType {
WORK(WORKING_HOURS_COLOR),
LUNCH(LUNCH_HOURS_COLOR),
OTHER(OTHER_HOURS_COLOR);
private Color color;
private WorkType(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
public interface TimeEntry {
public WorkType getType();
public double getStartTime();
public double getDuration();
}
public interface TimeSheet extends Iterable<TimeEntry> {
public String getName();
public int size();
public TimeEntry get(int index);
public double getWorkingHours();
}
public interface TimeSheetReport extends Iterable<TimeSheet> {
public int size();
public TimeSheet get(int index);
}
public class DefaultTimeEntry implements TimeEntry {
private final double startTime;
private final double endTime;
private final WorkType workType;
public DefaultTimeEntry(WorkType type, double startTime, double endTime) {
this.startTime = startTime;
this.endTime = endTime;
this.workType = type;
}
#Override
public double getStartTime() {
return startTime;
}
public double getEndTime() {
return endTime;
}
#Override
public double getDuration() {
return endTime - startTime;
}
#Override
public WorkType getType() {
return workType;
}
}
public class DefaultTimeSheet implements TimeSheet {
private final List<TimeEntry> timeEntries;
private final String name;
public DefaultTimeSheet(String name) {
this.name = name;
timeEntries = new ArrayList<>(25);
}
public TimeSheet add(TimeEntry te) {
timeEntries.add(te);
return this;
}
#Override
public Iterator<TimeEntry> iterator() {
return timeEntries.iterator();
}
#Override
public int size() {
return timeEntries.size();
}
#Override
public TimeEntry get(int index) {
return timeEntries.get(index);
}
#Override
public String getName() {
return name;
}
#Override
public double getWorkingHours() {
double time = 0;
for (TimeEntry te : this) {
switch (te.getType()) {
case WORK:
time += te.getDuration();
break;
}
}
return time;
}
}
public class DefaultTimeSheetReport implements TimeSheetReport {
private final List<TimeSheet> timeSheets;
public DefaultTimeSheetReport() {
timeSheets = new ArrayList<>(25);
}
public DefaultTimeSheetReport add(TimeSheet ts) {
timeSheets.add(ts);
return this;
}
#Override
public int size() {
return timeSheets.size();
}
#Override
public TimeSheet get(int index) {
return timeSheets.get(index);
}
#Override
public Iterator<TimeSheet> iterator() {
return timeSheets.iterator();
}
}
}

Related

How to make a spoiler in Swing (and why a simple solution is not working)

I'm trying to make a spoiler effect in Swing (like <summary>/<details> tag in HTML). However, if I toggle setVisible() method, the height of my parent containers is not calculated correctly.
All my parent containers of the panels that I'm trying to show and hide use BoxLayout with Page axis.
This is my code:
public class Entry extends javax.swing.JPanel {
public Entry() {
initComponents();
}
public Entry(Node node) {
this.node = node;
initComponents();
initEvents();
}
private void initEvents() {
marker.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
if (!opened) open();
else close();
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
});
addMouseListener(listener);
}
public void addChild(Entry child, int pos) {
content.add(child, pos);
//content.validate();
}
public void inflate(int width) {
if (node == null) return;
if (node.nodeType == 1) {
boolean isPaired = !TagLibrary.tags.containsKey(node.tagName.toLowerCase()) ||
TagLibrary.tags.get(node.tagName.toLowerCase());
if (!isPaired) {
headerTag.setText("<" + node.tagName.toLowerCase());
headerTag2.setText(" />");
threeDots.setText("");
headerTag3.setText("");
content.setVisible(false);
footer.setVisible(false);
marker.setVisible(false);
} else {
headerTag.setText("<" + node.tagName.toLowerCase());
headerTag2.setText(">");
headerTag3.setText("</" + node.tagName.toLowerCase() + ">");
footerTag.setText("</" + node.tagName.toLowerCase() + ">");
}
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
content.removeAll();
//System.out.println(getWidth());
for (int i = 0; i < node.children.size(); i++) {
Entry e = new Entry(node.children.get(i));
content.add(e);
e.inflate(w);
}
content.doLayout();
if (node.children.size() > 0) {
open();
} else {
close();
}
} else if (node.nodeType == 3 && !node.nodeValue.matches("\\s*")) {
content.removeAll();
header.setVisible(false);
footer.setVisible(false);
JTextArea textarea = new JTextArea();
textarea.setText(node.nodeValue);
textarea.setEditable(false);
textarea.setOpaque(false);
textarea.setBackground(new Color(255, 255, 255, 0));
textarea.setColumns(180);
textarea.setFont(new Font("Tahoma", Font.PLAIN, 16));
int rows = node.nodeValue.split("\n").length;
textarea.setRows(rows);
textarea.addMouseListener(listener);
int height = getFontMetrics(textarea.getFont()).getHeight() * rows;
content.add(textarea);
content.setOpaque(false);
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
((JPanel)getParent()).setMinimumSize(new Dimension(w, line_height * 2 + content.getPreferredSize().height));
opened = true;
content.validate();
} else {
setVisible(false);
content.removeAll();
opened = false;
return;
}
int w = Math.max(Math.max(Math.max(content.getMinimumSize().width, header.getMinimumSize().width), min_width), width - margin);
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
int height = line_height * 2 + content.getPreferredSize().height;
if (opened) {
setSize(w, height);
}
}
public void setWidth(int width) {
int w = Math.max(Math.max(header.getMinimumSize().width, min_width), width - margin);
setPreferredSize(new Dimension(w, getPreferredSize().height));
header.setMinimumSize(new Dimension(w, line_height));
footer.setMinimumSize(new Dimension(w, line_height));
content.setPreferredSize(new Dimension(w, content.getPreferredSize().height));
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry)c[i]).setWidth(w);
} else {
c[i].setSize(w, c[i].getMaximumSize().height);
c[i].setMaximumSize(new Dimension(w, c[i].getMaximumSize().height));
}
}
}
public static final int min_width = 280;
public static final int line_height = 26;
public static final int margin = 30;
MouseListener listener = new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {
updateChildren(true);
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
updateChildren(false);
repaint();
}
};
private void updateChildren(boolean value) {
hovered = value;
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry)c[i]).updateChildren(value);
}
}
}
#Override
public void paintComponent(Graphics g) {
if (hovered) {
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(190, 230, 255, 93));
g.fillRect(0, 0, getWidth(), getHeight());
} else {
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, getWidth(), getHeight());
}
//super.paintComponent(g);
}
private boolean hovered = false;
public void open() {
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle.png")));
threeDots.setVisible(false);
headerTag3.setVisible(false);
content.setVisible(true);
footer.setVisible(true);
opened = true;
//getParent().getParent().setPreferredSize(new Dimension(getParent().getPreferredSize().width, getParent().getPreferredSize().height + delta));
//getParent().getParent().setPreferredSize(new Dimension(getParent().getParent().getSize().width, getParent().getParent().getSize().height + delta));
//((JComponent)getParent()).validate();
}
public void close() {
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle2.png")));
content.setVisible(false);
footer.setVisible(false);
threeDots.setVisible(has_children);
marker.setVisible(has_children);
headerTag3.setVisible(true);
opened = false;
//getParent().setPreferredSize(new Dimension(getParent().getPreferredSize().width, getParent().getPreferredSize().height - delta));
//getParent().getParent().setPreferredSize(new Dimension(getParent().getParent().getSize().width, getParent().getParent().getSize().height - delta));
//((JComponent)getParent().getParent()).revalidate();
}
public void openAll() {
open();
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry) c[i]).openAll();
}
}
}
public void closeAll() {
close();
Component[] c = content.getComponents();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof Entry) {
((Entry) c[i]).closeAll();
}
}
}
public boolean opened = false;
public Node node;
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
header = new javax.swing.JPanel();
headerMargin = new javax.swing.JPanel();
marker = new javax.swing.JLabel();
headerTag = new javax.swing.JLabel();
attributes = new javax.swing.JPanel();
headerTag2 = new javax.swing.JLabel();
threeDots = new javax.swing.JLabel();
headerTag3 = new javax.swing.JLabel();
content = new javax.swing.JPanel();
footer = new javax.swing.JPanel();
footerMargin = new javax.swing.JPanel();
footerTag = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 255, 255));
setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));
header.setBackground(new java.awt.Color(255, 255, 255));
header.setAlignmentX(0.0F);
header.setMaximumSize(new java.awt.Dimension(32767, 26));
header.setMinimumSize(new java.awt.Dimension(280, 26));
header.setOpaque(false);
header.setPreferredSize(new java.awt.Dimension(280, 26));
header.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 0, 2));
headerMargin.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 0, 5));
headerMargin.setMaximumSize(new java.awt.Dimension(30, 26));
headerMargin.setOpaque(false);
headerMargin.setPreferredSize(new java.awt.Dimension(30, 26));
marker.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle.png"))); // NOI18N
marker.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
marker.setPreferredSize(new java.awt.Dimension(22, 22));
javax.swing.GroupLayout headerMarginLayout = new javax.swing.GroupLayout(headerMargin);
headerMargin.setLayout(headerMarginLayout);
headerMarginLayout.setHorizontalGroup(
headerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerMarginLayout.createSequentialGroup()
.addComponent(marker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
headerMarginLayout.setVerticalGroup(
headerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerMarginLayout.createSequentialGroup()
.addComponent(marker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
header.add(headerMargin);
headerTag.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag.setForeground(new java.awt.Color(102, 0, 153));
headerTag.setText("<body");
header.add(headerTag);
attributes.setMaximumSize(new java.awt.Dimension(32767, 26));
attributes.setOpaque(false);
attributes.setPreferredSize(new java.awt.Dimension(0, 26));
attributes.setLayout(new javax.swing.BoxLayout(attributes, javax.swing.BoxLayout.LINE_AXIS));
header.add(attributes);
headerTag2.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag2.setForeground(new java.awt.Color(102, 0, 153));
headerTag2.setText(">");
header.add(headerTag2);
threeDots.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
threeDots.setText("...");
threeDots.setPreferredSize(new java.awt.Dimension(19, 20));
header.add(threeDots);
headerTag3.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
headerTag3.setForeground(new java.awt.Color(102, 0, 153));
headerTag3.setText("</body>");
header.add(headerTag3);
add(header);
content.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 30, 0, 0));
content.setAlignmentX(0.0F);
content.setOpaque(false);
content.setLayout(new javax.swing.BoxLayout(content, javax.swing.BoxLayout.PAGE_AXIS));
add(content);
footer.setBackground(new java.awt.Color(255, 255, 255));
footer.setAlignmentX(0.0F);
footer.setMaximumSize(new java.awt.Dimension(32767, 26));
footer.setOpaque(false);
footer.setPreferredSize(new java.awt.Dimension(91, 26));
footer.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 0, 2));
footerMargin.setOpaque(false);
footerMargin.setPreferredSize(new java.awt.Dimension(30, 26));
javax.swing.GroupLayout footerMarginLayout = new javax.swing.GroupLayout(footerMargin);
footerMargin.setLayout(footerMarginLayout);
footerMarginLayout.setHorizontalGroup(
footerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 30, Short.MAX_VALUE)
);
footerMarginLayout.setVerticalGroup(
footerMarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 26, Short.MAX_VALUE)
);
footer.add(footerMargin);
footerTag.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
footerTag.setForeground(new java.awt.Color(102, 0, 153));
footerTag.setText("</body>");
footer.add(footerTag);
add(footer);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JPanel attributes;
private javax.swing.JPanel content;
private javax.swing.JPanel footer;
private javax.swing.JPanel footerMargin;
private javax.swing.JLabel footerTag;
private javax.swing.JPanel header;
private javax.swing.JPanel headerMargin;
private javax.swing.JLabel headerTag;
private javax.swing.JLabel headerTag2;
private javax.swing.JLabel headerTag3;
private javax.swing.JLabel marker;
private javax.swing.JLabel threeDots;
// End of variables declaration
}
public class Node {
public Node() {}
public Node(Node parent_node) {
if (parent_node.nodeType == 1) {
parent = parent_node;
parent_node.addChild(this);
}
}
public Node(int node_type) {
nodeType = node_type;
}
public Node(Node parent_node, int node_type) {
if (parent_node.nodeType == 1) {
parent = parent_node;
parent_node.addChild(this);
}
nodeType = node_type;
}
public boolean addChild(Node node) {
if (nodeType == 1) {
children.add(node);
return true;
}
return false;
}
public Node parent;
public Vector<Node> children = new Vector<Node>();
public LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>();
public Node previousSibling;
public Node nextSibling;
public String tagName = "";
public int nodeType = 3;
public String nodeValue = "";
}
public class TagLibrary {
public static void init() {
if (init) return;
tags.put("br", false);
tags.put("hr", false);
tags.put("link", false);
tags.put("img", false);
tags.put("a", true);
tags.put("span", true);
tags.put("div", true);
tags.put("p", true);
tags.put("sub", true);
tags.put("sup", true);
tags.put("b", true);
tags.put("i", true);
tags.put("u", true);
tags.put("s", true);
tags.put("strong", true);
tags.put("em", true);
tags.put("quote", true);
tags.put("cite", true);
tags.put("table", true);
tags.put("thead", true);
tags.put("tbody", true);
tags.put("cite", true);
tags.put("head", true);
tags.put("body", true);
leaves.add("style");
leaves.add("script");
init = true;
}
private static boolean init = false;
public static Hashtable<String, Boolean> tags = new Hashtable<String, Boolean>();
public static Vector<String> leaves = new Vector<String>();
}
Main class:
public class WebInspectorTest {
private static Node prepareTree() {
Node root = new Node(1);
root.tagName = "body";
Node p = new Node(root, 1);
p.tagName = "p";
Node text1 = new Node(p, 3);
text1.nodeValue = "This is a ";
Node i = new Node(p, 1);
i.tagName = "i";
Node text2 = new Node(i, 3);
text2.nodeValue = "paragraph";
return root;
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {}
final Node root = prepareTree();
if (root == null) return;
final JFrame frame = new JFrame("Document Inspector");
JPanel cp = new JPanel();
cp.setBorder(BorderFactory.createEmptyBorder(9, 10, 9, 10));
frame.setContentPane(cp);
cp.setLayout(new BorderLayout());
final JPanel contentpane = new JPanel();
contentpane.setBackground(Color.WHITE);
contentpane.setOpaque(true);
final int width = 490, height = 418;
final JScrollPane scrollpane = new JScrollPane(contentpane);
scrollpane.setOpaque(false);
scrollpane.getInsets();
cp.add(scrollpane);
scrollpane.setBackground(Color.WHITE);
scrollpane.setOpaque(true);
scrollpane.setPreferredSize(new Dimension(width, height));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TagLibrary.init();
final Entry rootEntry = new Entry(root);
contentpane.add(rootEntry);
final JScrollPane sp = scrollpane;
int width = sp.getVerticalScrollBar().isVisible() ? sp.getWidth() - sp.getVerticalScrollBar().getPreferredSize().width - 12 : sp.getWidth() + sp.getVerticalScrollBar().getPreferredSize().width;
rootEntry.inflate(width);
contentpane.addComponentListener(new java.awt.event.ComponentAdapter() {
#Override
public void componentMoved(java.awt.event.ComponentEvent evt) {}
#Override
public void componentResized(java.awt.event.ComponentEvent evt) {
int width = sp.getVerticalScrollBar().isVisible() ? sp.getWidth() - sp.getVerticalScrollBar().getPreferredSize().width - 12 : sp.getWidth() - 12;
rootEntry.setWidth(width);
}
});
}
});
}
}
What is wrong here? I tried setting the new size of the immediate parent directly, that does not help the situation.
Calling revalidate() on the parents does not change anything, too.
To see the effect you can click on a triangle on the left from the first letter in any text line (I can't attach image files here, triangle and triangle2 are two copies of a small 10x10 solid filled blue triangle looking down and right, respectively).
If you try to close the root, it will not open correctly anymore. Also, after the root is close, it gets moved to the center of the parent JScrollPane.
UPDATE:
Here is the updated code that seems to fix the "jumping root to center" problem and to fix the minimize/maximize behavior in general. But, the <i> element is still jumping around when being toggled.
public void open() {
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle.png")));
threeDots.setVisible(false);
headerTag3.setVisible(false);
content.setVisible(true);
footer.setVisible(true);
opened = true;
int w = Math.max(Math.max(content.getMinimumSize().width, header.getMinimumSize().width), min_width);
int height = opened ? line_height * 2 + content.getPreferredSize().height : line_height;
if (content.getMinimumSize().height > content.getPreferredSize().height) {
content.setPreferredSize(content.getMinimumSize());
}
setSize(w, height);
setPreferredSize(null);
}
public void close() {
int delta = line_height + content.getPreferredSize().height;
marker.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/triangle2.png")));
content.setVisible(false);
footer.setVisible(false);
boolean has_children = node.children.size() > 0;
threeDots.setVisible(has_children);
marker.setVisible(has_children);
headerTag3.setVisible(true);
opened = false;
int w = Math.max(getParent().getSize().width, Math.max(Math.max(content.getMinimumSize().width, header.getMinimumSize().width), min_width));
int height = opened ? line_height * 2 + content.getPreferredSize().height : line_height;
setSize(w, height);
if (getParent().getParent() instanceof Entry) {
getParent().setSize(new Dimension(getParent().getPreferredSize().width, getParent().getPreferredSize().height - delta));
} else {
setPreferredSize(new Dimension(w, height));
}
}
UPDATE 2: Seems that the "root entry centering" problem can be fixed another way: I can just set Layout Manager of my root panel inside JScrollPane to null. It also fixes the need to make strange manipulations in resize handler method, where I was substracting empirically found 12 number from the new width to keep the scrolling off when it is not really needed.
But again, the jumping on toggle elements in the middle are still there.
UPDATE 3: I wrote my own very simple layout manager, but it is still not working correctly. In fact it works even worse than BoxLayout. I don't understand, why.
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
public class LinearLayout implements LayoutManager {
public LinearLayout() {
this(X_AXIS);
}
public LinearLayout(int direction) {
this.direction = direction;
}
public LinearLayout(int direction, int gap) {
this.direction = direction;
this.gap = gap;
}
#Override
public void addLayoutComponent(String name, Component comp) {}
#Override
public void removeLayoutComponent(Component comp) {}
#Override
public Dimension preferredLayoutSize(Container parent) {
int width = 0;
int height = 0;
Insets insets = parent.getInsets();
Component[] c = parent.getComponents();
if (direction == X_AXIS) {
for (int i = 0; i < c.length; i++) {
if (c[i].getSize().height > height) {
height = c[i].getSize().height;
}
width += c[i].getSize().width + gap;
}
} else {
for (int i = 0; i < c.length; i++) {
if (c[i].getSize().width > width) {
width = c[i].getSize().width;
}
height += c[i].getSize().height + gap;
}
}
width += insets.left + insets.right;
height += insets.top + insets.bottom;
return new Dimension(width, height);
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
Dimension dim = preferredLayoutSize(parent);
Component[] c = parent.getComponents();
Insets insets = parent.getInsets();
int x = insets.left;
int y = insets.top;
for (int i = 0; i < c.length; i++) {
if (direction == X_AXIS) {
c[i].setBounds(x, y, c[i].getSize().width, dim.height);
x += c[i].getSize().width + gap;
} else {
c[i].setBounds(x, y, dim.width, c[i].getSize().height);
y += c[i].getSize().height + gap;
}
}
}
private int direction = 0;
private int gap = 0;
public static final int X_AXIS = 0;
public static final int Y_AXIS = 1;
}
It seems that, as people in the comments said, I should had defined my own sizing methods (getPreferredSize/getMinimumdSize/getMaximumSize) implementation. I implemented them for some of my panels and the problem was solved.

A simple 3x3 Dice Game in Java

I'm creating a dice game where 2 players have their own dice, each has his own turn to throw his dice , players can either lose the score entirely or gain score depending on where they stand on the window , and the game ends when any player stands on the finish lane first , the winner is the player with the highest score, I've worked on the design of the game so far but haven't worked on the logic yet.
This link is a picture of how the game should look like :
I would like to know how can I add the player 1 and player 2 as in the photo above on each tile , so basically every time time a player plays his turn ,I want his name to start moving depending on the number he gets when he throws the dice.
Code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class diceGame {
public static void main(String[] args) {
new RollDicePanel();
}
}
class RollDicePanel extends JFrame {
private Dice myLeftDie;
private Dice myRightDie;
JPanel mainPanel;
JPanel topLeft,topCenter,topRight;
JPanel centerLeft,centerCenter,centerRight;
JPanel bottomLeft,bottomCenter,bottomRight;
JLabel tLeft,tRight,tCenter,cLeft,cCenter1,cCenter2,cRight,bLeft,bCenter,bRight;
RollDicePanel() {
myLeftDie = new Dice();
myRightDie = new Dice();
JButton rollButton1 = new JButton("Player 1");
rollButton1.setFont(new Font("Sansserif", Font.BOLD, 5));
rollButton1.addActionListener(new RollListener1());
JButton rollButton2 = new JButton("Player 2");
rollButton2.setFont(new Font("Sansserif", Font.BOLD, 5));
rollButton2.addActionListener(new RollListener2());
topLeft = new JPanel();
tLeft = new JLabel("+20");
tLeft.setFont(new Font("Sansserif", Font.BOLD, 20));
tLeft.setLayout(new FlowLayout(FlowLayout.CENTER));
topLeft.add(tLeft,BorderLayout.WEST);
topLeft.setBackground(Color.RED);
topRight = new JPanel();
tRight = new JLabel("-50");
tRight.setFont(new Font("Sansserif", Font.BOLD, 20));
topRight.add(tRight,BorderLayout.EAST);
topRight.setBackground(Color.ORANGE);
topCenter = new JPanel();
tCenter = new JLabel("Try Again");
tCenter.setFont(new Font("Sansserif", Font.BOLD, 20));
topCenter.add(tCenter,BorderLayout.CENTER);
topCenter.setBackground(Color.BLUE);
centerCenter = new JPanel();
cCenter1 = new JLabel("Player 1");
cCenter2 = new JLabel("Player 2");
centerCenter.add(rollButton1,BorderLayout.NORTH);
centerCenter.add(myLeftDie,BorderLayout.SOUTH);
centerCenter.add(rollButton2,BorderLayout.NORTH);
centerCenter.add(myRightDie,BorderLayout.EAST);
centerLeft = new JPanel();
cLeft = new JLabel("Finish");
cLeft.setFont(new Font("Sansserif", Font.BOLD, 20));
centerLeft.add(cLeft,BorderLayout.WEST);
centerLeft.setBackground(Color.YELLOW);
centerRight = new JPanel();
cRight = new JLabel("Lost All");
cRight.setFont(new Font("Sansserif", Font.BOLD, 20));
centerRight.add(cRight,BorderLayout.EAST);
centerRight.setBackground(Color.GREEN);
bottomRight = new JPanel();
bRight = new JLabel("+30");
bRight.setFont(new Font("Sansserif", Font.BOLD, 20));
bottomRight.add(bRight,BorderLayout.EAST);
bottomRight.setBackground(Color.CYAN);
bottomCenter = new JPanel();
bCenter = new JLabel("+10");
bCenter.setFont(new Font("Sansserif", Font.BOLD, 20));
bottomCenter.add(bCenter,BorderLayout.CENTER);
bottomCenter.setBackground(Color.magenta);
bottomLeft = new JPanel();
bLeft = new JLabel("-10");
bLeft.setFont(new Font("Sansserif", Font.BOLD, 20));
bLeft.setForeground(Color.WHITE);
bottomLeft.add(bLeft,BorderLayout.WEST);
bottomLeft.setBackground(Color.BLACK);
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(3,3));
mainPanel.add(topLeft,BorderLayout.NORTH);
mainPanel.add(topCenter,BorderLayout.NORTH);
mainPanel.add(topRight,BorderLayout.NORTH);
mainPanel.add(centerLeft,BorderLayout.CENTER);
mainPanel.add(centerCenter,BorderLayout.CENTER);
mainPanel.add(centerRight,BorderLayout.CENTER);
mainPanel.add(bottomLeft,BorderLayout.SOUTH);
mainPanel.add(bottomCenter,BorderLayout.SOUTH);
mainPanel.add(bottomRight,BorderLayout.SOUTH);
this.setTitle("Dice Game");
this.setBounds(200, 200, 700, 700);
this.add(mainPanel);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
private class RollListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
myLeftDie.roll();
}
}
private class RollListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
myRightDie.roll();
}
}
}
class Dice extends JPanel {
private static final int SPOT_DIAMETER = 4;
private int myFaceValue;
public Dice() {
setBackground(Color.white);
setPreferredSize(new Dimension(15,15));
roll();
}
int roll() {
int val = (int)(6*Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return myFaceValue;
}
public void setValue(int spots) {
myFaceValue = spots;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
g.drawRect(0, 0, w-1, h-1);
switch (myFaceValue) {
case 1: drawSpot(g, w/2, h/2);
break;
case 3: drawSpot(g, w/2, h/2);
case 2: drawSpot(g, w/4, h/4);
drawSpot(g, 3*w/4, 3*h/4);
break;
case 5: drawSpot(g, w/2, h/2);
case 4: drawSpot(g, w/4, h/4);
drawSpot(g, 3*w/4, 3*h/4);
drawSpot(g, 3*w/4, h/4);
drawSpot(g, w/4, 3*h/4);
break;
case 6: drawSpot(g, w/4, h/4);
drawSpot(g, 3*w/4, 3*h/4);
drawSpot(g, 3*w/4, h/4);
drawSpot(g, w/4, 3*h/4);
drawSpot(g, w/4, h/2);
drawSpot(g, 3*w/4, h/2);
break;
}
}
private void drawSpot(Graphics g, int x, int y) {
g.fillOval(x-SPOT_DIAMETER/2, y-SPOT_DIAMETER/2, SPOT_DIAMETER, SPOT_DIAMETER);
}
}
I fixed up your GUI.
I started your GUI with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
I created the JFrame in your class constructor. I created an outer JPanel, eight inner JPanels, and a center JPanel. The JFrame methods must be executed in a specific order. This is the order I use for my Swing GUIs.
The outer JPanel uses a GridLayout to organize the inner JPanels. The eight inner JPanels are similar, so I used a method to create them.
The center JPanel uses a GridBagLayout to organize the JButtons and die images.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DiceGame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RollDicePanel();
}
});
}
}
class RollDicePanel extends JFrame {
private static final long serialVersionUID = 1L;
private Dice myLeftDie;
private Dice myRightDie;
public RollDicePanel() {
this.setTitle("Dice Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(createOuterPanel(), BorderLayout.CENTER);
this.pack();
this.setLocationByPlatform(true);
this.setVisible(true);
}
private JPanel createOuterPanel() {
JPanel panel = new JPanel(new GridLayout(0, 3));
panel.add(createInnerPanel("+20", new Color(152, 254, 152),
Color.BLACK));
panel.add(createInnerPanel("Try Again...", new Color(252, 252, 201),
Color.BLACK));
panel.add(createInnerPanel("-50", new Color(254, 152, 152),
Color.BLACK));
panel.add(createInnerPanel("Finish!",new Color(0, 203, 101),
Color.BLACK));
panel.add(createCenterPanel());
panel.add(createInnerPanel("Lost All",new Color(252, 48, 99),
Color.BLACK));
panel.add(createInnerPanel("-10", new Color(254, 203, 203),
Color.BLACK));
panel.add(createInnerPanel("+10", new Color(203, 254, 203),
Color.BLACK));
panel.add(createInnerPanel("+30", new Color(49, 253, 0),
Color.BLACK));
return panel;
}
private JPanel createInnerPanel(String text, Color backgroundColor,
Color foregroundColor) {
JPanel panel = new JPanel();
panel.setBackground(backgroundColor);
JLabel label = new JLabel(text);
label.setFont(new Font("Sansserif", Font.BOLD, 20));
label.setForeground(foregroundColor);
panel.add(label);
return panel;
}
private JPanel createCenterPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
JButton rollButton1 = new JButton("Player 1");
rollButton1.setFont(new Font("Sansserif", Font.BOLD, 10));
rollButton1.addActionListener(new RollListener1());
panel.add(rollButton1, gbc);
gbc.gridx++;
JButton rollButton2 = new JButton("Player 2");
rollButton2.setFont(new Font("Sansserif", Font.BOLD, 10));
rollButton2.addActionListener(new RollListener2());
panel.add(rollButton2, gbc);
gbc.gridx = 0;
gbc.gridy++;
myLeftDie = new Dice();
panel.add(myLeftDie, gbc);
gbc.gridx++;
myRightDie = new Dice();
panel.add(myRightDie, gbc);
return panel;
}
private class RollListener1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
myLeftDie.roll();
}
}
private class RollListener2 implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
myRightDie.roll();
}
}
}
class Dice extends JPanel {
private static final long serialVersionUID = 1L;
private static final int SPOT_DIAMETER = 4;
private int myFaceValue;
public Dice() {
setBackground(Color.white);
setPreferredSize(new Dimension(15, 15));
roll();
}
int roll() {
int val = (int) (6 * Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return myFaceValue;
}
public void setValue(int spots) {
myFaceValue = spots;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
g.drawRect(0, 0, w - 1, h - 1);
switch (myFaceValue) {
case 1:
drawSpot(g, w / 2, h / 2);
break;
case 3:
drawSpot(g, w / 2, h / 2);
case 2:
drawSpot(g, w / 4, h / 4);
drawSpot(g, 3 * w / 4, 3 * h / 4);
break;
case 5:
drawSpot(g, w / 2, h / 2);
case 4:
drawSpot(g, w / 4, h / 4);
drawSpot(g, 3 * w / 4, 3 * h / 4);
drawSpot(g, 3 * w / 4, h / 4);
drawSpot(g, w / 4, 3 * h / 4);
break;
case 6:
drawSpot(g, w / 4, h / 4);
drawSpot(g, 3 * w / 4, 3 * h / 4);
drawSpot(g, 3 * w / 4, h / 4);
drawSpot(g, w / 4, 3 * h / 4);
drawSpot(g, w / 4, h / 2);
drawSpot(g, 3 * w / 4, h / 2);
break;
}
}
private void drawSpot(Graphics g, int x, int y) {
g.fillOval(x - SPOT_DIAMETER / 2, y - SPOT_DIAMETER / 2,
SPOT_DIAMETER, SPOT_DIAMETER);
}
}
Update 1
I went ahead and finished the game.
I created a logical model to hold the board squares and the player positions and score for player 1 and player 2.
I modified the view to use the logical model.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class DiceGame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RollDicePanel();
}
});
}
}
class RollDicePanel extends JFrame {
private static final long serialVersionUID = 1L;
private final DiceGameModel model;
private Dice myLeftDie;
private Dice myRightDie;
private InnerSquarePanel[] innerPanels;
private JTextField scoreField1;
private JTextField scoreField2;
public RollDicePanel() {
this.model = new DiceGameModel();
this.setTitle("Dice Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(createOuterPanel(), BorderLayout.CENTER);
this.pack();
this.setLocationByPlatform(true);
this.setVisible(true);
}
private JPanel createOuterPanel() {
int length = model.getBoardSquares().size();
this.innerPanels = new InnerSquarePanel[length];
for (int index = 0; index < length; index++) {
innerPanels[index] = new InnerSquarePanel(
model.getBoardSquares().get(index));
}
JPanel panel = new JPanel(new GridLayout(0, 3));
panel.add(innerPanels[1].getPanel());
panel.add(innerPanels[2].getPanel());
panel.add(innerPanels[3].getPanel());
panel.add(innerPanels[0].getPanel());
panel.add(createCenterPanel());
panel.add(innerPanels[4].getPanel());
panel.add(innerPanels[7].getPanel());
panel.add(innerPanels[6].getPanel());
panel.add(innerPanels[5].getPanel());
innerPanels[0].getPlayer1Label().setText("Player 1");
innerPanels[0].getPlayer2Label().setText("Player 2");
return panel;
}
private JPanel createCenterPanel() {
JPanel panel = new JPanel(new GridBagLayout());
Font font = new Font("Arial", Font.BOLD, 12);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
JButton rollButton1 = new JButton("Player 1");
rollButton1.setFont(font);
rollButton1.addActionListener(new RollListener1());
panel.add(rollButton1, gbc);
gbc.gridx++;
JButton rollButton2 = new JButton("Player 2");
rollButton2.setFont(font);
rollButton2.addActionListener(new RollListener2());
panel.add(rollButton2, gbc);
gbc.gridx = 0;
gbc.gridy++;
myLeftDie = new Dice();
panel.add(myLeftDie, gbc);
gbc.gridx++;
myRightDie = new Dice();
panel.add(myRightDie, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel label = new JLabel("Score");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
label = new JLabel("Score");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx = 0;
gbc.gridy++;
scoreField1 = new JTextField(4);
scoreField1.setEditable(false);
scoreField1.setFont(font);
scoreField1.setHorizontalAlignment(JTextField.CENTER);
panel.add(scoreField1, gbc);
gbc.gridx++;
scoreField2 = new JTextField(4);
scoreField2.setEditable(false);
scoreField2.setFont(font);
scoreField2.setHorizontalAlignment(JTextField.CENTER);
panel.add(scoreField2, gbc);
return panel;
}
private class RollListener1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
int position = model.getPlayer1position();
int roll = myLeftDie.roll();
model.incrementPlayer1position(roll);
BoardSquare boardSquare = model.getBoardSquares().get(
model.getPlayer1position());
int score = boardSquare.execute(model.getPlayer1score());
model.setPlayer1score(score);
innerPanels[position].getPlayer1Label().setText(" ");
innerPanels[model.getPlayer1position()].getPlayer1Label().
setText("Player 1");
scoreField1.setText(Integer.toString(score));
}
}
private class RollListener2 implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
int position = model.getPlayer2position();
int roll = myRightDie.roll();
model.incrementPlayer2position(roll);
BoardSquare boardSquare = model.getBoardSquares().get(
model.getPlayer2position());
int score = boardSquare.execute(model.getPlayer2score());
model.setPlayer2score(score);
innerPanels[position].getPlayer2Label().setText(" ");
innerPanels[model.getPlayer2position()].getPlayer2Label().
setText("Player 2");
scoreField2.setText(Integer.toString(score));
}
}
}
class Dice extends JPanel {
private static final long serialVersionUID = 1L;
private static final int SPOT_DIAMETER = 4;
private int myFaceValue;
public Dice() {
setBackground(Color.white);
setPreferredSize(new Dimension(15, 15));
roll();
}
int roll() {
int val = (int) (6 * Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return myFaceValue;
}
public void setValue(int spots) {
myFaceValue = spots;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
g.drawRect(0, 0, w - 1, h - 1);
switch (myFaceValue) {
case 1:
drawSpot(g, w / 2, h / 2);
break;
case 3:
drawSpot(g, w / 2, h / 2);
case 2:
drawSpot(g, w / 4, h / 4);
drawSpot(g, 3 * w / 4, 3 * h / 4);
break;
case 5:
drawSpot(g, w / 2, h / 2);
case 4:
drawSpot(g, w / 4, h / 4);
drawSpot(g, 3 * w / 4, 3 * h / 4);
drawSpot(g, 3 * w / 4, h / 4);
drawSpot(g, w / 4, 3 * h / 4);
break;
case 6:
drawSpot(g, w / 4, h / 4);
drawSpot(g, 3 * w / 4, 3 * h / 4);
drawSpot(g, 3 * w / 4, h / 4);
drawSpot(g, w / 4, 3 * h / 4);
drawSpot(g, w / 4, h / 2);
drawSpot(g, 3 * w / 4, h / 2);
break;
}
}
private void drawSpot(Graphics g, int x, int y) {
g.fillOval(x - SPOT_DIAMETER / 2, y - SPOT_DIAMETER / 2,
SPOT_DIAMETER, SPOT_DIAMETER);
}
}
class InnerSquarePanel {
private JLabel player1Label;
private JLabel player2Label;
private final JPanel panel;
public InnerSquarePanel(BoardSquare boardSquare) {
this.panel = createInnerPanel(boardSquare);
}
private JPanel createInnerPanel(BoardSquare boardSquare) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(boardSquare.getBackgroundColor());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 10 ,10);
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel(boardSquare.getText());
label.setFont(new Font("Arial", Font.BOLD, 24));
label.setForeground(boardSquare.getForegroundColor());
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridwidth = 1;
gbc.gridy++;
player1Label = new JLabel(" ");
player1Label.setForeground(boardSquare.getForegroundColor());
player1Label.setHorizontalAlignment(JLabel.LEADING);
player1Label.setVerticalAlignment(JLabel.BOTTOM);
panel.add(player1Label, gbc);
gbc.anchor = GridBagConstraints.LINE_END;
gbc.gridx++;
player2Label = new JLabel(" ");
player2Label.setForeground(boardSquare.getForegroundColor());
player2Label.setHorizontalAlignment(JLabel.TRAILING);
player2Label.setVerticalAlignment(JLabel.BOTTOM);
panel.add(player2Label, gbc);
return panel;
}
public JLabel getPlayer1Label() {
return player1Label;
}
public JLabel getPlayer2Label() {
return player2Label;
}
public JPanel getPanel() {
return panel;
}
}
class DiceGameModel {
private int player1position;
private int player2position;
private int player1score;
private int player2score;
private final List<BoardSquare> boardSquares;
public DiceGameModel() {
this.player1position = 0;
this.player2position = 0;
this.player1score = 0;
this.player2score = 0;
this.boardSquares = new ArrayList<>();
boardSquares.add(new FinishSquare());
boardSquares.add(new Square1());
boardSquares.add(new Square2());
boardSquares.add(new Square3());
boardSquares.add(new Square4());
boardSquares.add(new Square5());
boardSquares.add(new Square6());
boardSquares.add(new Square7());
}
public int getPlayer1position() {
return player1position;
}
public void incrementPlayer1position(int increment) {
this.player1position = (player1position + increment) %
boardSquares.size();
}
public int getPlayer2position() {
return player2position;
}
public void incrementPlayer2position(int increment) {
this.player2position = (player2position + increment) %
boardSquares.size();
}
public int getPlayer1score() {
return player1score;
}
public void setPlayer1score(int player1score) {
this.player1score = player1score;
}
public int getPlayer2score() {
return player2score;
}
public void setPlayer2score(int player2score) {
this.player2score = player2score;
}
public List<BoardSquare> getBoardSquares() {
return boardSquares;
}
}
class FinishSquare extends BoardSquare {
public FinishSquare() {
super("Finish!", 0, new Color(0, 203, 101), Color.WHITE);
}
#Override
public int execute(int score) {
return score;
}
}
class Square1 extends BoardSquare {
public Square1() {
super("+20", 1, new Color(152, 254, 152), Color.BLACK);
}
#Override
public int execute(int score) {
return score + 20;
}
}
class Square2 extends BoardSquare {
public Square2() {
super("Try Again", 2, new Color(252, 252, 201), Color.BLACK);
}
#Override
public int execute(int score) {
return score;
}
}
class Square3 extends BoardSquare {
public Square3() {
super("-50", 3, new Color(254, 152, 152), Color.BLACK);
}
#Override
public int execute(int score) {
return score - 50;
}
}
class Square4 extends BoardSquare {
public Square4() {
super("Lost All", 4, new Color(252, 48, 99), Color.WHITE);
}
#Override
public int execute(int score) {
return 0;
}
}
class Square5 extends BoardSquare {
public Square5() {
super("+30", 5, new Color(49, 253, 0), Color.BLACK);
}
#Override
public int execute(int score) {
return score + 30;
}
}
class Square6 extends BoardSquare {
public Square6() {
super("+10", 6, new Color(203, 254, 203), Color.BLACK);
}
#Override
public int execute(int score) {
return score + 10;
}
}
class Square7 extends BoardSquare {
public Square7() {
super("-10", 7, new Color(254, 203, 203), Color.BLACK);
}
#Override
public int execute(int score) {
return score - 10;
}
}
abstract class BoardSquare {
private final int position;
private final Color backgroundColor;
private final Color foregroundColor;
private final String text;
public BoardSquare(String text, int position,
Color backgroundColor, Color foregroundColor) {
this.text = text;
this.position = position;
this.backgroundColor = backgroundColor;
this.foregroundColor = foregroundColor;
}
public abstract int execute(int score);
public int getPosition() {
return position;
}
public String getText() {
return text;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public Color getForegroundColor() {
return foregroundColor;
}
}

Can't move JLabel on JPanel

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

setBounds not displaying the component in JPanel

I have created my own layout manager for JPanel. In the layout container method of layout manager, I added three components only first two are getting displayed. Am I missing something? Here is the code for layout manager.
package com.indigo.neuron.gui.bandtrades.symbollist.orderentry.strategy;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import com.indigo.neuron.gui.bandtrades.layouts.LayoutConstants;
import com.indigo.neuron.gui.bandtrades.symbollist.SymbolPanel;
import com.indigo.neuron.gui.bandtrades.symbollist.orderentry.QuantityFieldPanel;
import com.indigo.neuron.gui.bandtrades.utils.MapUtils;
import com.indigo.neuron.gui.bandtrades.workspace.interfaces.ISymbolPanelLayoutManager;
public class SliceAnyStrategyLayoutManager implements ISymbolPanelLayoutManager {
private Map<String, Component> labels = new HashMap<String, Component>();
private Map<String, Component> fields = new HashMap<String, Component>();
private boolean isFullWidth = true;
private Insets insets = new Insets(2, 15, 15, 15);
private Insets compactInsets = new Insets(2, 5, 5, 5);
private Dimension prefCompSize = new Dimension(80, 24);
private Dimension prefLabelSize = new Dimension(30, 24);
private Dimension prefCompactLabelSize = new Dimension(30, 24);
private int fullSpaceAfterLabel = 3;
private int fullSpaceAfterField = 10;
private int narrowSpaceAfterLabel = 3;
private int narrowSpaceAfterField = 10;
private int rowSpace = 10;
private int compactRowSpace = 5;
private Rectangle invisible = new Rectangle(0, 0, 0, 0);
private Component sliceQtyField;
/**
* Reflection uses the following constructor
*/
public SliceAnyStrategyLayoutManager(){
}
public void addLayoutComponent(String name, Component comp) {
if (comp instanceof JLabel) {
labels.put(name, comp);
} else {
fields.put(name, comp);
}
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
int w = isFullWidth ? SymbolPanel.SYMBOL_PANEL_BASE_PLUS_SCROLL.width
: SymbolPanel.NARROW_SYMBOL_PANEL_BASE_PLUS_SCROLL.width;
Component qtyField = fields.get(SliceStrategyFields.PREFERRED_SLICE_QUANTITY);
int h = isFullWidth ? (insets.top + qtyField.getPreferredSize().height
+ insets.bottom + rowSpace)
: (compactInsets.top + (qtyField.getPreferredSize().height + compactRowSpace )
+ compactInsets.bottom);
return new Dimension(w, h);
}
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
public void layoutContainer(Container parent) {
if (isFullWidth) {
doRegularLayout(parent);
} else {
doRegularCompactLayout(parent);
}
}
private void doRegularLayout(Container parent){
int x = insets.left+fullSpaceAfterLabel;
int y = insets.top;
//Single Row here
JLabel qtyLabel = (JLabel)labels.get(SliceStrategyFields.PREFERRED_SLICE_QUANTITY);
qtyLabel.setVerticalAlignment(SwingConstants.CENTER);
qtyLabel.setBounds(x, y, prefLabelSize.width, prefLabelSize.height);
x+= prefLabelSize.width+fullSpaceAfterLabel;
if(sliceQtyField != null){
sliceQtyField.setBounds(invisible);
}
sliceQtyField = ((QuantityFieldPanel)fields.get(SliceStrategyFields.PREFERRED_SLICE_QUANTITY)).getCurrentComponent();
Dimension qtyDim = sliceQtyField.getPreferredSize();
sliceQtyField.setBounds(x, y, qtyDim.width, prefCompSize.height);
y+= prefCompSize.width+narrowSpaceAfterField;
JLabel intervalLabel = (JLabel)labels.get(SliceStrategyFields.PREFERRED_INTERVAL);
intervalLabel.setText("Comp");
intervalLabel.setVerticalAlignment(SwingConstants.CENTER);
intervalLabel.setBounds(0, 400, prefLabelSize.width, prefLabelSize.height);
x+= prefLabelSize.width+fullSpaceAfterLabel;
}
private void doRegularCompactLayout(Container parent){
int x = insets.left;
int y = insets.top;
JLabel qtyLabel = (JLabel)labels.get(SliceStrategyFields.PREFERRED_SLICE_QUANTITY);
qtyLabel.setVerticalAlignment(SwingConstants.CENTER);
qtyLabel.setBounds(x-2, y, prefCompactLabelSize.width, prefCompactLabelSize.height);
x+= prefCompactLabelSize.width+narrowSpaceAfterLabel;
if(sliceQtyField != null){
sliceQtyField.setBounds(invisible);
}
sliceQtyField = ((QuantityFieldPanel)fields.get(SliceStrategyFields.PREFERRED_SLICE_QUANTITY)).getCurrentComponent();
Dimension qtyDim = sliceQtyField.getPreferredSize();
sliceQtyField.setBounds(x, y, qtyDim.width, qtyDim.height);
}
public void clearAll(){
labels.clear();
fields.clear();
sliceQtyField = null;
}
public void setFullWidth(boolean b) {
isFullWidth = b;
}
public void setLayoutMap(Map<String, Object> map) {
this.prefCompSize = MapUtils.getAsDimension(map, LayoutConstants.FULL_DIMENSION_1);
this.prefLabelSize = MapUtils.getAsDimension(map, LayoutConstants.FULL_DIMENSION_2);
this.prefCompactLabelSize = MapUtils.getAsDimension(map, LayoutConstants.NARROW_DIMENSION_2);
this.rowSpace = MapUtils.getAsInt(map,LayoutConstants.FULL_ROW_SPACE);
this.compactRowSpace = MapUtils.getAsInt(map, LayoutConstants.NARROW_ROW_SPACE);
this.insets = MapUtils.getAsInsets(map, LayoutConstants.INSETS_WIDE);
this.compactInsets = MapUtils.getAsInsets(map, LayoutConstants.INSETS_NARROW);
this.fullSpaceAfterField = MapUtils.getAsInt(map,LayoutConstants.FULL_SPACE_AFTER_FIELD);
this.fullSpaceAfterLabel = MapUtils.getAsInt(map,LayoutConstants.FULL_SPACE_AFTER_LABEL);
this.narrowSpaceAfterField = MapUtils.getAsInt(map,LayoutConstants.NARROW_SPACE_AFTER_FIELD);
this.narrowSpaceAfterLabel = MapUtils.getAsInt(map,LayoutConstants.NARROW_SPACE_AFTER_LABEL);
}
}
This is what I am trying to achieve

Animations when using Gridbag Layout.

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);
}
}

Categories

Resources