Trying to solve a proportionnality issue here - java

In my code i generate randoms integer between 0 and 60 and i draw lines based on these.
I just want my lines fit the ordinate vertical line without touching my randoms integer... I guess it's kind of a mathematics problem but i'm really stuck here!
Here's my code first:
Windows.java:
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
ip.addActionListener(lForButton);
print.addActionListener(lForButton);
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
this.setContentPane(container);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==start)
{
time=Double.parseDouble(timeStep.getText());
System.out.println(time);
chrono = new Timer((int)(1000*time),pan);
chrono.start();
}
if(e.getSource()==ip)
{
JPanel options = new JPanel();
JLabel address = new JLabel("IP Address:");
JTextField address_t = new JTextField(15);
JLabel port = new JLabel("Port:");
JTextField port_t = new JTextField(5);
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
System.out.println(address_t.getText());
System.out.println(port_t.getText());
}
}
if(e.getSource()==print)
{
chrono.stop();
}
}
}
}
Panel.java:
public class Panel extends JPanel implements ActionListener {
int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,200,0);
Color blue = new Color (0,0,200);
Color yellow = new Color (200,200,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;
public Panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.8f));
g2.drawLine(20, 20, 20, this.getHeight()-50);
g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
g2.drawLine(20, 20, 15, 35);
g2.drawLine(20, 20, 25, 35);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
g.drawString("10", 0, this.getHeight()-85);
g.drawString("20", 0, this.getHeight()-125);
g.drawString("30", 0, this.getHeight()-165);
g.drawString("40", 0, this.getHeight()-205);
g.drawString("50", 0, this.getHeight()-245);
g2.drawString("Maximum: ", 20, this.getHeight()-20);
g2.drawString(Integer.toString(max), 80, this.getHeight()-20);
g2.drawString("Minimum: ", 140, this.getHeight()-20);
g2.drawString(Integer.toString(min), 200, this.getHeight()-20);
g2.drawString("Average: ", 260, this.getHeight()-20);
g2.drawString(Integer.toString(moyenne), 320, this.getHeight()-20);
g2.setColor(red);
g2.drawLine(500, this.getHeight()-25, 540, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Maximum", 560, this.getHeight()-20);
g2.setColor(blue);
g2.drawLine(640, this.getHeight()-25, 680, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Minimum", 700, this.getHeight()-20);
g2.setColor(green);
g2.drawLine(780, this.getHeight()-25, 820, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Average", 840, this.getHeight()-20);
if(!randL.isEmpty()){
g2.setColor(red);
g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);
g2.setColor(blue);
g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);
g2.setColor(green);
g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);
}
for(i = 0; i<tL.size(); i++){
int temp = randL.get(i);
int t = tL.get(i);
g2.setColor(new Color(0,0,0));
g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
// Ellipse2D circle = new Ellipse2D.Double();
//circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);
}
for(j=0;j<5;j++)
{
inc=inc+40;
g2.setColor(new Color(0,0,0));
g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
}
inc=0;
}
#Override
public void actionPerformed(ActionEvent e) {
rand = (int)(Math.random() * (60));
lastT += 80;
randL.add(rand);
tL.add(lastT);
Object obj = Collections.max(randL);
max = (int) obj;
Object obj2 = Collections.min(randL);
min = (int) obj2;
if(!randL.isEmpty()) {
degr = randL.get(k);
total += degr;
moyenne=total/randL.size();
}
k++;
if(randL.size()>=12)
{
randL.removeAll(randL);
tL.removeAll(tL);
lastT = 0;
k=0;
degr=0;
total=0;
moyenne=0;
}
repaint();
}
}
And here it what i gives me :
Sorry it's a real mess!
Any thoughts ?
Thanks.

You need to stop working with absolute/magical values, and start using the actual values of the component (width/height).
The basic problem is a simple calculation which takes the current value divides it by the maximum value and multiples it by the available width of the allowable area
int length = (value / max) * width;
value / max generates a percentage value of 0-1, which you then use to calculate the percentage of the available width of the area it will want to use.
The following example places a constraint (or margin) on the available viewable area, meaning all the lines need to be painted within that area and not use the entire viewable area of the component
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawLine {
public static void main(String[] args) {
new DrawLine();
}
public DrawLine() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int margin = 20;
int width = getWidth() - (margin * 2);
int height = getHeight() - (margin * 2);
int x = margin;
for (int index = 0; index < 4; index++) {
int y = margin + (int)(((index / 3d) * height));
int length = (int)(((index + 1) / 4d) * width);
g2d.drawLine(x, y, x + length, y);
}
g2d.dispose();
}
}
}

Related

JScrollPane with rulers didn't work

I've tried to run the example found in Java Swing 2nd Edition 7.1.3 ScrollPaneLayout. The image and the scroll have worked just fine, but the ruler hasn't. Here's my code:
public class ScrollPaneLayoutDemo extends JFrame{
JLabel label = new JLabel(new ImageIcon("img.jpg"));
public ScrollPaneLayoutDemo() {
super("ScrollPaneLayout Demo");
JScrollPane jsp = new JScrollPane(label);
JLabel[] corners = new JLabel[4];
for(int i=0; i<4; i++)
{
corners[i] = new JLabel();
corners[i].setBackground(Color.YELLOW);
corners[i].setOpaque(true);
corners[i].setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2), BorderFactory.createLineBorder(Color.RED, 1)));
}
JLabel rowheader = new JLabel() {
Font f = new Font("Serif", Font.ITALIC | Font.BOLD, 10);
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Rectangle r = g.getClipBounds();
g.setFont(f);
g.setColor(Color.RED);
for (int i = 50 - (r.y % 50); i < r.height; i += 50) {
g.drawLine(0, r.y + i, 3, r.y + i);
g.drawString("" + (r.y + i), 6, r.y + i + 3);
}
}
public Dimension getPreferredSize()
{
return new Dimension(25, (int) label.getPreferredSize().getHeight());
}
};
rowheader.setBackground(Color.YELLOW);
rowheader.setOpaque(true);
JLabel columnheader = new JLabel() {
Font f = new Font("Serif", Font.ITALIC | Font.BOLD, 10);
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Rectangle r = g.getClipBounds();
g.setFont(f);
g.setColor(Color.RED);
for (int i = 50 - (r.x % 50); i < r.width; i += 50)
{
g.drawLine(r.x + i, 0, r.x + i, 3);
g.drawString("" + (r.x + i), r.x + i - 10, 16);
}
}
public Dimension getPreferredSize()
{
return new Dimension((int) label.getPreferredSize().getWidth(),25);
}
};
columnheader.setBackground(Color.YELLOW);
columnheader.setOpaque(true);
jsp.setRowHeaderView(rowheader);
jsp.setColumnHeaderView(columnheader);
jsp.setCorner(JScrollPane.LOWER_LEFT_CORNER, corners[0]);
jsp.setCorner(JScrollPane.LOWER_RIGHT_CORNER, corners[1]);
jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, corners[2]);
jsp.setCorner(JScrollPane.UPPER_RIGHT_CORNER, corners[3]);
getContentPane().add(jsp, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args) {
new JScrollPaneDemo();
}
}
If anyone could help me with this issue I appreciate.
Dimension from child must be greater than JViewports Dimension (visible rectangle from JScrollPane), then JScrollBars or custom decorations can be visible, more in Oracle tutorial How to use ScrollPanes
search for #Annotations
e.g.
no idea why but I can't add image here :-)
from
import java.awt.*;
import javax.swing.*;
public class ScrollPaneLayoutDemo extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel label = new JLabel(new ImageIcon("img.jpg")) {
#Override
public Dimension getPreferredSize() {
return new Dimension(new Dimension(800, 600));/*icon.getIconWidth(), icon.getIconHeight()*/
}
};
public ScrollPaneLayoutDemo() {
super("ScrollPaneLayout Demo");
label.setPreferredSize(new Dimension(800, 600));
JScrollPane jsp = new JScrollPane(label);
JLabel[] corners = new JLabel[4];
for (int i = 0; i < 4; i++) {
corners[i] = new JLabel();
corners[i].setBackground(Color.YELLOW);
corners[i].setOpaque(true);
corners[i].setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2), BorderFactory.createLineBorder(Color.RED, 1)));
}
JLabel rowheader = new JLabel() {
private static final long serialVersionUID = 1L;
Font f = new Font("Serif", Font.ITALIC | Font.BOLD, 10);
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle r = g.getClipBounds();
g.setFont(f);
g.setColor(Color.RED);
for (int i = 50 - (r.y % 50); i < r.height; i += 50) {
g.drawLine(0, r.y + i, 3, r.y + i);
g.drawString("" + (r.y + i), 6, r.y + i + 3);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(25, (int) label.getPreferredSize().getHeight());
}
};
rowheader.setBackground(Color.YELLOW);
rowheader.setOpaque(true);
JLabel columnheader = new JLabel() {
private static final long serialVersionUID = 1L;
Font f = new Font("Serif", Font.ITALIC | Font.BOLD, 10);
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle r = g.getClipBounds();
g.setFont(f);
g.setColor(Color.RED);
for (int i = 50 - (r.x % 50); i < r.width; i += 50) {
g.drawLine(r.x + i, 0, r.x + i, 3);
g.drawString("" + (r.x + i), r.x + i - 10, 16);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension((int) label.getPreferredSize().getWidth(), 25);
}
};
columnheader.setBackground(Color.YELLOW);
columnheader.setOpaque(true);
jsp.setRowHeaderView(rowheader);
jsp.setColumnHeaderView(columnheader);
jsp.setCorner(JScrollPane.LOWER_LEFT_CORNER, corners[0]);
jsp.setCorner(JScrollPane.LOWER_RIGHT_CORNER, corners[1]);
jsp.setCorner(JScrollPane.UPPER_LEFT_CORNER, corners[2]);
jsp.setCorner(JScrollPane.UPPER_RIGHT_CORNER, corners[3]);
getContentPane().add(jsp, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ScrollPaneLayoutDemo();
}
});
}
}

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.

Drawing a bounding rectangle to select what area to record

How do I draw that semi-transparent rectangle on the screen?
That cannot be a JFrame because JFrames have the usual close, minimize, maximize options in top right.
if it is indeed a swing competent, How is it drawn in thin air? Without inserting it in a JFrame whatsoever?
Please tell me what it is and how I can implement it...
The immediate idea that comes to mind is to use java.awt.Robot to capture a screen shot, paint that to frameless window. From there you can simply draw a rectangle on it
Updated with example
... Took some time ...
public class SelectionRectangle {
public static void main(String[] args) {
new SelectionRectangle();
}
public SelectionRectangle() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setUndecorated(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BackgroundPane extends JPanel {
private BufferedImage background;
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
public BackgroundPane() {
selectionPane = new SelectionPane();
try {
Robot bot = new Robot();
background = bot.createScreenCapture(getScreenViewableBounds());
} catch (AWTException ex) {
Logger.getLogger(SelectionRectangle.class.getName()).log(Level.SEVERE, null, ex);
}
selectionPane = new SelectionPane();
setLayout(null);
add(selectionPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
}
#Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
int width = dragPoint.x - mouseAnchor.x;
int height = dragPoint.y - mouseAnchor.y;
int x = mouseAnchor.x;
int y = mouseAnchor.y;
if (width < 0) {
x = dragPoint.x;
width *= -1;
}
if (height < 0) {
y = dragPoint.y;
height *= -1;
}
selectionPane.setBounds(x, y, width, height);
selectionPane.revalidate();
repaint();
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(background, 0, 0, this);
g2d.dispose();
}
}
public class SelectionPane extends JPanel {
private JButton button;
private JLabel label;
public SelectionPane() {
button = new JButton("Close");
setOpaque(false);
label = new JLabel("Rectangle");
label.setOpaque(true);
label.setBorder(new EmptyBorder(4, 4, 4, 4));
label.setBackground(Color.GRAY);
label.setForeground(Color.WHITE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(SelectionPane.this).dispose();
}
});
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
label.setText("Rectangle " + getX() + "x" + getY() + "x" + getWidth() + "x" + getHeight());
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(128, 128, 128, 64));
g2d.fillRect(0, 0, getWidth(), getHeight());
float dash1[] = {10.0f};
BasicStroke dashed =
new BasicStroke(3.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
g2d.dispose();
}
}
public static Rectangle getScreenViewableBounds() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
return getScreenViewableBounds(gd);
}
public static Rectangle getScreenViewableBounds(GraphicsDevice gd) {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
if (gd != null) {
GraphicsConfiguration gc = gd.getDefaultConfiguration();
bounds = gc.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);
}
return bounds;
}
}
Update with SnipIt Example
Some people have suggested using a transparent window laid over the top of the screen, this actually won't work, as transparent windows don't actually respond to mouse clicks UNLESS they have something to be painted on them that will allow the mouse event to be trapped.
It's also been suggested that you use a Window as the selection mechanism, this is a valid answer, however, I would (personally) find that to be an unsuitable solution, as you want the user to simply click and drag the selection rectangle (IMHO).
Another approach is use something like SnipIt.
public class SnipIt {
public static void main(String[] args) {
new SnipIt();
}
public SnipIt() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setUndecorated(true);
// This works differently under Java 6
frame.setBackground(new Color(0, 0, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SnipItPane());
frame.setBounds(getVirtualBounds());
frame.setVisible(true);
}
});
}
public class SnipItPane extends JPanel {
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
public SnipItPane() {
setOpaque(false);
setLayout(null);
selectionPane = new SelectionPane();
add(selectionPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
}
#Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
int width = dragPoint.x - mouseAnchor.x;
int height = dragPoint.y - mouseAnchor.y;
int x = mouseAnchor.x;
int y = mouseAnchor.y;
if (width < 0) {
x = dragPoint.x;
width *= -1;
}
if (height < 0) {
y = dragPoint.y;
height *= -1;
}
selectionPane.setBounds(x, y, width, height);
selectionPane.revalidate();
repaint();
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Rectangle bounds = new Rectangle(0, 0, getWidth(), getHeight());
Area area = new Area(bounds);
area.subtract(new Area(selectionPane.getBounds()));
g2d.setColor(new Color(192, 192, 192, 64));
g2d.fill(area);
}
}
public class SelectionPane extends JPanel {
private JButton button;
private JLabel label;
public SelectionPane() {
button = new JButton("Close");
setOpaque(false);
label = new JLabel("Rectangle");
label.setOpaque(true);
label.setBorder(new EmptyBorder(4, 4, 4, 4));
label.setBackground(Color.GRAY);
label.setForeground(Color.WHITE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(SelectionPane.this).dispose();
}
});
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
label.setText("Rectangle " + getX() + "x" + getY() + "x" + getWidth() + "x" + getHeight());
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// I've chosen NOT to fill this selection rectangle, so that
// it now appears as if you're "cutting" away the selection
// g2d.setColor(new Color(128, 128, 128, 64));
// g2d.fillRect(0, 0, getWidth(), getHeight());
float dash1[] = {10.0f};
BasicStroke dashed =
new BasicStroke(3.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
g2d.dispose();
}
}
public static Rectangle getVirtualBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
for (GraphicsDevice gd : lstGDs) {
bounds.add(gd.getDefaultConfiguration().getBounds());
}
return bounds;
}
}
Update Multi Monitor Support to the Example Answer from #MadProgrammer.
Without ExtendedState(JFrame.MAXIMIZED_BOTH) and pack()
public SelectionRectangle() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BackgroundPane());
frame.setResizable( false );
frame.setBounds( getScreenViewableBounds() );
frame.setVisible(true);
}
});
}
public static Rectangle getScreenViewableBounds() {
GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
int minx = Integer.MAX_VALUE;
int miny = Integer.MAX_VALUE;
int maxx = Integer.MIN_VALUE;
int maxy = Integer.MIN_VALUE;
for( GraphicsDevice device : devices ) {
for( GraphicsConfiguration config : device.getConfigurations() ) {
Rectangle bounds = config.getBounds();
minx = Math.min( minx, bounds.x );
miny = Math.min( miny, bounds.y );
maxx = Math.max( maxx, bounds.x + bounds.width );
maxy = Math.max( maxy, bounds.y + bounds.height );
}
}
return new Rectangle( new Point(minx, miny), new Dimension(maxx - minx, maxy - miny) );
}
You could use a transparent, undecorated frame in order to create a basic border.
public class ScreenRectangle extends JFrame {
public ScreenRectangle() {
this.setUndecorated(true);
this.setBackground(new Color(0, 0, 0, 0.25F));
// opacity ranges 0.0-1.0 and is the fourth paramater
this.add(new DrawPanel());
}
private class DrawPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, this.getWidth(), this.getHeight());
// any other drawing
}
}
}
The frame may also need to be setOpaque, or the panel size may need to be handled, but this is the general idea of it.

Drawing rectangle on a JPanel

I want to draw a recangle on a JPanel. Am able to draw with the following code.
public class DrawingColor extends JFrame
{
public static void main(String[] args)
{
DrawingColor d = new DrawingColor();
}
public DrawingColor()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new MyComponent());
setSize(400,400);
setVisible(true);
}
public class MyComponent extends JComponent
{
#Override
public void paint(Graphics g)
{
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10, 10, height, width);
g.setColor(Color.gray);
g.fillRect(11, 11, height, width);
g.setColor(Color.red);
g.drawOval(250, 20, height, width);
g.setColor(Color.magenta);
g.fillOval(249, 19, height, width);
}
}
}
But getContentPane().add(new MyComponent());
Instead of this statement,I need to add one base panel to the frame. On the base panel I want to add the MyComponent panel.
JPanel basePanel = new JPanel();
basePanel = new MyComponent();
getContentPane().add(basePanel);
If I do like this, the rectangle is not getting visible. any idea?
And also I need to change the size of the rectangle at runtime. is it possible?
1) for Swing JComponent you have to use paintComponent() instead of paint() method
2) your JComponent doesn't returns PreferredSize
for example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
setTitle("Custom Component Graphics2D");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
CustomComponents cc = new CustomComponents();
/*cc.addComponentListener(new java.awt.event.ComponentAdapter() {
#Override
public void componentResized(ComponentEvent event) {
setSize(Math.min(getPreferredSize().width, getWidth()),
Math.min(getPreferredSize().height, getHeight()));
}
});*/
add(cc, BorderLayout.CENTER);
CustomComponents cc1 = new CustomComponents();
add(cc1, BorderLayout.EAST);
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getSize());
//setMaximumSize(getMaximumSize());
setVisible(true);
}
public static void main(String[] args) {
CustomComponent main = new CustomComponent();
main.display();
}
}
class CustomComponents extends JComponent {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(800, 600);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
Since you wanted to change the Dimensions of your Rectangle at run time, try this code for that :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RectangleTest extends JFrame {
private int x;
private int y;
private static JButton buttonFullSize;
private static JButton buttonHalfSize;
public RectangleTest() {
x = 0;
y = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel basePanel = new JPanel();
basePanel.setLayout(new BorderLayout());
final MyComponent component = new MyComponent(400, 400);
component.setOriginAndSize(0, 0, 100, 100);
buttonFullSize = new JButton("DRAW FULL SIZE");
buttonFullSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
component.setOriginAndSize(x++, y++,
(basePanel.getHeight() / 4), (basePanel.getWidth() / 4));
}
});
buttonHalfSize = new JButton("DRAW HALF SIZE");
buttonHalfSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
component.setOriginAndSize(x++, y++,
(basePanel.getHeight() / 8), (basePanel.getWidth() / 8));
}
});
basePanel.add(buttonHalfSize, BorderLayout.PAGE_START);
basePanel.add(component, BorderLayout.CENTER);
basePanel.add(buttonFullSize, BorderLayout.PAGE_END);
setContentPane(basePanel);
pack();
setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RectangleTest();
}
});
}
}
class MyComponent extends JComponent {
private int x;
private int y;
private int width;
private int height;
private int compWidth;
private int compHeight;
MyComponent(int w, int h) {
this.compWidth = w;
this.compHeight = h;
}
public void setOriginAndSize(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(compWidth, compHeight));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getBackground());
g.fillRect(x, y, width, height);
g.setColor(Color.RED);
g.drawOval(x, y, width, height);
g.setColor(Color.MAGENTA);
g.fillOval(x, y, width, height);
}
}
I had tried drawing a square and circle, dynamically varying the size at runtime....attaching the complete code ..if it helps.
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
import java.*;
import java.awt.Canvas;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class DisplayCanvas extends Canvas
{
static boolean clip = false;
static boolean clipfurther = false;
static boolean isReset = false, isSlider = false;
int w, h;
static int wi = 300, hi = 300;
public DisplayCanvas()
{
//setSize(300, 300);
setBounds(20, 40, 300, 300);
setBackground(Color.white);
}
public void paint(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
w = getSize().width;
h = getSize().height;
if(clip)
{
// Ellipse2D e = new Ellipse2D.Float(w/4.0f,h/4.0f,w/2.0f,h/2.0f);
Rectangle2D r = null;
if(isSlider)
{
r = new Rectangle2D.Float((w)/(4.0f), (h)/(4.0f), wi/2.0f, hi/2.0f);
// isSlider=false;
}
else
r = new Rectangle2D.Float(w/4.0f, h/4.0f, wi/2.0f, hi/2.0f);
//g2.setClip(e);
System.out.println("Width : "+ wi +" Height : "+ hi);
g2.setClip(r);
System.out.println(g2.getClipBounds());
if(shape.selectedcolor == "red")
{
g2.setColor(Color.red);
}
else if(shape.selectedcolor == "blue")
{
g2.setColor(Color.BLUE);
}
else if(shape.selectedcolor == "yellow")
{
g2.setColor(Color.yellow);
}
//g2.setColor(Color.RED);
g2.fillRect(0, 0, w, h);
}
else if(clipfurther)
{
//Rectangle r = new Rectangle(w/4, h/4, w/4, h/4);
Ellipse2D r = new Ellipse2D.Float(w/4.0f, h/4.0f, wi/2.0f, hi/2.0f);
g2.clip(r);
//g2.setColor(Color.green);
//g2.setColor(Color.getColor(shape.selectedcolor));
if(shape.selectedcolor == "red")
{
g2.setColor(Color.red);
}
else if(shape.selectedcolor == "blue")
{
g2.setColor(Color.BLUE);
}
else if(shape.selectedcolor == "yellow")
{
g2.setColor(Color.yellow);
}
g2.fillRect(0, 0, w, h);
}
}
}
class RadioListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == shape.circle)
{
shape.selectedcolor = shape.selectedcolor_reset;
System.out.println("Inside circle "+ shape.selectedcolor_reset);
System.out.println("2222222222");
DisplayCanvas.clip = true;
DisplayCanvas.clipfurther = false;
shape.canvas.repaint();
}
if (e.getSource() == shape.square)
{
shape.selectedcolor = shape.selectedcolor_reset;
System.out.println("333333333333333");
DisplayCanvas.clip = false;
DisplayCanvas.clipfurther = true;
shape.canvas.repaint();
}
}
}
class shape extends JFrame implements ActionListener
{
static String fname;
static JPanel panel, draw;
static Container contentpane, draw_pane;
static JFrame frame;
static JLayeredPane layer, draw_layer;
static JTextField user;
static JButton reset, cancel;
static JLabel file1, file2;
static JTextField text1;
static JRadioButton circle, square;
static JInternalFrame iframe, errmessage;
static JComboBox colors;
static JEditorPane sqc;
static JScrollPane scroller;
static JSlider slider;
String colors_array[]={"...", "red", "blue", "yellow"};
static DisplayCanvas canvas;
static String selectedcolor, selectedcolor_reset;
shape()
{
canvas=new DisplayCanvas();
panel= new JPanel();
panel.setBounds(20,20,250,140);
//panel.setLayout(new FlowLayout(10, 10, 10));
panel.setLayout(null);
contentpane = getContentPane();
contentpane.add(canvas);
//draw_pane=getContentPane();
layer = new JLayeredPane();
layer.setBounds(50,245,300,205);
layer.setForeground(Color.blue);
draw_layer = new JLayeredPane();
draw_layer.setBounds(200, 200, 80, 30);
draw_layer.setForeground(Color.BLACK);
draw = new JPanel();
draw.setBounds(20, 20, 250, 300);
draw.setLayout(null);
reset = new JButton("RESET");
reset.setBounds(360, 60, 100, 25);
circle = new JRadioButton("Square");
circle.setBounds(400, 100, 100, 40);
circle.setActionCommand("encryption");
square = new JRadioButton("Circle");
square.setBounds(330,100, 60, 40);
square.setActionCommand("decryption");
colors = new JComboBox(colors_array);
colors.setBounds(405, 140, 80, 30);
colors.setVisible(true);
file1 = new JLabel(" Select Color :");
file1.setBounds(320, 130, 150, 50);
//defining the Button Group for the Radio Buttons
ButtonGroup group = new ButtonGroup();
group.add(circle);
group.add(square);
cancel = new JButton("Exit");
cancel.setBounds(365, 250, 85, 25);
file2 = new JLabel("SIZE :");
file2.setBounds(336, 180, 150, 50);
setslider(0, 100, 100, 25, 5);
slider.setBounds(386, 190, 100, 50);
slider.setVisible(true);
panel.add(file2);
panel.add(layer);
panel.add(circle);
panel.add(square);
panel.add(colors);
panel.add(slider);
panel.add(file1);
panel.add(reset);
panel.add(cancel);
//panel.add(new CircleDraw());
//draw.add(draw_layer);
// draw_pane.add(draw);
contentpane.add(panel);
// contentpane.add(draw);
// contentpane.add(scroller);
RadioListener radio = new RadioListener();
circle.addActionListener(radio);
square.addActionListener(radio);
reset.addActionListener(this);
cancel.addActionListener(this);
colors.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JComboBox cb = (JComboBox)ae.getSource();
selectedcolor = (String)cb.getSelectedItem();
System.out.println(selectedcolor);
selectedcolor_reset = selectedcolor;
System.out.println("SELECTED "+ cb.getSelectedIndex());
canvas.repaint();
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== cancel)
{
System.exit(0);
}
if (e.getSource() == reset)
{
System.out.println("111111111");
DisplayCanvas.clip = true;
DisplayCanvas.clipfurther = false;
DisplayCanvas.isReset = true;
shape.selectedcolor = "...";
System.out.println(" PREVIOUS " + selectedcolor_reset);
DisplayCanvas.hi = DisplayCanvas.wi = 300;
canvas.repaint();
}
}
public class SliderListener implements ChangeListener
{
public SliderListener()
{
}
public void stateChanged(ChangeEvent e)
{
JSlider slider = (JSlider)e.getSource();
System.out.println(slider.getValue());
DisplayCanvas.wi = slider.getValue() * 3;
DisplayCanvas.hi = DisplayCanvas.wi;
DisplayCanvas.isSlider = true;
canvas.repaint();
}
}
public void setslider(int min,int max,int init,int mjrtk,int mintk)
{
slider = new JSlider(JSlider.HORIZONTAL, min, max, init);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(mjrtk);
slider.setMinorTickSpacing(mintk);
slider.setPaintLabels(true);
slider.addChangeListener((ChangeListener) new SliderListener());
}
}
public class display
{
static JFrame frame;
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
frame=new shape();
frame.setBounds(380, 200, 500, 400);
frame.setTitle("SHAPE AND COLOR");
frame.setVisible(true);
}
}

Java GUI repainting error?

This one's a tough one - I have a JFrame that generates JTextFields. When I go from generating 2 JTextFields to 12 JTextfields (for example), I see some error where there is an extra differently-sized JTextField at the end. It seems to be a repaint error.
Main.java code:
import java.awt.*;
import javax.swing.*;
public class Main {
public static Display display = new Display();
public static void main(String[] args) {
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display.setVisible(true);
}
}
Display.java code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Display extends JFrame {
final int FRAME_WIDTH = 820;
final int FRAME_HEIGHT = 700;
final int X_OFFSET = 40;
final int Y_OFFSET = 40;
final int GRAPH_OFFSETX = 35;
final int GRAPH_OFFSETY = 60;
final int GRAPH_WIDTH = 500;
final int GRAPH_HEIGHT = 500;
final int GRAPH_INTERVAL = 20;
JButton submit;
JTextField top;
JTextField bottom;
JTextField numPoint;
JPanel bpanel;
JPanel points;
int maxPoints;
public Display() {
init();
}
public void init() {
setBackground(Color.WHITE);
setLocation(X_OFFSET, Y_OFFSET);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Geometric Transformations");
getContentPane().setLayout(null);
setDefaultLookAndFeelDecorated(true);
top = new JTextField(); // parameter is size of input characters
top.setText("1 2 3");
top.setBounds(590, 150, 120, 25);
bottom = new JTextField(); // parameter is size of input characters
bottom.setText("5 6 7");
bottom.setBounds(590, 200, 120, 25);
numPoint = new JTextField();
numPoint.setText("Number of Points?");
numPoint.setBounds(550,200,200,25);
this.add(numPoint);
SubmitButton submit = new SubmitButton("Submit");
submit.setBounds(570, 250, 170, 25);
bpanel = new JPanel(new GridLayout(2,3));
bpanel.add(top);
bpanel.add(bottom);
bpanel.add(submit);
points = new JPanel(new GridLayout(2,2));
points.setBounds(540,250,265,60);
this.add(points);
bpanel.setBounds(550,100,200,70);
this.add(bpanel, BorderLayout.LINE_START);
Component[] a = points.getComponents();
System.out.println(a.length);
repaint();
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.fillRect(100, 100, 20, 30);
g.setColor(Color.BLACK);
genGraph(g, GRAPH_OFFSETX, GRAPH_OFFSETY, GRAPH_WIDTH, GRAPH_HEIGHT, GRAPH_INTERVAL);
}
public void genGraph (Graphics g, int x, int y, int width, int height, int interval) {
// draw background
int border = 5;
g.setColor(Color.BLACK);
width = width - (width % interval);
height = height - (height % interval);
for (int col=x; col <= x+width; col+=interval) {
g.drawLine(col, y, col, y+height);
}
for (int row=y; row <= y+height; row+=interval) {
g.drawLine(x, row, x+width, row);
}
}
class SubmitButton extends JButton implements ActionListener {
public SubmitButton(String title){
super(title);
addActionListener(this);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
maxPoints = Integer.parseInt(numPoint.getText()) * 2;
points.removeAll();
for (int i=0; i<maxPoints; i++) {
JTextField textField = new JTextField();
points.add(textField);
}
points.validate(); // necessary when adding components to a JPanel
// http://stackoverflow.com/questions/369823/java-gui-repaint-problem-solved
// What to Check:
// Things between commas are either spaces (which will be stripped later)
// or numbers!
// Pairs must match up!
}
}
}
The new components are redrawn over the previous ones.
I added points.repaint(); after points.validate(); and the problem was gone.
Note: I was annoyed with the issue of repainting of the grid too (put the window in front then back, you will see).
From a quick search, it seems better to avoid painting directly on the JFrame, but instead delegate that to a sub-component. If I am wrong, somebody tell me.
Here is my solution (imperfect, I leave to you the task to improve it... :-P
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SODisplay extends JFrame {
final int FRAME_WIDTH = 820;
final int FRAME_HEIGHT = 700;
final int X_OFFSET = 40;
final int Y_OFFSET = 40;
JButton submit;
JTextField top;
JTextField bottom;
JTextField numPoint;
JPanel bpanel;
JPanel points;
GridPanel grid;
int maxPoints;
public SODisplay() {
init();
}
public void init() {
setBackground(Color.WHITE);
setLocation(X_OFFSET, Y_OFFSET);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("Geometric Transformations");
getContentPane().setLayout(null);
setDefaultLookAndFeelDecorated(true);
grid = new GridPanel();
grid.setBounds(0,0,530,FRAME_HEIGHT);
this.add(grid);
top = new JTextField(); // parameter is size of input characters
top.setText("1 2 3");
top.setBounds(590, 150, 120, 25);
bottom = new JTextField(); // parameter is size of input characters
bottom.setText("5 6 7");
bottom.setBounds(590, 200, 120, 25);
numPoint = new JTextField();
numPoint.setText("Number of Points?");
numPoint.setBounds(550,200,200,25);
this.add(numPoint);
SubmitButton submit = new SubmitButton("Submit");
submit.setBounds(570, 250, 170, 25);
bpanel = new JPanel(new GridLayout(2,3));
bpanel.add(top);
bpanel.add(bottom);
bpanel.add(submit);
points = new JPanel(new GridLayout(2,2));
points.setBounds(540,250,265,60);
this.add(points);
bpanel.setBounds(550,100,200,70);
this.add(bpanel, BorderLayout.LINE_START);
Component[] a = points.getComponents();
System.out.println(a.length);
repaint();
}
class SubmitButton extends JButton implements ActionListener {
public SubmitButton(String title){
super(title);
addActionListener(this);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
maxPoints = Integer.parseInt(numPoint.getText()) * 2;
points.removeAll();
for (int i=0; i<maxPoints; i++) {
JTextField textField = new JTextField();
points.add(textField);
}
points.validate(); // necessary when adding components to a JPanel
points.repaint();
// http://stackoverflow.com/questions/369823/java-gui-repaint-problem-solved
// What to Check:
// Things between commas are either spaces (which will be stripped later)
// or numbers!
// Pairs must match up!
}
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SODisplay display = new SODisplay();
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display.setVisible(true);
}
});
}
class GridPanel extends JPanel {
// Or drop the offset and adjust the placement of the component
final int GRAPH_OFFSETX = 35;
final int GRAPH_OFFSETY = 60;
final int GRAPH_WIDTH = 500;
final int GRAPH_HEIGHT = 500;
final int GRAPH_INTERVAL = 20;
public GridPanel() {
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.fillRect(100, 100, 20, 30);
g.setColor(Color.BLACK);
genGraph(g, GRAPH_OFFSETX, GRAPH_OFFSETY, GRAPH_WIDTH, GRAPH_HEIGHT, GRAPH_INTERVAL);
}
public void genGraph (Graphics g, int x, int y, int width, int height, int interval) {
// draw background
int border = 5;
g.setColor(Color.BLACK);
width = width - (width % interval);
height = height - (height % interval);
for (int col=x; col <= x+width; col+=interval) {
g.drawLine(col, y, col, y+height);
}
for (int row=y; row <= y+height; row+=interval) {
g.drawLine(x, row, x+width, row);
}
}
}
}
That's just my test code in one file for simplicity, you might want to dissect it differently, of course.

Categories

Resources