Print Preview ( Pack does not work ) - java

I have a print preview made by JPanel, JDialog that run error free but doesn't show up after pack();.
I know it's a bit long, but you can just skip to PrintPreview method, others are just there to know more detail of how I control.
Pls help, I don't know why it doesn't show up on the screen. Anyone please help thanks so much. ^_^
private PageFormat pf;
private Book pg;
private int pageIndex;
private int totalPages;
private double scaler;
private String title;
private JTextField pageInput;
private JTextField zoomInput;
private PreviewPanel pp;
private JLabel statusBar;
Start Here
public void PrintPreview(String title, Book pg, int pageIndex) {
this.title = title;
setTitle(title + " - Print Preview");
scaler = .5;
this.pg = pg;
this.pageIndex = pageIndex;
this.totalPages = pg.getNumberOfPages();
pf = pg.getPageFormat(pageIndex);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
setLayout(new BorderLayout());
pp = new PreviewPanel();
add(new JScrollPane(pp), BorderLayout.CENTER);
JPanel topBar = new JPanel();
topBar.setLayout(new BorderLayout());
add(topBar, BorderLayout.NORTH);
JPanel leftTop = new JPanel();
JPanel rightTop = new JPanel();
topBar.add(leftTop, BorderLayout.WEST);
topBar.add(rightTop, BorderLayout.EAST);
leftTop.add(new JLabel("Page:"));
Insets pageButtonInsets = new Insets(0, 2, 0, 2);
JButton pageBack = new JButton("<");
pageBack.setMargin(pageButtonInsets);
pageBack.setActionCommand("back");
pageBack.addActionListener(this);
JButton pageForward = new JButton(">");
pageForward.setMargin(pageButtonInsets);
pageForward.setActionCommand("forward");
pageForward.addActionListener(this);
pageInput = new JTextField(Integer.toString(pageIndex+1));
pageInput.setPreferredSize(new Dimension(30, 20));
pageInput.setActionCommand("page");
pageInput.addActionListener(this);
leftTop.add(pageBack);
leftTop.add(pageInput);
leftTop.add(pageForward);
rightTop.add(new JLabel("Zoom:"));
zoomInput = new JTextField((int)(scaler*100)+"%");
zoomInput.setPreferredSize(new Dimension(30, 20));
rightTop.add(zoomInput);
JButton zoomSet = new JButton("Set");
zoomSet.setMargin(new Insets(0, 0, 0, 0));
zoomSet.setPreferredSize(new Dimension(30, 20));
rightTop.add(zoomSet);
zoomSet.setActionCommand("zoom");
zoomSet.addActionListener(this);
JPanel lowerBar = new JPanel();
lowerBar.setLayout(new BorderLayout());
lowerBar.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
statusBar = new JLabel("Ag"); // temporary label for setting size of status bar
lowerBar.add(statusBar, BorderLayout.CENTER);
add(lowerBar, BorderLayout.SOUTH);
JButton license = new JButton("<html>©</html>");
license.setActionCommand("license");
license.setMargin(new Insets(0, 0, 0, 0));
license.addActionListener(this);
lowerBar.add(license, BorderLayout.WEST);
JButton print = new JButton("Print...");
print.setActionCommand("print");
print.setMargin(new Insets(4, 0, 4, 0));
print.addActionListener(this);
lowerBar.add(print, BorderLayout.EAST);
pack();
//setVisible(true);
}
End here
private void updateStatusBar() {
updateStatusBar("Page " + (pageIndex+1) + " of " + totalPages);
}
private void updateStatusBar(String s) {
updateStatusBar(s, Color.black);
}
private void updateStatusBar(String s, Color c) {
statusBar.setText(s);
statusBar.setForeground(c);
}
private void print() {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPageable(pg);
pj.setJobName(title);
if (pj.printDialog()) {
try {
pj.print();
} catch (PrinterException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Could not print.\nSee the Java error console for details.", "error", JOptionPane.ERROR_MESSAGE);
}
}
}
private class PreviewPanel extends JPanel {
private static final long serialVersionUID = 1L;
public PreviewPanel() {
resetPreferredSize();
}
public void resetPreferredSize() {
setPreferredSize(new Dimension((int)(pf.getWidth()*scaler), (int)(pf.getHeight()*scaler)));
}
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D)g1;
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.white);
g.fillRect(0, 0, (int)(pf.getWidth()*scaler), (int)(pf.getHeight()*scaler));
g.setColor(Color.black);
try {
g.scale(scaler, scaler);
pg.getPrintable(pageIndex).print(g, pf, pageIndex);
updateStatusBar();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
g.setFont(new Font("Helvetica", Font.ITALIC, 30));
g.drawString("Page index out of range", 10, 30);
updateStatusBar("Page index out of range", Color.red);
} catch (PrinterException e) {
e.printStackTrace();
g.setFont(new Font("Helvetica", Font.ITALIC, 30));
g.drawString("Printer error", 10, 30);
updateStatusBar("Printer error", Color.red);
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getActionCommand().equals("page")) {
// change page
try {
pageIndex = Integer.parseInt(pageInput.getText())-1;
pp.repaint();
} catch (NumberFormatException e) {
// do nothing if the entry is not a number
}
} else if (arg0.getActionCommand().equals("back")) {
if (pageIndex > 0) {
pageIndex--;
pageInput.setText(Integer.toString(pageIndex+1));
pp.repaint();
}
} else if (arg0.getActionCommand().equals("forward")) {
if (pageIndex < totalPages - 1) {
pageIndex++;
pageInput.setText(Integer.toString(pageIndex+1));
pp.repaint();
}
} else if (arg0.getActionCommand().equals("zoom")) {
// change zoom setting
try {
scaler = Double.parseDouble(zoomInput.getText().replaceAll("%", ""))// 100.0;
pp.resetPreferredSize();
pp.revalidate();
pp.repaint();
} catch (NumberFormatException e) {
// do nothing if the entry is not a number
}
} else if (arg0.getActionCommand().equals("license")) {
JOptionPane.showMessageDialog(this, LICENSE);
} else if (arg0.getActionCommand().equals("print")) {
print();
}
}

Yeah, I figured it out. Hahahaha Actually it does pop out but behind other foreround application....hahahaa finally its done.

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.

Selected variables doesn't change on pong game - Swing

I'm trying to make a pong game by using Swing. I have a menu screen where you can change your preferences such as music, game speed and you can choose multiplayer options etc. But when I made a choice, their values don't change. I have my mainmenu class and computer class.
For ex: I want to change the difficulty which means changing the AI's speed but I wasn't be able to do it. I am looking forward for an answer, maybe it's so simple but I can't see it.
This is my code:
public class MenuPanel
{
ScoreBoard sc = new ScoreBoard();
private JFrame mainFrame;
private JFrame optionsFrame;
private JPanel menuPanel;
private JPanel optionsPanel;
private JFrame gameEndFrame;
private JPanel gameEndPanel;
JCheckBox twoPlayer;
// creating the swing components and containers,
// there are two frames to swap between them,
// we tried to use cardLayout but it didn't work for us.
public MenuPanel() {
mainFrame = new JFrame("Welcome To Pong Game");
mainFrame.setSize(700,700);
mainFrame.setLayout(new CardLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuPanel = new JPanel(null);
menuPanel.setSize(700,700);
menuPanel.setVisible(true);
mainFrame.add(menuPanel);
optionsFrame = new JFrame("Settings");
optionsFrame.setSize(700, 700);
optionsFrame.setLayout(new CardLayout());
optionsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel optionsPanel = new JPanel(null) ;
optionsPanel.setSize(700,700);
optionsPanel.setVisible(true);
optionsFrame.add(optionsPanel);
// mainPanel components
ImageIcon ic1 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Actions-player-play-icon.png");
ImageIcon ic2 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Settings-L-icon.png");
ImageIcon ic3 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\cup-icon.png");
ImageIcon ic4 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Button-Close-icon.png");
ImageIcon ic5 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\ice-2025937_960_720.jpg");
ImageIcon ic6 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\tenis1.png");
JLabel mainLabel = new JLabel();
Font font = new Font("Papyrus", Font.BOLD,26);
mainLabel.setFont(font);
mainLabel.setForeground(Color.RED);
mainLabel.setText("PONG GAME");
JButton startButton = new JButton("Start Game");
JButton optionsButton = new JButton("Options");
JButton leaderButton = new JButton("Leaderboard");
JButton exitButton = new JButton("Exit");
JButton icb1 = new JButton(ic1);
JButton icb2 = new JButton(ic2);
JButton icb3 = new JButton(ic3);
JButton icb4 = new JButton(ic4);
JButton icb6 = new JButton(ic6);
// at first, we tried to keep our buttons and labels in panels
// but then we didn't add an image to label as the background
// so we created a JLabel to set its image as the background, we may remove it later.
JLabel mn = new JLabel(ic5);
mn.setBackground(Color.BLUE);
mn.setBounds(1, 1, 700, 700);
Font font3 = new Font("Calibri", Font.PLAIN, 20);
twoPlayer = new JCheckBox();
twoPlayer.setFont(font3);
twoPlayer.setForeground(Color.DARK_GRAY);
twoPlayer.setText(" MultiPlayer");
twoPlayer.setBounds(200, 350, 220, 40);
menuPanel.add(mn);
mn.add(mainLabel);
mn.add(startButton);
mn.add(optionsButton);
mn.add(leaderButton);
mn.add(exitButton);
mn.add(icb1);
mn.add(icb2);
mn.add(icb3);
mn.add(icb4);
mn.add(icb6);
mn.add(twoPlayer);
mainFrame.setVisible(true);
// the components added by their coordinates to make them look formal
mainLabel.setBounds(210, 100, 220, 40);
startButton.setBounds(200, 150, 220, 40);
optionsButton.setBounds(200, 200, 220, 40);
leaderButton.setBounds(200, 250, 220, 40);
exitButton.setBounds(200, 300, 220, 40);
icb1.setBounds(150, 150, 40, 40);
icb2.setBounds(150, 200, 40, 40);
icb3.setBounds(150, 250, 40, 40);
icb4.setBounds(150, 300, 40, 40);
icb6.setBounds(150,350,40,40);
startButton.setBorder(BorderFactory.createRaisedBevelBorder());
optionsButton.setBorder(BorderFactory.createRaisedBevelBorder());
leaderButton.setBorder(BorderFactory.createRaisedBevelBorder());
exitButton.setBorder(BorderFactory.createRaisedBevelBorder());
// optionsPanel components
JButton doneButton = new JButton("Done");
doneButton.setBounds(150,330,220,40);
doneButton.setBorder(BorderFactory.createRaisedBevelBorder());
Font font1 = new Font("Calibri", Font.PLAIN,24);
Font font2 = new Font("Calibri", Font.BOLD,19);
JLabel st = new JLabel();
st.setFont(font1);
st.setForeground(Color.DARK_GRAY);
st.setText("-OPTIONS-");
JLabel difficulty = new JLabel("Difficulty: ");
difficulty.setFont(font2);
difficulty.setForeground(Color.DARK_GRAY);
JLabel music = new JLabel("Sound: ");
music.setFont(font2);
music.setForeground(Color.DARK_GRAY);
JLabel gSpeed = new JLabel("Game Speed: ");
gSpeed.setFont(font2);
gSpeed.setForeground(Color.DARK_GRAY);
JLabel screen = new JLabel(ic5);
screen.setBackground(Color.BLUE);
screen.setBounds(1, 1, 700, 700);
JRadioButton rb1 = new JRadioButton("Easy");
JRadioButton rb2 = new JRadioButton("Normal");
JRadioButton rb3 = new JRadioButton("Hard");
JRadioButton rb4 = new JRadioButton("On");
JRadioButton rb5 = new JRadioButton("Off");
JRadioButton rb6 = new JRadioButton("x");
JRadioButton rb7 = new JRadioButton("2x");
JRadioButton rb8 = new JRadioButton("3x");
ButtonGroup bg1 = new ButtonGroup();
ButtonGroup bg2 = new ButtonGroup();
ButtonGroup bg3 = new ButtonGroup();
bg1.add(rb1);
bg1.add(rb2);
bg1.add(rb3);
bg2.add(rb4);
bg2.add(rb5);
bg3.add(rb6);
bg3.add(rb7);
bg3.add(rb8);
optionsPanel.add(screen);
screen.add(difficulty);
screen.add(st);
screen.add(gSpeed);
screen.add(rb1);
screen.add(rb2);
screen.add(rb3);
screen.add(rb4);
screen.add(rb5);
screen.add(rb6);
screen.add(rb7);
screen.add(rb8);
screen.add(music);
screen.add(doneButton);
st.setBounds(200,100,220,40);
difficulty.setBounds(100,150,90,40);
music.setBounds(100,200,90,40);
gSpeed.setBounds(100, 250, 120, 40);
rb1.setBounds(200,150,60,40);
rb2.setBounds(260,150,80,40);
rb3.setBounds(340, 150, 60, 40);
rb4.setBounds(200, 200, 50, 40);
rb5.setBounds(250,200,50,40);
rb6.setBounds(220, 250, 50, 40);
rb7.setBounds(270, 250, 50, 40);
rb8.setBounds(320, 250, 50, 40);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Pong pong = new Pong();
sound("Marimba-music");
mainFrame.dispose();
if(twoPlayer.isSelected()) {
pong.c.isTwoPlayer = true;
}
else {
pong.c.isTwoPlayer = false;
}
}
});
optionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainFrame.setVisible(false);
optionsFrame.setVisible(true);
}
});
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsFrame.dispose();
Pong pong = new Pong();
if(rb1.isSelected())
{
pong.c.setUp(-10);;
pong.c.setDown(10);
}
else if(rb2.isSelected())
{
pong.c.setUp(-11);
pong.c.setDown(11);
}
else if(rb3.isSelected())
{
pong.c.setUp(-30);
pong.c.setDown(30);
}
if(rb4.isSelected())
{
sound("Marimba-music");
}
else if(rb5.isSelected())
{
soundStop("Marimba-music");
}
if(rb6.isSelected())
{
GamePanel g = new GamePanel();
g.x = 50;
}
else if(rb7.isSelected())
{
GamePanel g = new GamePanel();
g.x = 75;
}
else if(rb8.isSelected())
{
GamePanel g = new GamePanel();
g.x = 100;
System.out.println(g.x);
}
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
mainFrame.dispose();
}
});
}
public void sound(String nm)
{
AudioStream BGM;
try {
InputStream test = new FileInputStream("./" +nm+".wav");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
}
catch(IOException error) {
JOptionPane.showMessageDialog(null, error.getMessage());
}
}
public void soundStop(String nm)
{
AudioStream BGM;
try {
InputStream test = new FileInputStream("./" +nm+".wav");
BGM = new AudioStream(test);
AudioPlayer.player.stop(BGM);
}
catch(IOException error) {
JOptionPane.showMessageDialog(null, error.getMessage());
}
}
}
My Computer.class:
public class Computer
{
private GamePanel field;
private int y = Pong.WINDOW_HEIGHT / 2;
private int yCh = 0;
private int up = -10;
private int down = 10;
private int width = 20;
private int height = 90;
boolean isTwoPlayer = false;
public Computer() {
}
public void update(Ball b) {
if(y + height > Pong.WINDOW_HEIGHT)
{
y = Pong.WINDOW_HEIGHT - height;
}
else if(y < 0)
{
y = 0;
}
if(!isTwoPlayer) {
if(b.getY() < y+height && y >= 0)
{
yCh = up;
}
else if(b.getY() > y && y + height <= Pong.WINDOW_HEIGHT)
{
yCh = down;
}
y = y + yCh;
}
else {
y = y + yCh;
}
}
public void setYPosition(int speed) {
yCh = speed;
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRoundRect(450, y, width, height, 10, 10);
}
public int getX() {
return 450;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getUp() {
return up;
}
public int getDown() {
return down;
}
public void setUp(int up) {
this.up = up;
}
public void setDown(int down) {
this.down = down;
}
I don't know how your whole program is structured. But in this piece of code:
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsFrame.dispose();
Pong pong = new Pong();
You create a new instance of Pong class and set the values of the new created instance.
This instance is not used anywhere else. You may need to use a instance of Pong that is already in use, or make other classes use the new created instance.

Animation in Java on top of JPanel

I have a JPanel where I have array of buttons. It's a kind of memory game, and I wont to show some few frames of animation, for example Double Point.
Here is a part of code:
This animation is that some text is slowly showing and disappearing (I used also Alpha channel in those images) , but I don't know why when id should slowly disapearing it didn't like if of this image stay there.
public void paintComponent(Graphics g)
{
//Image img = new ImageIcon("res\\double.png").getImage();
//g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
t.start();
Image img2 = new ImageIcon("res\\double\\double_0000"+i+".png").getImage();
g.drawImage(img2, 0, 0, this.getWidth(), this.getHeight(), null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
t.restart();
repaint();
}
}
public class ScoreWindow extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
final public JButton btnScoreReturnButton;
final public JLabel ScoreLabel;
//final public JScrollBar scrollScoreBar;
private String[] data;
Timer t;
String sth="";
int i=0;
int datapower=0;
public ScoreWindow() {
btnScoreReturnButton = new JButton("Powrót");
SpringLayout sl_ScoreWindow = new SpringLayout();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, btnScoreReturnButton, 27, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, btnScoreReturnButton, 11, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, btnScoreReturnButton, 100, SpringLayout.WEST, this);
this.setLayout(sl_ScoreWindow);
this.add(btnScoreReturnButton);
ScoreLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, ScoreLabel, 64, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, ScoreLabel, 111, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, ScoreLabel, -15, SpringLayout.SOUTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, ScoreLabel, -76, SpringLayout.EAST, this);
this.add(ScoreLabel);
JLabel SubtitleLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, SubtitleLabel, 20, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, SubtitleLabel, 80, SpringLayout.WEST,ScoreLabel);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, SubtitleLabel, 60, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, SubtitleLabel, -150, SpringLayout.EAST, this);
SubtitleLabel.setForeground(Color.BLACK);
SubtitleLabel.setHorizontalAlignment(JLabel.CENTER);
SubtitleLabel.setVerticalAlignment(JLabel.CENTER);
SubtitleLabel.setFont(ScoreLabel.getFont().deriveFont(32.0f));
SubtitleLabel.setText("Najlepsze Wyniki");
this.add(SubtitleLabel);
t=new Timer(100,this);
}
public void ReadData()
{
data = new String[20];
FileReader readFile=null;
BufferedReader reader =null;
String temp;
try
{
readFile=new FileReader("highscore.dat");
reader=new BufferedReader(readFile);
int i=0;
while((temp=reader.readLine())!=null)
{
data[i]=temp;
i++;
}
}
catch(Exception e)
{
data[0] ="Nobody:0";
}
finally
{
try {
if(reader!=null)
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void LoadData() {
String stream="<html>";
//System.out.print(data[0]+"\n");
for(int i=0;i<data.length;i++)
{
if(data[i]!=null)
{
if(i==0)
stream=stream+data[i];
//tream=stream+data[i];
else if(i>0)
stream=stream+"<br>"+data[i];
}
}
stream+="</html>";
System.out.print(stream+"\n");
ScoreLabel.setHorizontalAlignment(JLabel.CENTER);
ScoreLabel.setVerticalAlignment(JLabel.CENTER);
ScoreLabel.setForeground(Color.WHITE);
ScoreLabel.setFont(ScoreLabel.getFont().deriveFont(16.0f));
ScoreLabel.setText(stream);
ScoreLabel.setOpaque(false);
}
public int AmoutofData()
{
String amount[] = ScoreLabel.getText().split("<br>");
return amount.length;
}
public void paintComponent(Graphics g)
{
t.start();
if(i<10)
sth="0"+i;
else
sth=i+"";
Image img2 = new ImageIcon("res\\double\\double_000"+sth+".png").getImage();
g.drawImage(img2, i, i, 100, 100, null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
i=0;
repaint();
}
}

BufferedImage for captured chess pieces does not display on my JPanel

Please am developing a chess game using Java. I am having problems trying to display captured chess pieces, this pieces are held in a bufferedImage. when i run and print the variable of the bufferedImage it isn't null and doesn't display the image on the JPanel.
In addition my list of captured chess piece stored in a "List capturedPiece" and is working fine, also the paths to the images are correct. The only problem is that the image stored on the bufferedImage doesn't displaying.
Here is my code
package chessgame.gui;
public class BrownPlayerPanel extends JPanel {
private Rectangle yellowPawnRect, yellowKnightRect, yellowBishopRect,
yellowRookRect, yellowQueenRect;
private Rectangle brownPawnRect, brownKnightRect, brownBishopRect,
brownRookRect, brownQueenRect;
private List<Piece> capturedPieces;
BufferedImage figurineLayer, counterLayer;
boolean firstPaint = true;
private ImageFactory fact;
BufferedImage piecetest;
public BrownPlayerPanel() {
initComponents();
fact = new ImageFactory();
}
public void setCapturedPieces(List<Piece> piece) {
capturedPieces = piece;
//System.out.println(capturedPieces);
if (counterLayer != null) {
clearBufferedImage(counterLayer);
}
if (figurineLayer != null) {
clearBufferedImage(figurineLayer);
}
updateLayers();
repaint();
}
private void initRects(int width, int height) {
int gridWidth = width / 5;
int gridHeight = height / 2;
yellowPawnRect = new Rectangle(0, 0, gridWidth, gridHeight);
yellowKnightRect = new Rectangle(gridWidth, 0, gridWidth, gridHeight);
yellowBishopRect = new Rectangle(gridWidth * 2, 0, gridWidth, gridHeight);
yellowRookRect = new Rectangle(gridWidth * 3, 0, gridWidth, gridHeight);
yellowQueenRect = new Rectangle(gridWidth * 4, 0, gridWidth, gridHeight);
brownPawnRect = new Rectangle(0, gridHeight, gridWidth, gridHeight);
brownKnightRect = new Rectangle(gridWidth, gridHeight, gridWidth,gridHeight);
brownBishopRect = new Rectangle(gridWidth * 2, gridHeight, gridWidth,gridHeight);
brownRookRect = new Rectangle(gridWidth * 3, gridHeight, gridWidth,gridHeight);
brownQueenRect = new Rectangle(gridWidth * 4, gridHeight, gridWidth,gridHeight);
}
public void clearBufferedImage(BufferedImage image) {
Graphics2D g2d = image.createGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.setColor(new Color(0, 0, 0, 0));
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
g2d.dispose();
}
private void updateLayers() {
int yPC = 0, yNC = 0, yBC = 0, yRC = 0, yQC = 0;
int bPC = 0, bNC = 0, bBC = 0, bRC = 0, bQC = 0;
if (firstPaint) {
int width = this.getWidth();
int height = this.getHeight();
figurineLayer = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
counterLayer = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
capturedPieces = new ArrayList<Piece>();
initRects(width, height);
firstPaint = false;
}
int width = this.getWidth();
int height = this.getHeight();
int gridWidth = width / 5;
for (Piece piece : capturedPieces) {
if (piece.getColor() == Piece.YELLOW_COLOR) {
if (piece.getType() == Piece.TYPE_PAWN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR, Piece.TYPE_PAWN),yellowPawnRect);
yPC++;
}
if (piece.getType() == Piece.TYPE_KNIGHT) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_KNIGHT),yellowKnightRect);
yNC++;
}
if (piece.getType() == Piece.TYPE_BISHOP) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_BISHOP),yellowBishopRect);
yBC++;
}
if (piece.getType() == Piece.TYPE_ROOK) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR, Piece.TYPE_ROOK), yellowRookRect);
yRC++;
}
if (piece.getType() == Piece.TYPE_QUEEN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_QUEEN), yellowQueenRect);
yQC++;
}
}
if (piece.getColor() == Piece.BROWN_COLOR) {
if (piece.getType() == Piece.TYPE_PAWN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_PAWN),brownPawnRect);
System.out.println(getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_PAWN).getWidth());
bPC++;
}
if (piece.getType() == Piece.TYPE_KNIGHT) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_KNIGHT),brownKnightRect);
bNC++;
}
if (piece.getType() == Piece.TYPE_BISHOP) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_BISHOP),brownBishopRect);
bBC++;
}
if (piece.getType() == Piece.TYPE_ROOK) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_ROOK),brownRookRect);
bRC++;
}
if (piece.getType() == Piece.TYPE_QUEEN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_QUEEN), brownQueenRect);
bQC++;
}
}
}
if (yPC > 1) {
drawCounterIntoLayer(counterLayer, yPC, yellowPawnRect);
}
if (yNC > 1) {
drawCounterIntoLayer(counterLayer, yNC, yellowKnightRect);
}
if (yBC > 1) {
drawCounterIntoLayer(counterLayer, yBC, yellowBishopRect);
}
if (yRC > 1) {
drawCounterIntoLayer(counterLayer, yRC, yellowRookRect);
}
if (yQC > 1) {
drawCounterIntoLayer(counterLayer, yQC, yellowQueenRect);
}
if (bPC > 1) {
drawCounterIntoLayer(counterLayer, bPC, brownPawnRect);
}
if (bNC > 1) {
drawCounterIntoLayer(counterLayer, bNC, brownKnightRect);
}
if (bBC > 1) {
drawCounterIntoLayer(counterLayer, bBC, brownBishopRect);
}
if (bRC > 1) {
drawCounterIntoLayer(counterLayer, bRC, brownRookRect);
}
if (bQC > 1) {
drawCounterIntoLayer(counterLayer, bQC, brownQueenRect);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(figurineLayer, 10,10, this);
g2d.drawImage(counterLayer, null, this);
}
private void drawCounterIntoLayer(BufferedImage canvas, int count,Rectangle whereToDraw) {
Graphics2D g2d = canvas.createGraphics();
g2d.setFont(new Font("Arial", Font.BOLD, 12));
g2d.setColor(Color.black);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
FontMetrics textMetrics = g2d.getFontMetrics();
String countString = Integer.toString(count);
int xCoord = whereToDraw.x + whereToDraw.width - textMetrics.stringWidth(countString);
int yCoord = whereToDraw.y + whereToDraw.height;
g2d.drawString(countString, xCoord, yCoord);
g2d.dispose();
}
private void drawImageIntoLayer(BufferedImage canvas, BufferedImage item,Rectangle r) {
Graphics2D g2d = canvas.createGraphics();
g2d.drawImage(item, r.x, r.y, r.width, r.height, this);
g2d.dispose();
}
private void initComponents() {
setName("Form");
setBounds(0, 0, 250, 146);
setBorder(new LineBorder(new Color(139, 69, 19)));
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGap(0, 698, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGap(0, 448, Short.MAX_VALUE)
);
setLayout(groupLayout);
setBackground(Color.black);
}
private BufferedImage getFigurineImage(int color, int type) {
BufferedImage ImageToDraw = null;
try {
String filename = "";
filename += (color == Piece.YELLOW_COLOR ? "Yellow" : "Brown");
switch (type) {
case Piece.TYPE_BISHOP:
filename += "b";
break;
case Piece.TYPE_KING:
filename += "k";
break;
case Piece.TYPE_KNIGHT:
filename += "n";
break;
case Piece.TYPE_PAWN:
filename += "p";
break;
case Piece.TYPE_QUEEN:
filename += "q";
break;
case Piece.TYPE_ROOK:
filename += "r";
break;
}
filename += ".png";
URL urlPiece = getClass().getResource("/chessgame/res/" + filename);
ImageToDraw = ImageIO.read(urlPiece);
} catch (IOException io) {
}
return ImageToDraw;
}
}
ChessWindow Class:
public class ChessWindow extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private BoardGUI boardgui;
private Game game;
JPanel panel_1;
public JLabel lblNewLabel;
private XmlRpcServer server;
private static final int PLAYER_OPTION_SWING = 1;
private static final int PLAYER_OPTION_AI = 2;
private static final int PLAYER_OPTION_NETWORK = 3;
String gameIdOnServer, gamePassword;
public ChessWindow(int yellowPlayerOption, int brownPlayerOption,Game game, String gameIdOnServer, String gamePassword) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 776, 583);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNewGame = new JMenuItem("New Game");
mnFile.add(mntmNewGame);
JSeparator separator = new JSeparator();
mnFile.add(separator);
JSeparator separator_1 = new JSeparator();
mnFile.add(separator_1);
JSeparator separator_2 = new JSeparator();
mnFile.add(separator_2);
JMenuItem mntmAccount = new JMenuItem("Account");
mnFile.add(mntmAccount);
JSeparator separator_10 = new JSeparator();
mnFile.add(separator_10);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
JMenu mnTactics = new JMenu("Tactics");
menuBar.add(mnTactics);
JMenuItem mntmTactics = new JMenuItem("Tactics 1");
mnTactics.add(mntmTactics);
JMenuItem mntmTactics_1 = new JMenuItem("Tactics 2");
mnTactics.add(mntmTactics_1);
JMenu mnServer = new JMenu("Server");
menuBar.add(mnServer);
JMenuItem mntmServerStatus = new JMenuItem("Server Status");
mntmServerStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//String gameId = "Game ID:" + server.getGameIdOnServer();
JOptionPane.showMessageDialog(boardgui,
server.gameIdOnServer,
"A plain message",
JOptionPane.PLAIN_MESSAGE);
}
});
mnServer.add(mntmServerStatus);
JMenuItem mntmServerLog = new JMenuItem("Server Log");
mntmServerLog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JavaConsole console = new JavaConsole();
console.frame.setVisible(true);
console.frame.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
}
});
mnServer.add(mntmServerLog);
JMenuItem mntmViewOnlinePlayers = new JMenuItem("View Online Players");
mnServer.add(mntmViewOnlinePlayers);
JMenu mnStatistics = new JMenu("Statistics");
menuBar.add(mnStatistics);
JMenuItem mntmHumanStatsAgainst = new JMenuItem("Human Stats Against Computer");
mnStatistics.add(mntmHumanStatsAgainst);
JSeparator separator_8 = new JSeparator();
mnStatistics.add(separator_8);
JMenuItem mntmComputerStatsAgainst = new JMenuItem("Computer Stats Against Itself");
mnStatistics.add(mntmComputerStatsAgainst);
JSeparator separator_9 = new JSeparator();
mnStatistics.add(separator_9);
JMenuItem mntmHumanStatsAgains = new JMenuItem("Human Stats Agains Human");
mnStatistics.add(mntmHumanStatsAgains);
JMenuItem mntmAlgorithmInformation = new JMenuItem("Algorithm Information");
mnStatistics.add(mntmAlgorithmInformation);
JMenu mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
JMenu mnTest = new JMenu("Test");
mnOptions.add(mnTest);
JMenuItem mntmPiecePosition = new JMenuItem("Piece Position");
mnTest.add(mntmPiecePosition);
JMenuItem mntmPieceMoves = new JMenuItem("Piece Moves");
mnTest.add(mntmPieceMoves);
JSeparator separator_11 = new JSeparator();
mnOptions.add(separator_11);
JMenuItem mntmConsole = new JMenuItem("Console");
mntmConsole.addActionListener(new ConsoleController());
mnOptions.add(mntmConsole);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmRulesOfChess = new JMenuItem("Rules of Chess");
mnHelp.add(mntmRulesOfChess);
JMenuItem mntmAbout = new JMenuItem("About");
mnHelp.add(mntmAbout);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
panel.setBounds(0, 0, 50, 50);
lblNewLabel = new JLabel("text");
panel.add(lblNewLabel);
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.1);
contentPane.add(splitPane, BorderLayout.CENTER);
game = new Game();
boardgui = new BoardGUI(game);
splitPane.setLeftComponent(boardgui);
GameConfig(yellowPlayerOption, brownPlayerOption, game, gameIdOnServer, gamePassword, boardgui);
StatusPanel panel_1 = new StatusPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
boardgui.lblGameState = new JLabel();
panel_1.add(boardgui.lblGameState);
JPanel panel_2 = new JPanel();
splitPane.setRightComponent(panel_2);
panel_2.setBounds(0, 0, 50, 300);
panel_2.setLayout(null);
BrownPlayerPanel brown = new BrownPlayerPanel();
panel_2.add(brown);
MovesHistoryPanel moveDisplay = new MovesHistoryPanel();
moveDisplay.setBorder(new LineBorder(new Color(139, 69, 19)));
panel_2.add(moveDisplay);
YellowPlayerPanel yellow = new YellowPlayerPanel();
yellow.setBorder(new LineBorder(new Color(139, 69, 19)));
panel_2.add(yellow);
}
}
Given these things you stated are true:
when i run and print the variable of the bufferedImage it isn't null
In addition my list of captured chess piece stored in a "List capturedPiece" and is working fine
also the paths to the images are correct.
A common problem will custom painting that the panel that the painting is being done on has not default preferred size (0x0). A panel only get increased preferred size based on more components being added to it. In the case of custom painting on a panel, you need to give the panel an explicit preferred size by overriding getPreferredSize()
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
Without this, it can be hit or miss, whether or not you will see the contents of the panel. The determining factory is the layout manager of the parent container. Some layout managers will respect the preferred size (in which case, you won't see the contents) and some that won't respect preferred size (in which case, the panel will stretch to fit the container - where you may see the contents). Generally when custom painting, you always want to override the method. Have a look at this post to get an idea of which layout managers respect preferred sizes and which ones don't
If that doesn't work, I suggest you post an MCVE that we can run and test. Leave out all the unnecessary code that doesn't pertain to this problem. I'd sat just create a separate program that has nothing to do with your program, just a couple simple images being drawn to a panel, and add it to a frame. Something simple recreates the problem.
UPDATE
Don't use null layouts! Use layout managers.. Your layout a null for the container you want to add the panel in question to, but you can't do that without setting the bounds. But forget that. Like I said, don't use null layouts. Learn to use the layout managers in the link. Let them do the position and sizing for you.

Image not being displayed properly in applet

i want to add a image at 615,50 in my applet . image name is logo1.jpg . but the following code only prints d image.. when i compile and then run using applet viewer. only the image logo1 shows at d spot. the rest code doesnt work. however if i remove the image . then the code works fine. i think theres some problem with the paint() function . if i use ImageIcon and then add it into a label and set that label to the location,then it works fine in the appletviewer but as soon as i open it in a webbrowser, an IO Error appears
"access denied("java.io.FilePermission" "logo1.jpg" "read" ). pls help. image size is 126,126.
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
public class site extends Applet implements MouseListener, Runnable
{
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
JLabel l5;
JLabel l6;
JLabel l21;
String str;
String s1;
String s2;
String s3;
Thread th;
int x;
int vt;
int hr;
int yx=75;
ImageIcon I;
Image image;
public void init()
{
setLayout(null);
addMouseListener(this);
loadImage();
//I=new ImageIcon("logo1.jpg");
l1 = new JLabel("2");
l1.setBounds(433, yx, 50, 50);
l1.setFont(new Font("Sketch Block", Font.PLAIN, 50));
l1.setForeground(Color.red);
add(l1);
l21=new JLabel(I);
l21.setBounds(630,50,126,126);;
add(l21);
l2 = new JLabel("0");
l2.setBounds(483, yx, 50, 50);
l2.setFont(new Font("Sketch Block", 0, 50));
l2.setForeground(Color.blue);
add(l2);
l3 = new JLabel("1");
l3.setBounds(543, yx, 50, 50);
l3.setFont(new Font("Sketch Block", 0, 50));
l3.setForeground(Color.magenta);
add(l3);
l4 = new JLabel("3");
l4.setBounds(583, yx, 50, 50);
l4.setFont(new Font("Sketch Block", 0, 50));
l4.setForeground(Color.cyan);
add(l4);
l5 = new JLabel("Impressions");
l5.setBounds(770, yx, 400, 50);
l5.setFont(new Font("Sketch Block", 0, 50));
l5.setForeground(Color.black);
add(l5);
l6 = new JLabel("March");
l6.setBounds(683, yx, 200, 50);
l6.setFont(new Font("Sketch Block", 0, 50));
l6.setForeground(Color.black);
th = new Thread(this);
}
public void loadImage()
{
URL url = getClass().getResource("logo1.jpg");
image = getToolkit().getImage(url);
}
public void paint(Graphics g)
{
g.drawImage(image, 615,50, this);
}
public void mouseClicked(MouseEvent me)
{
vt=me.getY();
hr=me.getX();
try
{
final URI uri = new URI("file:///E:/site/1.html");
final URI uri1 = new URI("file:///E:/site/2.html");
final URI uri2 = new URI("file:///E:/site/3.html");
if(hr<=468 && hr>=427)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri);
}
catch (Exception ex)
{
}
}
}
if(hr>=468 && hr<=527)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri1);
}
catch (Exception ex)
{
}
}
}
if(hr<=577 && hr>=527)
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(uri2);
}
catch (Exception ex)
{
}
}
}
}
catch(Exception e)
{
}
}
public void mouseEntered(MouseEvent me)
{
th = new Thread(this);
th.start();
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseExited(MouseEvent me) {
th.stop();
l1.setText(" ");
l2.setText(" ");
l3.setText(" ");
l4.setText(" ");
l5.setText(" ");
l6.setText(" ");
l1.setText("2");
l1.setBounds(433, yx, 40, 50);
l2.setText("0");
l2.setBounds(483, yx, 40, 50);
l3.setText("1");
l3.setBounds(533, yx, 40, 50);
l4.setText("3");
l4.setBounds(583, yx, 40, 50);
l5.setText("Impressions");
l5.setBounds(770, yx, 400, 50);
l21.setBounds(630,50,126,126);
}
public void run()
{
try
{
l2.setText(" ");
for (x = 0; x < 200; x += 1)
{
Thread.sleep(1L);
l3.setText("1");
l3.setBounds(533 - x / 2, yx, 40, 50);
l1.setText("2");
l1.setBounds(433 + x / 4, yx, 40, 50);
l4.setText("3");
l4.setBounds(583 - x / 4, yx, 40, 50);
l5.setBounds(770, yx-(6*x)/8, 400, 50);
l21.setBounds(630,50-x,126,126);
l6.setText("March");
l6.setBounds(650, 200 - (5 * x)/8, 200, 50);
add(l6);
}
l3.setText("<html>1<sup><font size=3>st</font></sup></html>");
l1.setText("<html>2<sup><font size=3>st</font></sup></html>");
l4.setText("<html>3<sup><font size=3>rd</font></sup></html>");
}
catch (Exception e)
{
}
}
}
everytime i use paint method, only the paint method works and the rest of the code doesnt work properly. even if i draw a line using the paint() method. then also the same happens.
Toolkit's image loading is sometimes not working. I don't know why but it is what I experienced. Use the ImageIcon class instead.
img = new ImageIcon(getClass().getResource("logo.png")).getImage();

Categories

Resources