I'm looking for some help regarding a Java program I'm writing. I need to display a simple bar graph consisting of rectangles based off of data saved in an array that has been generated by a JList selection event. However, nothing is drawn in the JPanel and I cannot figure out how to fix it.
List Selection Event (For reference)
try
{
BufferedReader in = new BufferedReader((new FileReader("scores.txt")));
String sLine;
while ((sLine = in.readLine()) != null)
{
vecAthlete.addElement(new Stage3_DataFile(sLine));
}
String[] saAthlete = new String[vecAthlete.size()];
for (int iI = 0; iI < vecAthlete.size(); iI++)
saAthlete[iI] = vecAthlete.get(iI).sName;
jList_Athlete.setListData(saAthlete);
jList_Athlete.setSelectedIndex(0);
// Reading input line by line
// Close file
in.close();
}
catch (IOException e)
{
System.out.println("ERROR: Could not read text file!");
}
jList_Athlete.addListSelectionListener(new javax.swing.event.ListSelectionListener()
{
public void valueChanged(javax.swing.event.ListSelectionEvent e)
{
double[][] daRun = new double[2][7];
final double dScoreUsed = 5;
double dMinScoreRun1 = 10, dMaxScoreRun1 = 0;
double dMinScoreRun2 = 10, dMaxScoreRun2 = 0;
double dTotalRun1 = 0, dTotalRun2 = 0;
jLabel_Athlete.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sName);
jLabel_Country.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sCountry);
jLabel_Run1_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[0]);
jLabel_Run1_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[1]);
jLabel_Run1_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[2]);
jLabel_Run1_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[3]);
jLabel_Run1_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[4]);
jLabel_Run1_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[5]);
jLabel_Run1_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[6]);
jLabel_Run2_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[0]);
jLabel_Run2_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[1]);
jLabel_Run2_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[2]);
jLabel_Run2_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[3]);
jLabel_Run2_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[4]);
jLabel_Run2_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[5]);
jLabel_Run2_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[6]);
daRun[0][0] = Double.parseDouble(jLabel_Run1_Score_1.getText());
daRun[0][1] = Double.parseDouble(jLabel_Run1_Score_2.getText());
daRun[0][2] = Double.parseDouble(jLabel_Run1_Score_3.getText());
daRun[0][3] = Double.parseDouble(jLabel_Run1_Score_4.getText());
daRun[0][4] = Double.parseDouble(jLabel_Run1_Score_5.getText());
daRun[0][5] = Double.parseDouble(jLabel_Run1_Score_6.getText());
daRun[0][6] = Double.parseDouble(jLabel_Run1_Score_7.getText());
daRun[1][0] = Double.parseDouble(jLabel_Run2_Score_1.getText());
daRun[1][1] = Double.parseDouble(jLabel_Run2_Score_2.getText());
daRun[1][2] = Double.parseDouble(jLabel_Run2_Score_3.getText());
daRun[1][3] = Double.parseDouble(jLabel_Run2_Score_4.getText());
daRun[1][4] = Double.parseDouble(jLabel_Run2_Score_5.getText());
daRun[1][5] = Double.parseDouble(jLabel_Run2_Score_6.getText());
daRun[1][6] = Double.parseDouble(jLabel_Run2_Score_7.getText());
for(int i = 0; i < 7; i++)
{
if(daRun[0][i] <= dMinScoreRun1)
{
dMinScoreRun1 = daRun[0][i];
}
if(daRun[0][i] >= dMaxScoreRun1)
{
dMaxScoreRun1 = daRun[0][i];
}
dTotalRun1 += daRun[0][i];
}
dTotalRun1 = (dTotalRun1 - dMinScoreRun1 - dMaxScoreRun1) / dScoreUsed;
jLabel_TotalRun1.setText(String.valueOf(dTotalRun1));
jLabel_Run1AddInfo.setText("Min Score: " + (dMinScoreRun1) + ", Max Score: " + (dMaxScoreRun1));
for(int i = 0; i < 7; i++)
{
if(daRun[1][i] <= dMinScoreRun2)
{
dMinScoreRun2 = daRun[1][i];
}
if(daRun[1][i] >= dMaxScoreRun2)
{
dMaxScoreRun2 = daRun[1][i];
}
dTotalRun2 += daRun[1][i];
}
dTotalRun2 = (dTotalRun2 - dMinScoreRun2 - dMaxScoreRun2) / dScoreUsed;
jLabel_TotalRun2.setText(String.valueOf(dTotalRun2));
jLabel_Run2AddInfo.setText("Min Score: " + (dMinScoreRun2) + ", Max Score: " + (dMaxScoreRun2));
if(dTotalRun1 >= dTotalRun2)
jLabel_FinalScore.setText(String.valueOf(dTotalRun1));
else
jLabel_FinalScore.setText(String.valueOf(dTotalRun2));
jPanel_Graph.repaint();
}
});
JPanel Definitions
JPanel jPanel_Graph = new JPanel();
jPanel_Graph.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
jPanel_Graph.setBounds(729, 159, 700, 200);
frame.getContentPane().add(jPanel_Graph);
img = new BufferedImage(jPanel_Graph.getWidth(),
jPanel_Graph.getHeight(),
BufferedImage.TYPE_INT_RGB);
g2dimg = (Graphics2D)img.getGraphics();
// Draw a filled white coloured rectangle on the entire area to clear it.
g2dimg.setPaint(Color.WHITE);
g2dimg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
JPanel Drawing Event
class myJPanel extends JPanel
{
private Rectangle2D.Double rectangle;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < 7; i++)
{
dHeight = daRun[0][i];
rectangle = new Rectangle2D.Double(dX, dY, dWidth, dHeight);
g2dimg.setPaint(Color.red);
g2dimg.draw(rectangle);
g2dimg.fill(rectangle);
dX += dXIncrement;
g2dimg.drawImage(img, 0, 0, null);
}
}
}
Thanks in advance!
So, from what I can tell, there is no way for your "graph" to know what it should paint. The basic idea is, your "graph" should be focused on painting the data/model, so you need some way to tell it when the data changes.
There are lots of ways you might do this, for example, you could devise a model, which you add/remove data to, which could trigger updates that the graph pane listeners for and then updates itself with the new data.
Or you just pass the data you want updated directly to the graph pane, which in this case, might the simplest solution available to you
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private GraphPane graphPane;
public TestPane() {
setLayout(new BorderLayout());
DefaultListModel<Double> listmodel = new DefaultListModel<>();
for (int index = 0; index < 100; index++) {
listmodel.addElement(Math.random());
}
graphPane = new GraphPane();
add(graphPane);
JList<Double> listData = new JList<>(listmodel);
add(new JScrollPane(listData), BorderLayout.WEST);
listData.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
graphPane.setData(listData.getSelectedValuesList().toArray(new Double[0]));
}
});
}
}
public class GraphPane extends JPanel {
private Double[] data;
public void setData(Double[] data) {
this.data = data;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (data != null && data.length > 0) {
Graphics2D g2d = (Graphics2D) g.create();
double barWidth = getWidth() / (double)data.length;
int xPos = 0;
for (Double value : data) {
double height = (getHeight() - 1) * value;
Rectangle2D bar = new Rectangle2D.Double(xPos, getHeight() - height, barWidth, height);
g2d.setColor(Color.GREEN);
g2d.fill(bar);
g2d.setColor(Color.BLACK);
g2d.draw(bar);
xPos += barWidth;
}
g2d.dispose();
}
}
}
}
Related
I am trying to make a chess game in java, by having a class of pieces and a subclass for each piece. However, When I try to draw the pieces, The position doesn't seem to register.
Here is my Piece class:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.net.URL;
public class Piece {
public int Id;
public int color;
public int state;
public Image Sprite;
public AffineTransform tx;
public boolean dragged;
public int x;
public int y;
public Piece(int Id, int color, int position){
dragged = false;
this.Id = Id;
this.color = color;
int x = 100*(position % 8);
int y = 100*(position / 8);
System.out.println(x);
tx = AffineTransform.getTranslateInstance(x, y);
init(x, y);
}
private void init (double a, double b) {
tx.setToTranslation(a, b);
tx.scale(0.1, 0.1);
}
private void update(){
tx.setToTranslation(x*1000, y*1000);
tx.scale(0.1, 0.1);
}
protected Image getImage(String path) {
Image tempImage = null;
try {
URL imageURL = Piece.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
} catch (Exception e) {e.printStackTrace();}
return tempImage;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
update();
g2.drawImage(Sprite, tx, null);
}
}
my pawn class:
public class Pawn extends Piece {
public Pawn(int Id, int color, int position) {
super(Id, color, position);
this.state = 0;
String path = "/imgs/Pieces/";
if(color == 0){
path += "W";
} else{
path += "B";
}
path += "_Pawn.png";
Sprite = getImage(path);
}
}
my Board class:
Piece[][] board;
public Board(){
board = new Piece[8][8];
for(int i = 0; i < 8; i++){
board[1][i] = new Pawn(i, 1, 8+i);
}
for(int i = 0; i < 8; i++){
board[6][i] = new Pawn(i, 0, 8+i);
}
}
}
and my main class:
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main extends JPanel implements ActionListener, MouseListener, KeyListener{
Color GREEN = new Color( 41, 176, 59);
Color WHITE = new Color(254, 255, 228);
Board board = new Board();
public static void main(String[] args) {
new Main();
}
public void paint(Graphics g){
super.paintComponent(g);
boolean flag = true;
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if(flag){
g.setColor(WHITE);
} else{
g.setColor(GREEN);
}
g.fillRect((j*100), (i*100), ((j+1)*100), ((i+1)*100));
flag = !flag;
}
flag = !flag;
}
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if(board.board[i][j] != null){
board.board[i][j].paint(g);
}
}
}
}
public Main() {
JFrame f = new JFrame("Chess");
f.setSize(new Dimension(800, 800));
f.setBackground(Color.blue);
f.add(this);
f.setResizable(false);
f.setLayout(new GridLayout(1,2));
f.addMouseListener(this);
f.addKeyListener(this);
Timer t = new Timer(16, this);
t.start();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
I had previously written a game that implemented this techqnique, so I'm not sure what could have gone wrong with this one
It's really important to read the documentation, especially for something that is (to my simple brain), complicated.
If you have a read of the documentation for AffineTransform#scale
Concatenates this transform with a scaling transformation
(emphis added by me)
This is important, as it seems to apply that each time you call it, it will apply ANOTHER scaling operation.
Based on your avaliable code, this means that when the Piece is created, a scale is applied and the each time it's painted, a new scale is applied, until you're basically scaled out of existence.
Sooo. I took out your init (applied the scale within the constructor directly instead) and update methods and was able to get a basic result
Scaling from 1.0, 0.75, 0.5, 0.25and0.1` (it's there but I had to reduce the size of the output)
Runnable example...
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new Main());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class Main extends JPanel implements ActionListener, MouseListener, KeyListener {
Color GREEN = new Color(41, 176, 59);
Color WHITE = new Color(254, 255, 228);
Board board;
public Main() throws IOException {
board = new Board();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 800);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
super.paintComponent(g);
boolean flag = true;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (flag) {
g.setColor(WHITE);
} else {
g.setColor(GREEN);
}
g.fillRect((j * 100), (i * 100), ((j + 1) * 100), ((i + 1) * 100));
flag = !flag;
}
flag = !flag;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board.board[i][j] != null) {
board.board[i][j].paint(g);
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
public class Board {
Piece[][] board;
public Board() throws IOException {
board = new Piece[8][8];
for (int i = 0; i < 8; i++) {
board[1][i] = new Pawn(i, 1, 8 + i);
}
for (int i = 0; i < 8; i++) {
board[6][i] = new Pawn(i, 0, 16 + i);
}
}
}
public class Pawn extends Piece {
public Pawn(int Id, int color, int position) throws IOException {
super(Id, color, position);
this.state = 0;
String path = "/imgs/Pieces/";
if (color == 0) {
path += "W";
} else {
path += "B";
}
path += "_Pawn.png";
Sprite = getImage(path);
}
}
public class Piece {
public int Id;
public int color;
public int state;
public Image Sprite;
public AffineTransform tx;
public boolean dragged;
public int x;
public int y;
public Piece(int Id, int color, int position) {
dragged = false;
this.Id = Id;
this.color = color;
x = 100 * (position % 8);
y = 100 * (position / 8);
System.out.println(x + "x" + y);
tx = AffineTransform.getTranslateInstance(x, y);
tx.scale(0.1, 0.1);
}
protected Image getImage(String path) throws IOException {
BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setFont(new JLabel().getFont().deriveFont(Font.PLAIN, 16));
g2d.setColor(Color.BLACK);
FontMetrics fm = g2d.getFontMetrics();
int cellX = x;
int cellY = y;
String text = x + "x" + y;
int x = (100 - fm.stringWidth(text)) / 2;
int y = ((100 - fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString(text, x, y);
g2d.setStroke(new BasicStroke(16));
g2d.drawRect(0, 0, 99, 99);
g2d.dispose();
return img;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(Sprite, tx, null);
}
}
}
I have 2 classes: TestingPanel and SnipIt.
SnipIt is used for selecting an area on the screen.
TestingPanel is the main frame, containing a button to run method Snip() and receiving the return values.
If I test the SnipIt class separately, it works. But if I create a SnipIt object and run method Snip() from TestingPanel class, it doesn't work. The GUI just freezes and doesn't respond to mouse click or drag event. I guess something block the thread handle the mouse events but I'm not sure.
I have been stuck for couple hours and still don't know what caused the issue. Please help.
TestingPanel
package Testing;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestingPanel {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestingPanel window = new TestingPanel();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestingPanel() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 200, 160);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnSnip = new JButton("Snip");
btnSnip.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getSelectionSize();
}
});
btnSnip.setBounds(47, 87, 89, 23);
frame.getContentPane().add(btnSnip);
}
private void getSelectionSize() {
int[] size = new int[4];
Thread worker = new Thread(new Runnable() {
public void run() {
SnipIt sn = new SnipIt();
sn.snip();
while(!sn.complete) {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
size[0] = sn.returnSize()[0];
size[1] = sn.returnSize()[1];
size[2] = sn.returnSize()[2];
size[3] = sn.returnSize()[3];
}
});
worker.start();
try {
worker.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(size[0] + " " + size[1] + " " + size[2] + " " + size[3]);
}
}
SnipIt
package Testing;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class SnipIt {
private int recX = 0;
private int recY = 0;
private int recWidth = 0;
private int recHeight = 0;
public boolean complete = false;
/*
public static void main(String [] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SnipIt s = new SnipIt();
s.snip();
}
});
}
*/
public void snip() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame();
frame.setUndecorated(true);
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);
}
#SuppressWarnings("serial")
public class SnipItPane extends JPanel {
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
private ControlPane controlPane;
public SnipItPane() {
setOpaque(false);
setLayout(null);
selectionPane = new SelectionPane();
controlPane = new ControlPane();
add(selectionPane);
add(controlPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
controlPane.setLocation(mouseAnchor);
controlPane.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();
int controlY = y + height + 5;
controlPane.setBounds(x, controlY, width, 25);
controlPane.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(102, 102, 102, 80));
g2d.fill(area);
}
}
#SuppressWarnings("serial")
public class ControlPane extends JPanel {
private JButton btnClose;
public ControlPane() {
setOpaque(false);
btnClose = new JButton("Save");
setLayout(new BorderLayout());
this.add(btnClose, BorderLayout.NORTH);
btnClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
complete = true;
SwingUtilities.getWindowAncestor(ControlPane.this).dispose();
}
});
}
}
#SuppressWarnings("serial")
public class SelectionPane extends JPanel {
public SelectionPane() {
setOpaque(false);
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
recX = getX();
recY = getY();
recWidth = getWidth();
recHeight = getHeight();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
float strokeWidth = 1.0f;
float dash1[] = {10.0f};
BasicStroke dashed =
new BasicStroke(strokeWidth,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
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;
}
public int[] returnSize() {
int[] size = new int[4];
size[0] = recX;
size[1] = recY;
size[2] = recWidth;
size[3] = recHeight;
return size;
}
}
You're running the Snipit application in a background thread and then freezing that thread with Thread.sleep and a while true block, something guaranteed to freeze the GUI. Read Lesson: Concurrency in Swing and then be sure to always run Swing applications on the single Swing event thread, and do any long running or sleeping code in a background thread.
Possible solutions to your issue:
Make the Snipit window an undecorated modal dialog. This way program flow from the calling code stops when the dialog is visible and resumes when no longer visible.
Or Make the Snipit window JFrame an instance field of the class and allow outside classes to add listeners to it so that they will be notified when it closes.
e.g.,
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog.ModalityType;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestSnipit {
private static void createAndShowGui() {
boolean runTest = true;
if (runTest) {
TestingPanel.main(null);
} else {
SnipIt.main(null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class TestingPanel {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestingPanel window = new TestingPanel();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestingPanel() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 200, 160);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnSnip = new JButton("Snip");
btnSnip.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getSelectionSize();
}
});
btnSnip.setBounds(47, 87, 89, 23);
frame.getContentPane().add(btnSnip);
}
private void getSelectionSize() {
int[] size = new int[4];
// !!
SnipIt sn = new SnipIt();
sn.snip(frame);
// Thread worker = new Thread(new Runnable() {
// public void run() {
// SnipIt sn = new SnipIt();
// sn.snip();
//
// while (!sn.complete) {
// try {
// Thread.sleep(800);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
size[0] = sn.returnSize()[0];
size[1] = sn.returnSize()[1];
size[2] = sn.returnSize()[2];
size[3] = sn.returnSize()[3];
// }
// });
//
// worker.start();
//
// try {
// worker.join();
// } catch (InterruptedException e1) {
// e1.printStackTrace();
// }
System.out.println(size[0] + " " + size[1] + " " + size[2] + " " + size[3]);
}
}
class SnipIt {
private int recX = 0;
private int recY = 0;
private int recWidth = 0;
private int recHeight = 0;
public boolean complete = false;
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SnipIt s = new SnipIt();
s.snip(null); // !!
}
});
}
public void snip(Window owner) { // !!
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
// JFrame frame = new JFrame();
JDialog frame = new JDialog(owner, null, ModalityType.APPLICATION_MODAL); // !!
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // !!
frame.setLayout(new BorderLayout());
frame.add(new SnipItPane());
frame.setBounds(getVirtualBounds());
frame.setVisible(true);
}
#SuppressWarnings("serial")
public class SnipItPane extends JPanel {
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
private ControlPane controlPane;
public SnipItPane() {
setOpaque(false);
setLayout(null);
selectionPane = new SelectionPane();
controlPane = new ControlPane();
add(selectionPane);
add(controlPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
controlPane.setLocation(mouseAnchor);
controlPane.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();
int controlY = y + height + 5;
controlPane.setBounds(x, controlY, width, 25);
controlPane.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(102, 102, 102, 80));
g2d.fill(area);
}
}
#SuppressWarnings("serial")
public class ControlPane extends JPanel {
private JButton btnClose;
public ControlPane() {
setOpaque(false);
btnClose = new JButton("Save");
setLayout(new BorderLayout());
this.add(btnClose, BorderLayout.NORTH);
btnClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
complete = true;
SwingUtilities.getWindowAncestor(ControlPane.this).dispose();
}
});
}
}
#SuppressWarnings("serial")
public class SelectionPane extends JPanel {
public SelectionPane() {
setOpaque(false);
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
recX = getX();
recY = getY();
recWidth = getWidth();
recHeight = getHeight();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
float strokeWidth = 1.0f;
float dash1[] = { 10.0f };
BasicStroke dashed = new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
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;
}
public int[] returnSize() {
int[] size = new int[4];
size[0] = recX;
size[1] = recY;
size[2] = recWidth;
size[3] = recHeight;
return size;
}
}
A side issue unrelated to your initial problem is your use of null layougs. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
I'm writing a GUI for my neural network(https://github.com/banana01/Neural-Network If you need to see any other classes) to show a map of the network and I have a map organised by layers. I would like to be able to draw connections between the nodes on a transparent JPanel that is on top of the JPanel that has the layers and nodes in it.
I have read the following question but that requires the class be a JFrame, I would like to be able to do it in a JPanel so I can add it to a tab so I can have different tabs for different things such as the map, the input, setting etc.
placing a transparent JPanel on top of another JPanel not working
Here is my current class, lacking any sort of overlay layer.
public class NeuralNetworkDisplay extends JPanel //implements MouseListener
{
private Network ntk;
JPanel[] layerPanels;
JPanel[] layerSubPanels;
JButton[] nodeButtons;
JSplitPane splitPane;
JLayeredPane NNMap;
JPanel test;
ArrayList<Layer> layers = new ArrayList<Layer>();
ArrayList<Node[]> nodes = new ArrayList<Node[]>();
public NeuralNetworkDisplay(Network ntk)
{
setNtk(ntk);
parseNetworkDesign();
splitPane = new JSplitPane();
NNMap = new JLayeredPane();
test = new JPanel();
NNMap.setLayout(new GridLayout(3,1,5,5));
splitPane.setRightComponent(NNMap);
add(splitPane);
}
public void init()
{
drawLayers();
drawNodes();
}
public void parseNetworkDesign()
{
for (int i = 0;i < ntk.getLayers().size(); i++)
{
layers.add(ntk.getLayers().get(i));
}
for (int i = 0; i < layers.size(); i++)
{
nodes.add(layers.get(i).getNodes().toArray(new Node[layers.get(i).getNodes().size()]));
}
}
public Network getNtk() {
return ntk;
}
public void setNtk(Network ntk) {
this.ntk = ntk;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
public ArrayList<Layer> getLayers() {
return layers;
}
public void setLayers(ArrayList<Layer> layers) {
this.layers = layers;
}
public ArrayList<Node[]> getNodes() {
return nodes;
}
public int getNodesSize() {
return nodes.size();
}
public int getLayersSize() {
return layers.size();
}
public void setNodes(ArrayList<Node[]> nodes) {
this.nodes = nodes;
}
public void drawLayers()
{
layerPanels = new JPanel[getLayersSize()];
layerSubPanels = new JPanel[getLayersSize()];
for (int i = 0; i < layerPanels.length; i++)
{
layerPanels[i] = new JPanel();
layerSubPanels[i] = new JPanel();
layerPanels[i].setLayout(new FlowLayout());
layerSubPanels[i].setLayout(new GridLayout(3,5,5,5));
layerPanels[i].add(new JLabel("Layer::"+i));
layerPanels[i].add(layerSubPanels[i]);
NNMap.add(layerPanels[i]);
}
}
public void drawNodes()
{
int nod = 0;
for (int i = 0; i < getNodes().size(); i++)
{
nod += getNodes().get(i).length;
}
nodeButtons = new JButton[nod];
for (int i = 0; i < getLayersSize(); i++)
{
for (int j = 0; j < getNodes().get(i).length; j++)
{
//nodeButtons[j]
layerSubPanels[i].add(MyFactory.createNODEButton(getNodes().get(i)[j]));
}
}
}
}
This is a JPanel that is added to the main window in a split pane. That is all done in a different class.
Here is the Map Panel:
What would I use to create a transparent JPanel on top of the JPanel that contains the map. So I could draw connections between the nodes.
There's probably a few ways you could do this, but one way might be to create a custom JLayeredPane, which can maintain and paint the relationships between the components, for example...
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
GroupPane parent = new GroupPane("Parent", Color.RED);
GroupPane child1 = new GroupPane("Child 1", Color.BLUE);
GroupPane child2 = new GroupPane("Child 2", Color.CYAN);
parent.setBounds(10, 10, 100, 100);
child1.setBounds(10, 150, 100, 100);
child2.setBounds(150, 150, 100, 100);
ConnectionPane connectionPane = new ConnectionPane();
connectionPane.add(parent, child1);
connectionPane.add(parent, child2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(connectionPane);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class GroupPane extends JPanel {
public GroupPane(String name, Color background) {
setLayout(new GridBagLayout());
add(new JLabel(name));
setBackground(background);
}
}
public class ConnectionPane extends JLayeredPane {
private List<Component[]> connections;
public ConnectionPane() {
connections = new ArrayList<>();
MouseAdapter ma = new MouseAdapter() {
private Component dragComponent;
private Point clickPoint;
private Point offset;
#Override
public void mousePressed(MouseEvent e) {
Component component = getComponentAt(e.getPoint());
if (component != ConnectionPane.this && component != null) {
dragComponent = component;
clickPoint = e.getPoint();
int deltaX = clickPoint.x - dragComponent.getX();
int deltaY = clickPoint.y - dragComponent.getY();
offset = new Point(deltaX, deltaY);
}
}
#Override
public void mouseDragged(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
int xDelta = mouseX - offset.x;
int yDelta = mouseY - offset.y;
dragComponent.setLocation(xDelta, yDelta);
repaint();
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
public void add(Component parent, Component child) {
if (parent.getParent() != this) {
add(parent);
}
if (child.getParent() != this) {
add(child);
}
connections.add(new Component[]{parent, child});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Component[] connection : connections) {
Rectangle parent = connection[0].getBounds();
Rectangle child = connection[1].getBounds();
g2d.draw(new Line2D.Double(parent.getCenterX(), parent.getCenterY(), child.getCenterX(), child.getCenterY()));
}
g2d.dispose();
}
}
}
I am trying to make a JPanel slide in from the side using this class i made:
public class AnimationClass {
private int i;
private int y;
private JPanel panel;
private int xTo;
private Timer timer;
private int xFrom;
synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;
panel.setSize(width, height);
timer = new Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
for (int i = xFrom; i > xTo; i--) {
panel.setLocation(i, y);
panel.repaint();
i--;
timer.stop();
timer.setDelay(100);
if (i >= xTo) {
timer.stop();
}
}
timer.stop();
}
});
timer.start();
}
}
Well, i dont know what the problem is. I've tried a lot of different things, but i doesn't seem like I can get it to work.
The timer should be changing the location on each tick, until it is in place, instead, on each tick, you're running through a for-next loop, which is blocking the EDT until the loop finishes, preventing from updating the UI
Update with example
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestAnimatedPane {
public static void main(String[] args) {
new TestAnimatedPane();
}
public TestAnimatedPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel panel;
public TestPane() {
setLayout(null);
panel = new JPanel();
panel.setBackground(Color.RED);
add(panel);
Dimension size = getPreferredSize();
Rectangle from = new Rectangle(size.width, (size.height - 50) / 2, 50, 50);
Rectangle to = new Rectangle((size.width - 50) / 2, (size.height - 50) / 2, 50, 50);
Animate animate = new Animate(panel, from, to);
animate.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public static class Animate {
public static final int RUN_TIME = 2000;
private JPanel panel;
private Rectangle from;
private Rectangle to;
private long startTime;
public Animate(JPanel panel, Rectangle from, Rectangle to) {
this.panel = panel;
this.from = from;
this.to = to;
}
public void start() {
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long duration = System.currentTimeMillis() - startTime;
double progress = (double)duration / (double)RUN_TIME;
if (progress > 1f) {
progress = 1f;
((Timer)e.getSource()).stop();
}
Rectangle target = calculateProgress(from, to, progress);
panel.setBounds(target);
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(0);
startTime = System.currentTimeMillis();
timer.start();
}
}
public static Rectangle calculateProgress(Rectangle startBounds, Rectangle targetBounds, double progress) {
Rectangle bounds = new Rectangle();
if (startBounds != null && targetBounds != null) {
bounds.setLocation(calculateProgress(startBounds.getLocation(), targetBounds.getLocation(), progress));
bounds.setSize(calculateProgress(startBounds.getSize(), targetBounds.getSize(), progress));
}
return bounds;
}
public static Point calculateProgress(Point startPoint, Point targetPoint, double progress) {
Point point = new Point();
if (startPoint != null && targetPoint != null) {
point.x = calculateProgress(startPoint.x, targetPoint.x, progress);
point.y = calculateProgress(startPoint.y, targetPoint.y, progress);
}
return point;
}
public static int calculateProgress(int startValue, int endValue, double fraction) {
int value = 0;
int distance = endValue - startValue;
value = (int)Math.round((double)distance * fraction);
value += startValue;
return value;
}
public static Dimension calculateProgress(Dimension startSize, Dimension targetSize, double progress) {
Dimension size = new Dimension();
if (startSize != null && targetSize != null) {
size.width = calculateProgress(startSize.width, targetSize.width, progress);
size.height = calculateProgress(startSize.height, targetSize.height, progress);
}
return size;
}
}
Update
I should have added this in last night (1 year who didn't want to go to bed, 2 parents that did, say no more...)
Animation is complex topic, especially when you start looking at variable speed (the example is static).
Instead of reinventing the wheel, you should seriously consider taking a look at...
Timing Framework - This is base animation framework, that makes no assumptions about how you might like to use it.
Trident - Similar to the Timing Framework, but also has support for Swing based components (via reflection) build in
Universal Tween Engine
This well-factored example easily admits the variation below. It leverages the enclosed panel's preferred size in a JLayeredPane.
/**
* #see https://stackoverflow.com/a/16322007/230513
* #see https://stackoverflow.com/a/16316345/230513
*/
public class TestPane extends JLayeredPane {
private static final int WIDE = 200;
private static final int HIGH = 5 * WIDE / 8; // ~1/phi
private JPanel panel;
public TestPane() {
panel = new JPanel();
panel.setBackground(Color.RED);
panel.add(new JButton("Test"));
add(panel);
Dimension size = panel.getPreferredSize();
int half = HIGH / 2 - size.height / 2;
Rectangle from = new Rectangle(size);
from.translate(WIDE, half);
Rectangle to = new Rectangle(size);
to.translate(0, half);
panel.setBounds(from);
Animate animate = new Animate(panel, from, to);
animate.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(WIDE, HIGH);
}
}
There are a number of problems in the OP's code. As MadProrammer points, should only be moving one step per timer tick. Here is a simple,tested correction to the OPs code which moves the JPanel one pixel at a time, 25 times a second. Note the comments:
synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;
panel.setSize(width, height);
// timer runs 25 times per second
timer = new Timer(40, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Must 'remember' where we have slid panel to by using instance variable rather than automatic variable
// Only move one step at a time.
// No need to restart timer, it continues to run until stopped
if (xFrom > xTo){
xFrom = xFrom - 1;
panel.setLocation(xFrom, y);
panel.repaint();
} else {
timer.stop();
}
panel.setLocation(xFrom, y);
panel.repaint();
}
});
timer.start();
}
example to slid Anything
package TestingPackage;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ToggleBtn extends JPanel {
JFrame frame;
JPanel panelOut;
JLabel labelOn;
JLabel labelOff;
JButton btn;
int count = 1;
public ToggleBtn() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(500, 300, 300, 300);
frame.setLayout(null);
panelOut = new JPanel(null);
panelOut.setBounds(50, 100, 120, 30);
panelOut.setBackground(Color.gray);
frame.add(panelOut);
btn = new JButton("::");
btn.setBounds(0, 0, 60, 30);
panelOut.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
startThread();
}
});
labelOn = new JLabel("ON");
labelOn.setBounds(0, 0, 60, 30);
panelOut.add(labelOn);
labelOff = new JLabel("OFF");
labelOff.setBounds(60, 0, 60, 30);
panelOut.add(labelOff);
frame.setVisible(true);
}
public void startThread() {
count++;
new Move().start();
}
public static void main(String[] args) {
new ToggleBtn();
}
class Move extends Thread {
#Override
public void run() {
if (count % 2 == 0) {
System.out.println("if");
for (int i = 0; i <= 60; i++) {
try {
Thread.sleep(3);
} catch (InterruptedException ex) {
Logger.getLogger(ToggleBtn.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setBounds(i, 0, 60, 30);
}
} else {
System.out.println("else");
for (int i = 60; i >= 0; i--) {
try {
Thread.sleep(3);
} catch (InterruptedException ex) {
Logger.getLogger(ToggleBtn.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setBounds(i, 0, 60, 30);
}
}
}
}
}
Single keys (in code KeyboardButtons) extends JComponent. When i'm trying to add the to main JFrame, i can do that for single key, when trying to add another one, the first one is not showing.
Can you please look at the code a tell me where the problem is?
MainFrame.java:
package keyboard;
import java.awt.*;
import javax.swing.JFrame;
public class MainFrame extends JFrame {
public MainFrame() throws HeadlessException {
setTitle("Keyboard");
setSize(1024, 768);
}
public static void main(String[] args) throws InterruptedException {
JFrame mainWindow = new MainFrame();
mainWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
Point left5 = new Point(210, 210);
Point left4 = new Point(410, 110);
Point left3 = new Point(580, 120);
Point left2 = new Point(680, 200);
Point left1 = new Point(800, 500);
Keyboard kb = new Keyboard(left1, left2, left3, left4, left5);
KeyboardButton[] buttons = kb.registerKeys();
Container c = mainWindow.getContentPane();
c.add(buttons[0]);
c.add(buttons[1]);
mainWindow.setVisible(true);
}
}
KeyboardButton.java:
package keyboard;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.*;
import javax.swing.JComponent;
public class KeyboardButton extends JComponent implements MouseListener {
Polygon polygon;
boolean isActive;
final Color ACTIVE_COLOR = Color.red;
final Color INACTIVE_COLOR = Color.blue;
public KeyboardButton(Polygon p) {
polygon = p;
addMouseListener(this);
}
private void checkMousePosition(MouseEvent e) {
if (polygon.contains(e.getX(), e.getY())) {
setState(true);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
checkMousePosition(e);
System.out.println(this + " pressed");
}
public void mouseReleased(MouseEvent e) {
setState(false);
System.out.println(this + " released");
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(isActive ? ACTIVE_COLOR : INACTIVE_COLOR);
g.drawPolygon(polygon);
}
void setState(boolean state) {
isActive = state;
repaint();
}
}
Keyboard.java:
package keyboard;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import javax.swing.JComponent;
public class Keyboard extends JComponent {
Point[] leftFingers;
Point leftCenter = new Point(300, 600);
public Keyboard(Point left1, Point left2, Point left3, Point left4, Point left5) {
leftFingers = new Point[5];
leftFingers[0] = left1;
leftFingers[1] = left2;
leftFingers[2] = left3;
leftFingers[3] = left4;
leftFingers[4] = left5;
}
public KeyboardButton[] registerKeys() {
Polygon[] polygons = generateKeyPolygons(calculateBordersOfKeys(calculateCentersBetweenEachTwoFingers(leftFingers)));
KeyboardButton[] buttons = new KeyboardButton[5];
for (int i = 0; i < polygons.length; i++) {
buttons[i] = new KeyboardButton(polygons[i]);
}
return buttons;
}
private Point[] calculateBordersOfKeys(Point[] fingers) {
Point[] centers = calculateCentersBetweenEachTwoFingers(fingers);
Point[] result = new Point[6];
result[0] = calculateCentralSymmetry(centers[0], fingers[0]);
System.arraycopy(centers, 0, result, 1, centers.length);
result[5] = calculateCentralSymmetry(centers[3], fingers[4]);
return result;
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.drawOval(leftCenter.x - 25, leftCenter.y - 25, 50, 50);
for (int i = 0; i < leftFingers.length; i++) {
g.drawOval(leftFingers[i].x, leftFingers[i].y, 10, 10);
}
}
private Polygon[] generateKeyPolygons(Point[] borders) {
Polygon[] polygons = new Polygon[5];
for (int i = 0; i < borders.length - 1; i++) {
Polygon p = new Polygon();
p.addPoint(leftCenter.x, leftCenter.y);
p.addPoint(borders[i].x, borders[i].y);
p.addPoint(borders[i + 1].x, borders[i + 1].y);
polygons[i] = p;
}
return polygons;
}
private Point[] calculateCentersBetweenEachTwoFingers(Point[] fingers) {
Point[] centers = new Point[4];
for (int i = 0; i < fingers.length - 1; i++) {
centers[i] = new Point(((fingers[i].x + fingers[i + 1].x) / 2), ((fingers[i].y + fingers[i + 1].y) / 2));
}
return centers;
}
private Point calculateCentralSymmetry(Point toReflected, Point center) {
Point reflection = new Point();
if (toReflected.x > center.x) {
reflection.x = center.x - Math.abs(center.x - toReflected.x);
} else {
reflection.x = center.x + Math.abs(center.x - toReflected.x);
}
if (toReflected.y > center.y) {
reflection.y = center.y - Math.abs(center.y - toReflected.y);
} else {
reflection.y = center.y + Math.abs(center.y - toReflected.y);
}
return reflection;
}
}
Try to use another LayoutManager, or for what it seems to me it looks like you are trying to manualy paint shapes on the screen, i'd suggest painting them all on one layer. (have one JComponent's paintComponent() method which calls to KeyboardButton.paint() and other painting methods, then you can just add that one JComponent)