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)
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'm trying to do this code to output the same result as the picture
it should start with one black circle then when I click the button, a white circle appear with shift the right and get bigger by 20 pixels and so on
after the 4th circle it should clear the window and start from the beginning and I keep getting only one circle color or two circles together
here's the code
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.WindowConstants;
public class CircleList extends JFrame implements ActionListener {
JButton addCircle;
int nCircle = 1;
int step = 0;
int shift = 0;
int d = 0;
public static void main (String [] args){
new CircleList();
}
private class Circle {
public int x1;
public int y1;
public int w;
public int h;
public Color color;
}
private List<Circle> whiteList = new ArrayList<>();
private List<Circle> blackList = new ArrayList<>();
public CircleList() {
super("CircleList");
setSize(500,500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.gray);
addCircle = new JButton("Add Circle");
add(addCircle,BorderLayout.SOUTH);
addCircle.addActionListener(this);
repaint();
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
g.fillOval(35, 35, 35, 35);
if (d==1) {
for (Circle s: whiteList ) {
paintWhiteCircle(g, s);
}
addWhiteCircle();
}
else if (d==2) {
for (Circle s: blackList ) {
paintBlackCircle(g, s);
}
addBlackCircle();
}
}
public void paintWhiteCircle(Graphics g, Circle circle) {
g.setColor(circle.color);
g.fillOval(circle.x1, circle.y1, circle.w, circle.h);
}
public void paintBlackCircle(Graphics g, Circle circle) {
g.setColor(circle.color);
g.fillOval(circle.x1, circle.y1, circle.w, circle.h);
}
public void addBlackCircle(){
Circle circle = new Circle();
circle.x1 = 40 + shift;
circle.y1 = 30 ;
circle.w = 30 + step;
circle.h = 30 + step;
circle.color = new Color(0,0,0);
this.blackList.add(circle);
}
public void addWhiteCircle() {
Circle circle = new Circle();
circle.x1 = 100 + shift;
circle.y1 = 30 ;
circle.w = 50 + step;
circle.h = 50 + step;
circle.color = new Color(255*65536+255*256+255);
this.whiteList.add(circle);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
d = 0;
if (source == addCircle) {
for (nCircle = 2; nCircle <= 5; nCircle++) {
if (nCircle == 2) {
d = 1;
step+=20;
shift += 20;
nCircle++;
}
else if (nCircle == 3) {
d = 2;
step+=20;
shift += 20;
}
else if (nCircle == 4) {
d=1;
step+=20;
shift += 20;
}
else if (nCircle == 5)
repaint(); // it should clear the window and start with one circle like the beginning
}
repaint();
}
}
}
the output should be like this
I've corrected your example. It works now.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class CircleList extends JPanel implements ActionListener, Runnable {
private static final int INTERVAL = 20;
private static final int INITIAL_DIAMETR = 20;
private int actualXPos;
private final List<Circle> circleList = new ArrayList<>();
public static void main(String[] args) {
SwingUtilities.invokeLater(new CircleList());
}
#Override
public void run() {
JFrame frm = new JFrame(getClass().getSimpleName());
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.getContentPane().add(this);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
public CircleList() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(500, 500));
setBackground(Color.gray);
JButton addCircle = new JButton("Add Circle");
add(addCircle, BorderLayout.SOUTH);
addCircle.addActionListener(this);
addCircle();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Circle c : circleList) {
c.paint(g);
}
}
private void addCircle() {
Circle circle = new Circle();
int num = circleList.size();
circle.x1 = 40 + actualXPos;
circle.y1 = 30;
circle.w = 30 + INITIAL_DIAMETR * (num + 1);
circle.h = 30 + INITIAL_DIAMETR * (num + 1);
circle.color = num % 2 == 0 ? Color.BLACK : Color.WHITE;
circleList.add(circle);
actualXPos += circle.w + INTERVAL;
}
#Override
public void actionPerformed(ActionEvent e) {
if (circleList.size() == 4) {
circleList.clear();
actualXPos = 0;
}
addCircle();
repaint();
}
private static class Circle {
private int x1;
private int y1;
private int w;
private int h;
private Color color;
public void paint(Graphics g) {
g.setColor(color);
g.fillOval(x1, y1, w, h);
}
}
}
I'm having trouble with some custom Component I'm using in my project. It's drawing fine, but now I want to find coordinates of first pixel in certain color and have some troubles with it.
Here is my component code:
class DrawPad extends JComponent {
private LinkedList<Line> lines = new LinkedList<>();
DrawPad() {
setDoubleBuffered(true);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
lines.add(new Line());
lines.getLast().add(e.getPoint());
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
lines.getLast().add(e.getPoint());
repaint();
}
});
}
void clear() {
lines.clear();
repaint();
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
if (!lines.isEmpty()) {
for (Line line : lines) {
// TODO
LinkedList<Point> points = line.getPoints();
Point previous = points.getFirst(), current = previous;
for (int i = 1; i < points.size(); i++) {
current = points.get(i);
g.drawLine(previous.x, previous.y, current.x, current.y);
previous = current;
}
}
}
}
}
I know it probably can be optimized, but it's not so important right now.
Can anyone help me to write a method that's searching for first pixel in certain color?
I recently find out that it has to do something with BufferedImage, but don't know how to implement it. Any help would be appreciated.
The example below paints an Icon into a BufferedImage and sets a RED pixel for find() to discover. Hover the mouse over other pixels to see the underlying color.
System.out.println(find(Color.RED));
…
private Point find(Color color) {
for (int r = 0; r < imgH; r++) {
for (int c = 0; c < imgW; c++) {
if (img.getRGB(c, r) == color.getRGB()) {
System.out.println(c + "," + r + ": "
+ String.format("%08X", img.getRGB(c, r)));
return new Point(c, r);
}
}
}
return new Point(-1 , -1);
}
Console:
32,32: FFFF0000
java.awt.Point[x=32,y=32]
Code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
/**
* #see http://stackoverflow.com/a/37574791/230513
* #see http://stackoverflow.com/questions/2900801
*/
public class Grid extends JPanel {
private static final int SCALE = 8;
private final BufferedImage img;
private int imgW, imgH, paneW, paneH;
public Grid(String name) {
Icon icon = UIManager.getIcon(name);
imgW = icon.getIconWidth();
imgH = icon.getIconHeight();
img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
img.setRGB(imgW / 2, imgH / 2, Color.RED.getRGB());
this.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
int x = p.x * imgW / paneW;
int y = p.y * imgH / paneH;
int c = img.getRGB(x, y);
setToolTipText(x + "," + y + ": "
+ String.format("%08X", c));
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(imgW * SCALE, imgH * SCALE);
}
#Override
protected void paintComponent(Graphics g) {
paneW = this.getWidth();
paneH = this.getHeight();
g.drawImage(img, 0, 0, paneW, paneH, null);
System.out.println(find(Color.RED));
}
private Point find(Color color) {
for (int r = 0; r < imgH; r++) {
for (int c = 0; c < imgW; c++) {
if (img.getRGB(c, r) == color.getRGB()) {
System.out.println(r + "," + c + ": "
+ String.format("%08X", img.getRGB(c, r)));
return new Point(c, r);
}
}
}
return new Point(-1 , -1);
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Grid("OptionPane.informationIcon"));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
}
I'm looking for some help regarding a Java program I'm writing. I need to display a simple bar graph consisting of rectangles based off of data saved in an array that has been generated by a JList selection event. However, nothing is drawn in the JPanel and I cannot figure out how to fix it.
List Selection Event (For reference)
try
{
BufferedReader in = new BufferedReader((new FileReader("scores.txt")));
String sLine;
while ((sLine = in.readLine()) != null)
{
vecAthlete.addElement(new Stage3_DataFile(sLine));
}
String[] saAthlete = new String[vecAthlete.size()];
for (int iI = 0; iI < vecAthlete.size(); iI++)
saAthlete[iI] = vecAthlete.get(iI).sName;
jList_Athlete.setListData(saAthlete);
jList_Athlete.setSelectedIndex(0);
// Reading input line by line
// Close file
in.close();
}
catch (IOException e)
{
System.out.println("ERROR: Could not read text file!");
}
jList_Athlete.addListSelectionListener(new javax.swing.event.ListSelectionListener()
{
public void valueChanged(javax.swing.event.ListSelectionEvent e)
{
double[][] daRun = new double[2][7];
final double dScoreUsed = 5;
double dMinScoreRun1 = 10, dMaxScoreRun1 = 0;
double dMinScoreRun2 = 10, dMaxScoreRun2 = 0;
double dTotalRun1 = 0, dTotalRun2 = 0;
jLabel_Athlete.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sName);
jLabel_Country.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).sCountry);
jLabel_Run1_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[0]);
jLabel_Run1_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[1]);
jLabel_Run1_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[2]);
jLabel_Run1_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[3]);
jLabel_Run1_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[4]);
jLabel_Run1_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[5]);
jLabel_Run1_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun1[6]);
jLabel_Run2_Score_1.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[0]);
jLabel_Run2_Score_2.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[1]);
jLabel_Run2_Score_3.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[2]);
jLabel_Run2_Score_4.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[3]);
jLabel_Run2_Score_5.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[4]);
jLabel_Run2_Score_6.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[5]);
jLabel_Run2_Score_7.setText(vecAthlete.get(jList_Athlete.getSelectedIndex()).saTempRun2[6]);
daRun[0][0] = Double.parseDouble(jLabel_Run1_Score_1.getText());
daRun[0][1] = Double.parseDouble(jLabel_Run1_Score_2.getText());
daRun[0][2] = Double.parseDouble(jLabel_Run1_Score_3.getText());
daRun[0][3] = Double.parseDouble(jLabel_Run1_Score_4.getText());
daRun[0][4] = Double.parseDouble(jLabel_Run1_Score_5.getText());
daRun[0][5] = Double.parseDouble(jLabel_Run1_Score_6.getText());
daRun[0][6] = Double.parseDouble(jLabel_Run1_Score_7.getText());
daRun[1][0] = Double.parseDouble(jLabel_Run2_Score_1.getText());
daRun[1][1] = Double.parseDouble(jLabel_Run2_Score_2.getText());
daRun[1][2] = Double.parseDouble(jLabel_Run2_Score_3.getText());
daRun[1][3] = Double.parseDouble(jLabel_Run2_Score_4.getText());
daRun[1][4] = Double.parseDouble(jLabel_Run2_Score_5.getText());
daRun[1][5] = Double.parseDouble(jLabel_Run2_Score_6.getText());
daRun[1][6] = Double.parseDouble(jLabel_Run2_Score_7.getText());
for(int i = 0; i < 7; i++)
{
if(daRun[0][i] <= dMinScoreRun1)
{
dMinScoreRun1 = daRun[0][i];
}
if(daRun[0][i] >= dMaxScoreRun1)
{
dMaxScoreRun1 = daRun[0][i];
}
dTotalRun1 += daRun[0][i];
}
dTotalRun1 = (dTotalRun1 - dMinScoreRun1 - dMaxScoreRun1) / dScoreUsed;
jLabel_TotalRun1.setText(String.valueOf(dTotalRun1));
jLabel_Run1AddInfo.setText("Min Score: " + (dMinScoreRun1) + ", Max Score: " + (dMaxScoreRun1));
for(int i = 0; i < 7; i++)
{
if(daRun[1][i] <= dMinScoreRun2)
{
dMinScoreRun2 = daRun[1][i];
}
if(daRun[1][i] >= dMaxScoreRun2)
{
dMaxScoreRun2 = daRun[1][i];
}
dTotalRun2 += daRun[1][i];
}
dTotalRun2 = (dTotalRun2 - dMinScoreRun2 - dMaxScoreRun2) / dScoreUsed;
jLabel_TotalRun2.setText(String.valueOf(dTotalRun2));
jLabel_Run2AddInfo.setText("Min Score: " + (dMinScoreRun2) + ", Max Score: " + (dMaxScoreRun2));
if(dTotalRun1 >= dTotalRun2)
jLabel_FinalScore.setText(String.valueOf(dTotalRun1));
else
jLabel_FinalScore.setText(String.valueOf(dTotalRun2));
jPanel_Graph.repaint();
}
});
JPanel Definitions
JPanel jPanel_Graph = new JPanel();
jPanel_Graph.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
jPanel_Graph.setBounds(729, 159, 700, 200);
frame.getContentPane().add(jPanel_Graph);
img = new BufferedImage(jPanel_Graph.getWidth(),
jPanel_Graph.getHeight(),
BufferedImage.TYPE_INT_RGB);
g2dimg = (Graphics2D)img.getGraphics();
// Draw a filled white coloured rectangle on the entire area to clear it.
g2dimg.setPaint(Color.WHITE);
g2dimg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
JPanel Drawing Event
class myJPanel extends JPanel
{
private Rectangle2D.Double rectangle;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < 7; i++)
{
dHeight = daRun[0][i];
rectangle = new Rectangle2D.Double(dX, dY, dWidth, dHeight);
g2dimg.setPaint(Color.red);
g2dimg.draw(rectangle);
g2dimg.fill(rectangle);
dX += dXIncrement;
g2dimg.drawImage(img, 0, 0, null);
}
}
}
Thanks in advance!
So, from what I can tell, there is no way for your "graph" to know what it should paint. The basic idea is, your "graph" should be focused on painting the data/model, so you need some way to tell it when the data changes.
There are lots of ways you might do this, for example, you could devise a model, which you add/remove data to, which could trigger updates that the graph pane listeners for and then updates itself with the new data.
Or you just pass the data you want updated directly to the graph pane, which in this case, might the simplest solution available to you
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private GraphPane graphPane;
public TestPane() {
setLayout(new BorderLayout());
DefaultListModel<Double> listmodel = new DefaultListModel<>();
for (int index = 0; index < 100; index++) {
listmodel.addElement(Math.random());
}
graphPane = new GraphPane();
add(graphPane);
JList<Double> listData = new JList<>(listmodel);
add(new JScrollPane(listData), BorderLayout.WEST);
listData.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
graphPane.setData(listData.getSelectedValuesList().toArray(new Double[0]));
}
});
}
}
public class GraphPane extends JPanel {
private Double[] data;
public void setData(Double[] data) {
this.data = data;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (data != null && data.length > 0) {
Graphics2D g2d = (Graphics2D) g.create();
double barWidth = getWidth() / (double)data.length;
int xPos = 0;
for (Double value : data) {
double height = (getHeight() - 1) * value;
Rectangle2D bar = new Rectangle2D.Double(xPos, getHeight() - height, barWidth, height);
g2d.setColor(Color.GREEN);
g2d.fill(bar);
g2d.setColor(Color.BLACK);
g2d.draw(bar);
xPos += barWidth;
}
g2d.dispose();
}
}
}
}
I'm trying to get the mouse position and light up a button when the curser is over it. However the mouse position isn't updating right. I think the y position is messed up because currently if i am far above the button it lights up.
Heres my code that is incorrect:
public void mouseMoved(MouseEvent e) {
Window.mse = new Point((e.getX()) + ((Frame.size.width - Window.myWidth)/2), (e.getY()) + (Frame.size.height - (Window.myHeight)/2));
}
This is the Window file:
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class Window extends JPanel implements Runnable {
public Thread thread = new Thread(this);
public static Image[] tileset_ground = new Image[100];
public static Image[] tileset_air = new Image[100];
public static Image[] tileset_resources = new Image[100];
public static int myWidth, myHeight;
public static boolean isFirst = true;
public static Point mse = new Point(0, 0);
public static Room room;
public static Levels levels;
public static Shop shop;
public Window(Frame frame) {
frame.addMouseListener(new KeyHandler());
frame.addMouseMotionListener(new KeyHandler());
thread.start();
}
public void define() {
room = new Room();
levels = new Levels();
shop = new Shop();
tileset_resources[0] = new ImageIcon("resources/cell.png").getImage();
levels.loadLevels(new File("levels/level1.level"));
for(int i=0;i<tileset_ground.length; i++) {
tileset_ground[i] = new ImageIcon("resources/tileset_ground.png").getImage();
tileset_ground[i] = createImage(new FilteredImageSource(tileset_ground[i].getSource(), new CropImageFilter(0, 32 * i, 32, 32)));
}
for(int i=0;i<tileset_air.length; i++) {
tileset_air[i] = new ImageIcon("resources/tileset_air.png").getImage();
tileset_air[i] = createImage(new FilteredImageSource(tileset_air[i].getSource(), new CropImageFilter(0, 32 * i, 32, 32)));
}
}
public void paintComponent(Graphics g) {
if(isFirst) {
myWidth = getWidth();
myHeight = getHeight();
define();
isFirst = false;
}
g.setColor(new Color(70, 70, 70));
g.fillRect(0, 0, myWidth, myHeight);
g.setColor(new Color(0, 0, 0));
g.drawLine(room.block[0][0].x, room.block[room.worldHeight - 1][0].y + room.blockSize, room.block[0][room.worldWidth - 1].x + room.blockSize, room.block[room.worldHeight - 1][0].y + room.blockSize);
g.drawLine(room.block[0][0].x, room.block[room.worldHeight - 1][0].y + 1 + room.blockSize, room.block[0][room.worldWidth - 1].x + room.blockSize, room.block[room.worldHeight - 1][0].y + 1 + room.blockSize);
room.draw(g); //Draws room
shop.draw(g); //Draws shop
}
public void run() {
while(true) {
if(!isFirst) {
room.physic();
}
repaint();
try {
Thread.sleep(1);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Simply add a MouseListener to the JButton. Or better still add a ChangeListener to the button's model, and in it, call isRollover() on the model.