plotting a graph [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi there I am quite new to java, however I need to plot a graph in JApplet. I have managed to declare all variables and classes, the equation is working (when compiled on it's own). but all I get is a strait line! can anyone tell me what am I doing wrong please?!
in this applet the user will be asked to insert the values for abcd and the min and max values for the x axes
here is my code.......any help will be gratefully appreciated :)
package CubicEquationSolver;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
public class graphApplet extends JApplet implements ActionListener {
private static class g {
public g() {
}
}
int a;
int b;
int c;
int d;
int minimumX;
int maximumX;
int minimumY;
int maximumY;
int xCoOrdinates[];
int yCoOrdinates[];
int y;
// Setting labels
JLabel labelA = new JLabel("Enter value of A");
JLabel labelB = new JLabel("Enter value of B");
JLabel labelC = new JLabel("Enter value of C");
JLabel labelD = new JLabel("Enter value of D");
JLabel labelMinX = new JLabel("Minimum X value");
JLabel labelMaxX = new JLabel("Maximum X value");
JLabel message = new JLabel("Please insert your values");
// Values will be entered here using JTextField
JTextField textA = new JTextField();
JTextField textB = new JTextField();
JTextField textC = new JTextField();
JTextField textD = new JTextField();
JTextField minX = new JTextField();
JTextField maxX = new JTextField();
JTextField ref = new JTextField("Enter value 0-1");
// declaring the layout for layout manager
JPanel north = new JPanel();
JPanel south = new JPanel();
JPanel west = new JPanel();
JPanel east = new JPanel();
JPanel center = new JPanel();
// declaring buttons using JButtons
JButton calculate = new JButton("Calculate");
JButton delete = new JButton("Delete");
JButton refine = new JButton("Refine");
// Calling from equation class
// equation eq = new equation();
private JPanel panel;
private int width = center.getWidth();
private int height = center.getHeight();
#Override
public void init() {
// setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = this.getContentPane();
this.setSize(900, 480);
this.setVisible(true);
// listener to buttons
calculate.addActionListener(this);
delete.addActionListener(this);
refine.addActionListener(this);
// listeer to user's input
textA.addActionListener(this);
textB.addActionListener(this);
textC.addActionListener(this);
textD.addActionListener(this);
minX.addActionListener(this);
maxX.addActionListener(this);
ref.addActionListener(this);
// assigning colours to panels to be distinguished
north.setBackground(Color.LIGHT_GRAY);
south.setBackground(Color.LIGHT_GRAY);
west.setBackground(Color.YELLOW);
east.setBackground(Color.GREEN);
center.setBackground(Color.GRAY);
// Declaring border
BorderLayout layoutBorder = new BorderLayout();
// setting up the grid (x rows, y clumns, space, space)
GridLayout layoutGrid = new GridLayout(2, 8, 4, 4);
// layout grid
north.setLayout(layoutGrid);
// set labels
north.add(labelA);
north.add(labelB);
north.add(labelC);
north.add(labelD);
north.add(labelMinX);
north.add(labelMaxX);
north.add(ref);
// calculate button
north.add(calculate);
// text boxes
north.add(textA);
north.add(textB);
north.add(textC);
north.add(textD);
north.add(minX);
north.add(maxX);
north.add(refine);
// delete button
north.add(delete);
south.add(message);
// border layout
c.add(north, BorderLayout.NORTH);
c.add(south, BorderLayout.SOUTH);
c.add(center, BorderLayout.CENTER);
// c .add(west, BorderLayout.WEST);
// c .add(east, BorderLayout.EAST);
// panel = new JPanel();
// panel.setPreferredSize(new Dimension(width, height));
// panel.setBackground(Color.GRAY);
// center.add(panel);
}
#Override
public void actionPerformed(ActionEvent e) // throws NumberFormatException
{
// dafault message will be <message> -- "Please insert values"
message.setText(e.getActionCommand());
// when button "Delete" is pressed all values in text firlds will turn
// null
if (e.getActionCommand().equals("Delete")) {
message.setForeground(Color.DARK_GRAY);
textA.setText(null);
textB.setText(null);
textC.setText(null);
textD.setText(null);
minX.setText(null);
maxX.setText(null);
repaint();
} else if (e.getActionCommand().equals("Calculate"))
// when "Calculate" button is pressed, values will be attached to
// equation
try {
message.setForeground(Color.DARK_GRAY);
// -------------------------------------------------
a = Integer.parseInt(textA.getText());
b = Integer.parseInt(textB.getText());
c = Integer.parseInt(textC.getText());
d = Integer.parseInt(textD.getText());
minimumX = Integer.parseInt(minX.getText());
maximumX = Integer.parseInt(maxX.getText());
System.out.println("center.getWidth() " + center.getWidth());
System.out.println("center.getHeight() " + center.getHeight());
System.out.println("minimum " + minX.getText());
System.out.println("maximum " + maxX.getText());
System.out.println("a " + textA.getText());
System.out.println("b " + textB.getText());
System.out.println("c " + textC.getText());
System.out.println("d " + textD.getText());
// ------------------------------------------------------
message.setText("This is the result for " + "A "
+ textA.getText() + ", B " + textB.getText() + ", C "
+ textC.getText() + ", D " + textD.getText());
draw();
}
catch (NumberFormatException ex)
// if user inputs other than numbers, a warning message in the south
// panel will show
{
message.setText("Please insert numerical value in "
+ ex.getMessage());
message.setForeground(Color.red);
message.setFont(new Font("Tahoma", Font.BOLD, 12));
}
else if (e.getActionCommand().equals("Refine")) {
// for refine
}
}
// ===================================================================================
private void calculation() {
xCoOrdinates = new int[(maximumX - minimumX) + 1];
yCoOrdinates = new int[(maximumX - minimumX) + 1];
for (int i = 0; i < xCoOrdinates.length; i++)
// for(int j = 0; j < yCoOrdinates.length; j++)
{
// generating the x co-ordinates and storing them in arrays
xCoOrdinates[i] = minimumX + i;
// generating the y co-ordinates using the formula given
y = ((a * (int) Math.pow(i, 3)) + (b * (int) Math.pow(i, 2))
+ (c * i) + (d));
// storing y co-ordinates
yCoOrdinates[i] = y;
// displaying results
// System.out.println("X = " + i + " Y = " + getY());
System.out.println("These are the values of X = " + i);
}
// printing the y axes values
for (int i = 0; i < yCoOrdinates.length; i++) {
System.out.println("this is the extracted Y " + yCoOrdinates[i]);
}
maximumX = xCoOrdinates[0];
maximumX = xCoOrdinates[0];
for (int i = 1; i < yCoOrdinates.length; i++) {
if (yCoOrdinates[i] > maximumX)
maximumX = xCoOrdinates[i];
else if (yCoOrdinates[i] < minimumX)
minimumX = xCoOrdinates[i];
}
System.out.println("MAXX is " + maximumX);
System.out.println("MINX is " + minimumX);
maximumY = yCoOrdinates[0];
minimumY = yCoOrdinates[0];
for (int i = 1; i < yCoOrdinates.length; i++) {
if (yCoOrdinates[i] > maximumY)
maximumY = yCoOrdinates[i];
else if (yCoOrdinates[i] < minimumY)
minimumY = yCoOrdinates[i];
}
System.out.println("MAXY is " + maximumY);
System.out.println("MINY is " + minimumY);
}
// =================================================================================================
public void draw() {
Graphics g = center.getGraphics();
g.setColor(Color.GRAY);
g.fillRect(0, 0, center.getWidth(), center.getHeight());
// g.fillRect(25,25, center.getWidth()-50, center.getHeight()-50);
double x, y, nextX, nextY;
int xPoint; // = 0;
int yPoint; // = 0;
int nextXpoint; // = 0;
int nextYpoint; // = 0;
g.setColor(Color.BLUE);
for (xPoint = 0; xPoint <= (double) center.getWidth(); xPoint++) {
x = scaleX(xPoint);
y = equation(x);
yPoint = scaleY(y);
nextXpoint = xPoint + 1;
nextX = scaleX(nextXpoint);
nextY = equation(nextX);
nextYpoint = scaleY(nextY);
g.drawLine(xPoint, yPoint, nextXpoint, nextYpoint);
// System.out.println("equation --->" + eq.getY());
}
}
private double equation(double x) {
return y;
// return a*x*x*x + b*x*x + c*x + d;
}
private double scaleX(int xPoint) {
int minXstart = minimumX;
int maxXend = maximumX;
double xScale = (double) center.getWidth() / (maxXend - minXstart);
return (xPoint - (center.getWidth() / 2)) / xScale;
}
private int scaleY(double y) {
int minYstart = minimumY;
int maxYend = maximumY;
int yCoord;
double yScale = (double) center.getHeight() / (maxYend - minYstart);
yCoord = (int) (-y * yScale) + (int) (center.getHeight() / 2);
return yCoord;
}
}

There are 3rd party libraries out there to do this type of work for you. Check out:
JFreeChart
Charts4J

Short term help: Check your output, do the values of x and y vary as expected? are they actually used during plotting? Use a debugger to step through your code. Then come back with a more focused questions.
Mid term (within the next two days): Please buy and read the following two books:
http://www.amazon.com/Pragmatic-Programmer-Andrew-Hunt/dp/020161622X
http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&ie=UTF8&qid=1342369060&sr=1-1&keywords=clean+code
Classes as long as the one you posted are not acceptable, and make it next to impossible to understand the revlevant part. This is the reason why you received the down votes I'd guess.

I'm a JFreeChart fan, but you can also plot graphs using Cartesian coordinates in Java 2D, as suggested here.

Related

Sudoku: Selection image does not appear

I am building a Sudoku game. I have drawn a grid so far and programmed the selection of a field, but my chosen picture for selection does not appear. My Class for the selector is:
package com.brendenbunker;
import javax.swing.*;
public class Selection {
public JLabel boxSelected;
public ImageIcon selected;
int x, y;
public Selection(){
x = 0;
y = 0;
selected = new ImageIcon(getClass().getResource("/Selected.png"));
boxSelected = new JLabel("");
boxSelected.setIcon(selected);
boxSelected.setBounds((x * (selected.getIconWidth() + 4) + (x / 3) * 4) + 4, (y * (selected.getIconWidth() + 4) + (y / 3) * 4) + 4, selected.getIconWidth(), selected.getIconHeight());
}
public Selection(int x, int y){
this.x = x;
this.y = y;
selected = new ImageIcon(getClass().getResource("/Selected.png"));
boxSelected = new JLabel("");
boxSelected.setIcon(selected);
boxSelected.setBounds((x * (selected.getIconWidth() + 4) + (x / 3) * 4) + 4, (y * (selected.getIconWidth() + 4) + (y / 3) * 4) + 4, selected.getIconWidth(), selected.getIconHeight());
}
public void setNewSelection(int x, int y) {
this.x = x;
this.y = y;
boxSelected.setBounds((x * (selected.getIconWidth() + 4) + (x / 3) * 4) + 4, (y * (selected.getIconWidth() + 4) + (y / 3) * 4) + 4, selected.getIconWidth(), selected.getIconHeight());
}
}
The code which displays everything is:
package com.brendenbunker;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class ScreenGenerator extends JFrame{
//Intro Components
//JLabel temp;
JLabel[] gridLabel, numbLabel, numbBackLabel;
JLabel[][] numbDisp;
ImageIcon gridPic, numbPic, numbBackPic;
Rectangle[][] boxArea;
Selection selection;
Random random;
//intro Vars
public ScreenGenerator() {
setLayout(null);
random = new Random();
selection = new Selection();
gridPic = new ImageIcon(getClass().getResource("/Grid_Unified.png"));
numbBackPic = new ImageIcon(getClass().getResource("/Square.png"));
gridLabel = new JLabel[9];
numbLabel = new JLabel[9];
numbBackLabel = new JLabel[9];
boxArea = new Rectangle[9][9];
numbDisp = new JLabel[9][9];
for (int i=0; i<9; i++) {
gridLabel[i] = new JLabel("");
gridLabel[i].setBounds(((i+1)%3)*gridPic.getIconWidth(),Math.round(i/3)*gridPic.getIconHeight(),gridPic.getIconWidth(),gridPic.getIconHeight());
numbBackLabel[i] = new JLabel("");
numbBackLabel[i].setBounds(i*numbBackPic.getIconWidth()+1,gridPic.getIconHeight()*3,numbBackPic.getIconWidth(),numbBackPic.getIconHeight());
numbLabel[i] = new JLabel("");
numbLabel[i].setBounds(i*numbBackPic.getIconWidth(),gridPic.getIconHeight()*3,numbBackPic.getIconWidth(),numbBackPic.getIconHeight());
for (int j=0; j<9; j++) {
numbDisp[i][j] = new JLabel("");
numbDisp[i][j].setBounds((j * (selection.selected.getIconWidth() + 4) + (j / 3) * 4) + 4, (i * (selection.selected.getIconWidth() + 4) + (i / 3) * 4) + 4, selection.selected.getIconWidth(), selection.selected.getIconHeight());
boxArea[j][i] = new Rectangle((j*(selection.selected.getIconWidth()+4)+(j/3)*4)+4,(i*(selection.selected.getIconWidth()+4)+(i/3)*4)+4,selection.selected.getIconWidth(),selection.selected.getIconHeight());
add(numbDisp[i][j]);
}
}
for (int i=0; i<9; i++) {
numbPic = new ImageIcon(getClass().getResource("/numb_" + (i+1) + ".png"));
numbLabel[i].setIcon(numbPic);
gridLabel[i].setIcon(gridPic);
numbBackLabel[i].setIcon(numbBackPic);
add(selection.boxSelected);
add(gridLabel[i]);
add(numbLabel[i]);
add(numbBackLabel[i]);
}
setBoxNumb(random.nextInt(9)+1,random.nextInt(9)+1,random.nextInt(9)+1);
selection.setNewSelection(1,2);
}
public void setBoxNumb(int x, int y, int numb){
numbPic = new ImageIcon(getClass().getResource("/numb_" + numb + ".png"));
numbDisp[x - 1][y - 1].setIcon(numbPic);
}
}
So what I am trying to ask is why the image I want to be displayed if a field is selected does not appear ? Does anyone know how to fix this ?
Try to simplify your program down to the simplest one that reproduces the problem. You may discover the problem in the process, but if not, you'll have a clear example of it that's easy to understand.
Single step through your program to see if it's behaving as you expect.
Add logging to your program to see if it's behaving as you expect.
If you encounter any specific issues, feel free to ask a specific question. But right now, you're basically asking "how do I debug a program?"
What I found is that the layout layers are backwards to what i would expect. The Label you add first will always stay on top. That label won't be drawn over by JComponents add after the original is on. So basically, the earlier in the code you add a component to a JFrame, the Higher the priority that Component has.

How can i put delay in displaying the final result of my maze

i am creating a maze generation application. what i want to happen is that, when i run my program, it will show the animation on how the maze was created (it will show how it knocks the wall to create a path).
i tried to put delay on some of its parts but it won't run.thank you for the HUGE HELP!
here's the code:
public class Maze extends JPanel {
private Room[][] rooms;// m x n matrix of rooms
private ArrayList<Wall> walls; // List of walls
private Random rand;// for random wall
private int height;// height of matrix
private int width;// width of matrix
private int num;// incrementor
private JoinRoom ds;// union paths
// paint methods //
private int x_cord; // x-axis rep
private int y_cord;// y-axis rep
private int roomSize;
private int randomWall;
private int create;
int mazectr;
public static int m;// these are variables for the size of maze (m x n)
public static int n;
public Maze(int m, int n) {
JPanel j = new JPanel();
final JFrame f = new JFrame();
this.height = m;
this.width = n;
rooms = new Room[m][n];
walls = new ArrayList<Wall>((m - 1) * (n - 1));
long startTime = System.currentTimeMillis();
generateRandomMaze();
long endTime = System.currentTimeMillis();
final JLabel jl = new JLabel("Time Taken: " + (endTime-startTime) + "ms");
final JButton y = new JButton("OK");
j.add(jl);
j.add(y);
f.add(j);
y.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e)
{
f.setVisible(false);
}
});
f.setVisible(true);
f.setSize(100, 100);
//jl.setLocation(1000, 1500);
//jl.setBounds(0, 0, 110, 130);
setPreferredSize(new Dimension(800, 700));
}
private void generateRandomMaze() {
generateInitialRooms();// see next method
ds = new JoinRoom(width * height);
rand = new Random(); // here is the random room generator
num = width * height;
while (num > 1) {
// when we pick a random wall we want to avoid the borders getting eliminated
randomWall = rand.nextInt(walls.size());
Wall temp = walls.get(randomWall);
// we will pick two rooms randomly
int roomA = temp.currentRoom.y + temp.currentRoom.x * width;
int roomB = temp.nextRoom.y + temp.nextRoom.x * width;
// check roomA and roomB to see if they are already members
if (ds.find(roomA) != ds.find(roomB)) {
walls.remove(randomWall);
ds.unionRooms(ds.find(roomA), ds.find(roomB));
temp.isGone = true;
temp.currentRoom.adj.add(temp.nextRoom);
temp.nextRoom.adj.add(temp.currentRoom);
num--;
}// end of if
}// end of while
}
// name the room to display
private int roomNumber = 0;
private static Label input;
private static Label input2;
/**
* Sets the grid of rooms to be initially boxes
* This is self explanitory, we are only creating an reverse L for all
* The rooms and there is an L for the border
*/
private void generateInitialRooms() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// create north walls
rooms[i][j] = new Room(i, j);
if (i == 0) {
rooms[i][j].north = new Wall(rooms[i][j]);
} else {
rooms[i][j].north = new Wall(rooms[i - 1][j], rooms[i][j]);
walls.add(rooms[i][j].north);
}
if (i == height - 1) {
rooms[i][j].south = new Wall(rooms[i][j]);
}
if (j == 0) {
rooms[i][j].west = new Wall(rooms[i][j]);
} else {
rooms[i][j].west = new Wall(rooms[i][j - 1], rooms[i][j]);
walls.add(rooms[i][j].west);
}
if (j == width - 1) {
rooms[i][j].east = new Wall(rooms[i][j]);
}
rooms[i][j].roomName = roomNumber++;// we will name the rooms
}
}
// initalize entrance and exit
rooms[0][0].west.isGone = true;// you can replace .west.isGone with .north.isGone
// this is just saying the roomName for top left is 0
rooms[0][0].roomName = 0;
// we will remove the south wall of the last room
rooms[height - 1][width - 1].south.isGone = true;
// this is just saying the roomName for bottom right is the last element in the mxn room matrix
rooms[height - 1][width - 1].roomName = (height * width);
}
public void paintComponent(Graphics g) {
x_cord = 40;
y_cord = 40;
Thread t = new Thread();
// could have taken height as well as width
// just need something to base the roomsize
roomSize = (width - x_cord) / width + 20;
// temp variables used for painting
int x = x_cord;
int y = y_cord;
for (int i = 0; i <= height - 1; i++) {
for (int j = 0; j <= width - 1; j++) {
if (!(rooms[i][j].north.isGone)) {
g.drawLine(x, y, x + roomSize, y);
}//end of north if
// west wall not there draw the line
if (rooms[i][j].west.isGone == false) {
g.drawLine(x, y, x, y + roomSize);
}// end of west if
if ((i == height - 1) && rooms[i][j].south.isGone == false) {
g.drawLine(x, y + roomSize, x + roomSize,
y + roomSize);
}// end of south if
if ((j == width - 1) && rooms[i][j].east.isGone == false) {
g.drawLine(x + roomSize, y, x + roomSize,
y + roomSize);
}// end of east if
x += roomSize;// change the horizontal
try
{
Thread.sleep(50);
} catch (Exception e) {};
t.start();
}// end of inner for loop
x = x_cord;
y += roomSize;
}// end of outer for loop
}
public static void main(String[] args) throws IOException {
// use JFrame to put the created panel on
String path = "E:\\Iskul\\trys\\tryy\\bin\\GUI.jpg";
File file = new File("E:\\Iskul\\trys\\tryy\\bin\\GUI.jpg");
BufferedImage image = ImageIO.read(file);
File fileRec = new File("E:\\Iskul\\trys\\tryy\\bin\\re.jpg");
BufferedImage imageRec = ImageIO.read(fileRec);
File fileHex = new File("E:\\Iskul\\trys\\tryy\\bin\\hexx.jpg");
BufferedImage imageHex = ImageIO.read(fileHex);
final JFrame frame = new JFrame("Prim's Algorithm");
final JPanel jp = new JPanel();
final JTextField input = new JTextField(10);
final JTextField input2 = new JTextField(10);
final JButton jb = new JButton(new ImageIcon(imageRec));
jb.setBorder(BorderFactory.createEmptyBorder());
final JButton jb1 = new JButton(new ImageIcon(imageHex));
jb1.setBorder(BorderFactory.createEmptyBorder());
final JLabel label = new JLabel(new ImageIcon(image));
jb.setLocation(100, 10);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(795, 501));
jp.add(input);
jp.add(input2);
frame.add(jp);
jp.add(jb);
jp.add(jb1);
//jb.setImage(image);
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//int mazectr = 1;
int m = Integer.valueOf(input.getText());
int n = Integer.valueOf(input2.getText());
frame.remove(label);
frame.remove(jp);
//frame.add(new Maze(m,n));
frame.getContentPane().add(new Maze(m, n));
frame.pack();
}});
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//int m = Integer.valueOf(input.getText());
//int n = Integer.valueOf(input2.getText());
Hexa1 hexa = new Hexa1();
hexa.main();
//hexa.run();
}
});
}}// end of main
Your code wont work, you cant do an sleep in the Paint method, because if you do so, he wont draw, he just waits and at the end he'll draw your whole image.
If you want to do a nice effect, you should draw one step after the other but you should be aware that this is a lot of work to realize...

keylistener and JMenuBar issue

The menu bar won't draw and the keylistener won't work. Should I add the menu bar to a panel or a content pane? What am I doing wrong? What to do? Help? Thank you!
Please copy and run the code first.
CLASS DRAWINGDEMO
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawingDemo extends JFrame implements ActionListener, KeyListener{
DrawingPanel demo = new DrawingPanel();
public DrawingDemo()
{
getContentPane().add(demo);
setVisible(true);
setSize(1024,720);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel p = new JPanel();
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenu settings = new JMenu("Settings");
JMenu help = new JMenu("Help");
JMenuItem exit = new JMenuItem(">Exit");
JMenuItem imp = new JMenuItem(">Import");
JMenuItem exp = new JMenuItem(">Export");
JMenuItem sav = new JMenuItem(">Save");
JMenuItem ope = new JMenuItem(">Open");
file.add(ope);
file.add(sav);
file.add(imp);
file.add(exp);
file.add(exit);
mb.add(file);
mb.add(edit);
mb.add(settings);
mb.add(help);
setJMenuBar(mb);
while(true){
demo.repaint();
}
}
public void actionPerformed(java.awt.event.ActionEvent e)
{
}
public void KeyEvent(java.awt.event.ActionEvent e)
{
}
public void keyReleased(java.awt.event.KeyEvent e)
{
}
public void keyPressed(java.awt.event.KeyEvent e)
{
switch (e.getKeyCode()){
case KeyEvent.VK_A :
{
demo.pos_camx -= 0.5;
}
break;
case KeyEvent.VK_D :
{
demo.pos_camx += 0.5;
}
break;
case KeyEvent.VK_W :
{
demo.pos_camy += 0.5;
}
break;
case KeyEvent.VK_S :
{
demo.pos_camy -= 0.5;
}
break;
}
}
public void keyTyped(java.awt.event.KeyEvent e)
{
}
public static void main(String[] args)
{
new DrawingDemo();
}
}
CLASS DRAWINGPANEL
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.awt.Graphics;
public class DrawingPanel extends JPanel {
long nextSecond = System.currentTimeMillis() + 1000;
int framesInLastSecond = 0;
int framesInCurrentSecond = 0;
int[][] LP= new int[19][3];
double pos_camx,pos_camy,pos_camz,rot_camx,rot_camy,xpoint,ypoint,zpoint;
double rot_radx,rot_rady,nclip,xscr,yscr,kx,ky;
int pxscr,pyscr,nxscr,nyscr,e;
public void paint(Graphics g)
{
LP[0][0] = -1;
LP[0][1] = -1;
LP[0][2] = -1;
LP[1][0] = 1;
LP[1][1] = -1;
LP[1][2] = -1;
LP[2][0] = 1;
LP[2][1] = 1;
LP[2][2] = -1;
LP[3][0] = -1;
LP[3][1] = 1;
LP[3][2] = -1;
LP[4][0] = -1;
LP[4][1] = -1;
LP[4][2] = -1;
LP[5][0] = 1;
LP[5][1] = 1;
LP[5][2] = -1;
LP[6][0] = 1;
LP[6][1] = 1;
LP[6][2] = 1;
LP[7][0] = -1;
LP[7][1] = 1;
LP[7][2] = 1;
LP[8][0] = -1;
LP[8][1] = -1;
LP[8][2] = 1;
LP[9][0] = 1;
LP[9][1] = -1;
LP[9][2] = 1;
LP[10][0] = 1;
LP[10][1] = 1;
LP[10][2] = 1;
LP[11][0] = -1;
LP[11][1] = -1;
LP[11][2] = 1;
LP[12][0] = -1;
LP[12][1] = -1;
LP[12][2] = -1;
LP[13][0] = 1;
LP[13][1] = -1;
LP[13][2] = 1;
LP[14][0] = 1;
LP[14][1] = -1;
LP[14][2] = -1;
LP[15][0] = 1;
LP[15][1] = 1;
LP[15][2] = 1;
LP[16][0] = -1;
LP[16][1] = 1;
LP[16][2] = -1;
LP[17][0] = -1;
LP[17][1] = 1;
LP[17][2] = 1;
LP[18][0] = -1;
LP[18][1] = -1;
LP[18][2] = -1;
pos_camx = 0;
pos_camy = 0;
pos_camz = 0;
rot_camx = 0;
rot_camy = 0;
rot_radx = 3.1415*rot_camx/180;
rot_rady = 3.1415*rot_camy/180;
nclip = 0.275;
kx = 8.52/getWidth();
ky = 5.46/getHeight();
super.paint(g);
Graphics2D g1 = (Graphics2D)g;
g1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.black);
xpoint = (double)(LP[0][0])/2;
ypoint = 20 + (double)(LP[0][1])/2;
zpoint = (double)(LP[0][2])/2;
pxscr = (int)(
((xpoint - pos_camx)*Math.cos(rot_radx) + (ypoint + pos_camy)*Math.sin(rot_radx))*nclip
/((ypoint - pos_camy)*Math.cos(rot_radx) + (pos_camx- xpoint)*Math.sin(rot_radx) + 0.0000000012)*100/kx
+ getWidth()/2);
pyscr = (int)(
getHeight()/2-
(((ypoint + pos_camy)*Math.sin(rot_rady) + (zpoint - pos_camz)*Math.cos(rot_rady))*nclip
/((ypoint - pos_camy)*Math.cos(rot_radx) + (pos_camx + xpoint)*Math.sin(rot_radx) + 0.0000000012)*100/ky)
);
for (int i=1; i<19;i++){
xpoint = (double)(LP[i][0])/2;
ypoint = 20 + (double)(LP[i][1])/2;
zpoint = (double)(LP[i][2])/2;
nxscr = (int)(
((xpoint - pos_camx)*Math.cos(rot_radx) + (ypoint + pos_camy)*Math.sin(rot_radx))*nclip
/((ypoint - pos_camy)*Math.cos(rot_radx)+(pos_camx + xpoint)*Math.sin(rot_radx)+0.0000000012)*100/kx
+getWidth()/2);
nyscr = (int)(
getHeight()/2-
(((ypoint + pos_camy)*Math.sin(rot_rady)+(zpoint - pos_camz)*Math.cos(rot_rady))*nclip
/((ypoint - pos_camy)*Math.cos(rot_radx)+(pos_camx + xpoint)*Math.sin(rot_radx)+0.0000000012)*100/ky)
);
g1.drawLine(pxscr,pyscr,nxscr,nyscr);
pxscr = nxscr;
pyscr = nyscr;
}
g.drawString("(" + pxscr + "," + pyscr + ")",20,40);
long currentTime = System.currentTimeMillis();
if (currentTime > nextSecond) {
nextSecond += 1000;
framesInLastSecond = framesInCurrentSecond;
framesInCurrentSecond = 0;
}
framesInCurrentSecond++;
g.drawString(framesInLastSecond + " fps", 20, 20);
}
}
Swing is an Event Driven environment, blocking the Event Dispatching Thread in any way will prevent it from begin able to process any events (such as mouse or keyboard events).
KeyListener is a low level API and is generally discourage for a number of reasons, focus issues been the most prominent. In order for a component to be able to respond to a KeyListener it must be focusable and have focus. The problem you have, is neither of these conditions are actually being meet (nor are you actually registering the key listener with anything).
While the JFrame is focusable, it contains a JRootPane which contains (amongst other things) a content pane, which contains your DrawingPanel. Any of these may steal focus from the frame at any time, rendering your KeyListener useless.
The preferred method is to use the key bindings API
Generally, you are discouraged from overriding paint. Paint is a very complex method and you should only override it if you are absolutely sure it is the right thing to do. The preferred method for performing custom painting is to override the paintComponent method, as out lined here. The most important reason for this, is this method is double buffered, making you painting smoother, also, you, generally, won't interfere with other components that may be on the component.
Also, in your paint method, you are setting the camera positions to 0 which basically undoes all you good work with your non-functional key listeners ;)
public class DrawingDemo extends JFrame { //implements ActionListener, KeyListener {
DrawingPanel demo = new DrawingPanel();
public DrawingDemo() {
getContentPane().add(demo);
setVisible(true);
setSize(1024, 720);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel p = new JPanel();
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenu settings = new JMenu("Settings");
JMenu help = new JMenu("Help");
JMenuItem exit = new JMenuItem(">Exit");
JMenuItem imp = new JMenuItem(">Import");
JMenuItem exp = new JMenuItem(">Export");
JMenuItem sav = new JMenuItem(">Save");
JMenuItem ope = new JMenuItem(">Open");
file.add(ope);
file.add(sav);
file.add(imp);
file.add(exp);
file.add(exit);
mb.add(file);
mb.add(edit);
mb.add(settings);
mb.add(help);
setJMenuBar(mb);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DrawingDemo();
}
});
}
public class DrawingPanel extends JPanel {
long nextSecond = System.currentTimeMillis() + 1000;
int framesInLastSecond = 0;
int framesInCurrentSecond = 0;
int[][] LP = new int[19][3];
double pos_camx, pos_camy, pos_camz, rot_camx, rot_camy, xpoint, ypoint, zpoint;
double rot_radx, rot_rady, nclip, xscr, yscr, kx, ky;
int pxscr, pyscr, nxscr, nyscr, e;
public DrawingPanel() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "Move.A");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "Move.D");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "Move.W");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "Move.S");
ActionMap am = getActionMap();
am.put("Move.A", new MoveXAction(this, 0.5f));
am.put("Move.D", new MoveXAction(this, -0.5f));
am.put("Move.W", new MoveYAction(this, 0.5f));
am.put("Move.S", new MoveYAction(this, -0.5f));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
LP[0][0] = -1;
LP[0][1] = -1;
LP[0][2] = -1;
LP[1][0] = 1;
LP[1][1] = -1;
LP[1][2] = -1;
LP[2][0] = 1;
LP[2][1] = 1;
LP[2][2] = -1;
LP[3][0] = -1;
LP[3][1] = 1;
LP[3][2] = -1;
LP[4][0] = -1;
LP[4][1] = -1;
LP[4][2] = -1;
LP[5][0] = 1;
LP[5][1] = 1;
LP[5][2] = -1;
LP[6][0] = 1;
LP[6][1] = 1;
LP[6][2] = 1;
LP[7][0] = -1;
LP[7][1] = 1;
LP[7][2] = 1;
LP[8][0] = -1;
LP[8][1] = -1;
LP[8][2] = 1;
LP[9][0] = 1;
LP[9][1] = -1;
LP[9][2] = 1;
LP[10][0] = 1;
LP[10][1] = 1;
LP[10][2] = 1;
LP[11][0] = -1;
LP[11][1] = -1;
LP[11][2] = 1;
LP[12][0] = -1;
LP[12][1] = -1;
LP[12][2] = -1;
LP[13][0] = 1;
LP[13][1] = -1;
LP[13][2] = 1;
LP[14][0] = 1;
LP[14][1] = -1;
LP[14][2] = -1;
LP[15][0] = 1;
LP[15][1] = 1;
LP[15][2] = 1;
LP[16][0] = -1;
LP[16][1] = 1;
LP[16][2] = -1;
LP[17][0] = -1;
LP[17][1] = 1;
LP[17][2] = 1;
LP[18][0] = -1;
LP[18][1] = -1;
LP[18][2] = -1;
// pos_camx = 0;
// pos_camy = 0;
// pos_camz = 0;
rot_camx = 0;
rot_camy = 0;
rot_radx = 3.1415 * rot_camx / 180;
rot_rady = 3.1415 * rot_camy / 180;
nclip = 0.275;
kx = 8.52 / getWidth();
ky = 5.46 / getHeight();
Graphics2D g1 = (Graphics2D) g;
g1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.black);
xpoint = (double) (LP[0][0]) / 2;
ypoint = 20 + (double) (LP[0][1]) / 2;
zpoint = (double) (LP[0][2]) / 2;
pxscr = (int) (((xpoint - pos_camx) * Math.cos(rot_radx) + (ypoint + pos_camy) * Math.sin(rot_radx)) * nclip
/ ((ypoint - pos_camy) * Math.cos(rot_radx) + (pos_camx - xpoint) * Math.sin(rot_radx) + 0.0000000012) * 100 / kx
+ getWidth() / 2);
pyscr = (int) (getHeight() / 2
- (((ypoint + pos_camy) * Math.sin(rot_rady) + (zpoint - pos_camz) * Math.cos(rot_rady)) * nclip
/ ((ypoint - pos_camy) * Math.cos(rot_radx) + (pos_camx + xpoint) * Math.sin(rot_radx) + 0.0000000012) * 100 / ky));
for (int i = 1; i < 19; i++) {
xpoint = (double) (LP[i][0]) / 2;
ypoint = 20 + (double) (LP[i][1]) / 2;
zpoint = (double) (LP[i][2]) / 2;
nxscr = (int) (((xpoint - pos_camx) * Math.cos(rot_radx) + (ypoint + pos_camy) * Math.sin(rot_radx)) * nclip
/ ((ypoint - pos_camy) * Math.cos(rot_radx) + (pos_camx + xpoint) * Math.sin(rot_radx) + 0.0000000012) * 100 / kx
+ getWidth() / 2);
nyscr = (int) (getHeight() / 2
- (((ypoint + pos_camy) * Math.sin(rot_rady) + (zpoint - pos_camz) * Math.cos(rot_rady)) * nclip
/ ((ypoint - pos_camy) * Math.cos(rot_radx) + (pos_camx + xpoint) * Math.sin(rot_radx) + 0.0000000012) * 100 / ky));
g1.drawLine(pxscr, pyscr, nxscr, nyscr);
pxscr = nxscr;
pyscr = nyscr;
}
g.drawString("(" + pxscr + "," + pyscr + ")", 20, 40);
long currentTime = System.currentTimeMillis();
if (currentTime > nextSecond) {
nextSecond += 1000;
framesInLastSecond = framesInCurrentSecond;
framesInCurrentSecond = 0;
}
framesInCurrentSecond++;
g.drawString(framesInLastSecond + " fps", 20, 20);
}
}
public class MoveXAction extends AbstractAction {
private float direction;
private final DrawingPanel pane;
private MoveXAction(DrawingPanel pane, float amount) {
this.direction = amount;
this.pane = pane;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("...x by " + direction);
pane.pos_camx += direction;
pane.repaint();
}
}
public class MoveYAction extends AbstractAction {
private float direction;
private final DrawingPanel pane;
private MoveYAction(DrawingPanel pane, float amount) {
this.direction = amount;
this.pane = pane;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("...y by " + direction);
pane.pos_camy += direction;
pane.repaint();
}
}
}
I had a quick play around and I have to say, Nice ;)
you only need to repaint if something changed, and even then, probably not a million times a second ( or whatever your cpu can handle). so i would suggest to change the while(true) to a loop which waits for a bit, or repaint in the keylistener (depending on what you want the application to do)
and you implement the keylistener interface, but you are not adding it to the registered listeners so you need a this.addKeyListener(this);
the JMenuBar doesnt show up because you make the frame visible before adding the menubar. normally you want to make the window visible after initializing its components.
so put the setVisible(true); after you add the menubar

using repaint() method with actionPerformed

How to use the repaint() method when a button is pressed and Graphics p has to re-paint everything from scratch?
Thanks.
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class fares extends JPanel{
private static final long serialVersionUID = 1L;
public static int xaxis1,xaxis2,yaxis3,yaxis4;
public ControlsB(square) {
final JButton btn1 = new JButton("Resize");
final Box b = Box.createHorizontalBox();
b.add(new JLabel("Please enter range: "));
Box b0 = Box.createVerticalBox();//create a vertical box to stack the controls
Box b1 = Box.createHorizontalBox(); // create a horizontal box for the x-axis
//x-axis
b1.add(new JLabel("mark "));
b1.add(new JLabel("for"));
f1.setMaximumSize(new Dimension(100,30));
b1.add(f1);
b1.add(new JLabel("till"));
f2.setMaximumSize(new Dimension(100,30));
b1.add(f2);
//y-axis
//this code is not in use at the moment
f4.setMaximumSize(new Dimension(100,30));
b2.add(f4);
b0.add(b1);
add(b);
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
f = Integer.parseInt(f1.getText());
invalidate();
validate();
paint(p);//this is not working...
}
});
b.add(btn1);
}
}
This is the code that has to be called and repainted:
import java.awt.*;
import javax.swing.*;
class Graph extends JPanel {
public static Graphics p;
private static final long serialVersionUID = 1L;
public static int f;
public static int g;
#Override
public Dimension getPreferredSize()
{
return (new Dimension(560,560));
}
public void paintComponent(Graphics p) {
super.paintComponent(p);
Graphics2D graph = (Graphics2D)p;
Dimension appletSize = this.getSize();
int appletHeight = (int)(appletSize.height);
int appletWidth = appletSize.width;
//change -ve num to +ve
int g3 = Math.abs(g);
int a1 = g3 + f;
int b1 = a1;
int d = (appletWidth / a1);
int e = (appletHeight / b1);
//draw y-axis numbers
//(+ve)
while(f != 0){
String s = String.valueOf(f);
m = m + b;
f = f - 1;
}
//(-ve)
m2 = y;
while(f2 != g-1)
m2 = m2 + b;
f2 = f2 - 1;
}
//draw x-axis numbers.
//(-ve)
while(g != 0){
String hy = String.valueOf(g);
n = n + a;
g = g + 1;
}
//(+ve)
n2 = x + a;
while(g2 != g3+1){
String w = String.valueOf(g2);
n2 = n2 + a;
g2 = g2 + 1;
}
BasicStroke aLine2 = new BasicStroke(1.0F,
BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
graph.setStroke(aLine2);
//notch on numbers and grid lines
//left to right, top to bottom notches
int v2 = -5;
int v5 = 0;
while(i <= a1-1){
p.setColor(Color.lightGray);//lightgray line
a = a + d;
b = b + e;
i = i + 1;
}
}
}
At the moment the resize button works, but I need to resize my window in order for the graph to respond to the inputs given. Basically when resizing the graph is being redrawn / repainted... now I need this to be done automatically.
It's hard to tell what's wrong based on snippets of code, but it appears that your graph is drawn on the Graph object, called graph (please correct me if I'm wrong), and you appear to be trying to repaint (or paint -- never call that directly!) your ControlsB panel. If so, then you may be calling methods on the wrong object. Perhaps you need to do something like:
// graph is final so it may be used in an inner class
public ControlsB(Box box2, final Graph graph) {
// .....
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
f = Integer.parseInt(f1.getText());
g = Integer.parseInt(f2.getText());
System.out.println(f + " " + g);
// invalidate();
// validate();
// paint(p); ***** NEVER do this
graph.repaint();
}
});
}
Also:
Never call paint(...) directly on a component except in very special circumstances (this isn't it).
Never try to hold on to a components Graphics object and draw with it as this will often lead to a NullPointerException occurring, and it surely won't work.
Do read up on how to do drawing in Swing in the standard Swing tutorials. You would likely learn much from doing this.
Again, if you don't get a decent answer soon, consider creating and posting an sscce.
Changes made :
- Inside the GraphApplet class, these two lines have been changed
Box box2 = new Box(BoxLayout.Y_AXIS); // Changed
// Added one more argument, while making Object.
ControlsB b = new ControlsB(box2, graph);//horizontal
Inside Graph Class, setValues(...) method has been added.
-
public void setValues(int x, int y)
{
xstart = x;
ystart = y;
repaint();
}
Inside Graph class, scope of variables xstart and ystart has
been changed to Instance/Class
- Inside ControlB Class
refineButton = new JButton("Refine");
buttonBox.add(refineButton);
refineButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int x = Integer.parseInt(f1.getText());
int y = Integer.parseInt(f3.getText());
/*
* Calling a method of Graph Class (setValues)
* and passing the values that we had got from
* the respective JTextFields.
*/
graph.setValues(x, y); }
});
}
Here watch this code example, modified your previous example a bit to give you one idea how to make this work. Have a look at the image attached, only use these three thingies, enter some integer values in the pointed JTextFields and then click on Refine JButton, you will see how to repaint. Since I really don't know how the logic works, hence won't be able to say how you can optimize your code, though to give you one idea, here it is :
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class GraphApplet extends JApplet
{
private static final long serialVersionUID = 1L;
public void init(){
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Container conn = getContentPane();
conn.setLayout(new BorderLayout());
Graph graph = new Graph();//graph
conn.add(graph,BorderLayout.CENTER);
Box box1 = new Box(BoxLayout.X_AXIS);
ControlsA a = new ControlsA(box1);//vertical
conn.add(a,BorderLayout.EAST);
Box box2 = new Box(BoxLayout.Y_AXIS); // Changed
// Added one more argument, while making Object.
ControlsB b = new ControlsB(box2, graph);//horizontal
conn.add(b,BorderLayout.SOUTH);
}
});
}
}
class Graph extends JPanel {
private static final long serialVersionUID = 1L;
private int xstart;
private int ystart;
public Graph(){
this.setBackground(Color.yellow);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(460,560));
}
/*
* Added this method, which will call
* repaint(), everytime it is been
* called from anywhere. Moreover
* the variables used inside
* paintComponent(...) method xstart
* and ystart, have been changed to
* instance variables of the Graph Class.
*/
public void setValues(int x, int y)
{
xstart = x;
ystart = y;
repaint();
}
#Override
public void paintComponent(Graphics p)
{
super.paintComponent(p);
Graphics2D graph = (Graphics2D)p;
Dimension appletSize = this.getSize();
int appletHeight = (int)(appletSize.height);
int appletWidth = appletSize.width;
this.setBackground(Color.yellow);//set background color.
int x,y,y1,x1,a,b,p1x,p1y,p2x,p2y;
//line co-ordinates
//the numbers represent the number of boxes on the graph
// Made these two variables as Instance Variables
//int xstart = 10;
//int ystart = 5;
int xfinish = 2;
int yfinish = 8;
//other variables
int i = 0;
int i2 = 0;
int m = 0;
int n = 0;
int m2 = 0;
int n2 = 0;
int f2 = 0;
int g2 = 1;
//ranges
int f = 5;
int g = -5;
//change -ve num to +ve
int g3 = Math.abs(g);
int a1 = g3 + f;
int b1 = a1;
y1 = (appletHeight);
x1 = (appletWidth);
y = (appletHeight / 2);
x = (appletWidth / 2);
a = (appletWidth / a1);
b = (appletHeight / b1);
int d = (appletWidth / a1);
int e = (appletHeight / b1);
/**
to determine the
ammount of pixles there
is in each box of the
graph, both y-axis and
x-axis
*/
int xbox = x1 / 10;
int ybox = y1 / 10;
//line variables
//the xstart, ystart, etc represent the number of boxes
//top point of the line on the graph
p1x = xbox * xstart;//start x
p1y = ybox * ystart;//start y
//lowwer point of the line on the graph
p2x = xbox * xfinish;//finish x
p2y = ybox * yfinish;//finish y
//draw y-axis numbers
//(+ve)
while(f != 0){
String s = String.valueOf(f);
p.drawString(s,(x + 5),m + 13);
m = m + b;
f = f - 1;
}
//(-ve)
m2 = y;
while(f2 != g-1){
String u = String.valueOf(f2);
p.drawString(u,(x + 5),m2 - 3);
m2 = m2 + b;
f2 = f2 - 1;
}
//draw x-axis numbers.
//(-ve)
while(g != 0){
String t = String.valueOf(g);
p.drawString(t,n,y - 5);
n = n + a;
g = g + 1;
}
//(+ve)
n2 = x + a;
while(g2 != g3+1){
String vw = String.valueOf(g2);
p.drawString(vw,n2 -10,y - 5);
n2 = n2 + a;
g2 = g2 + 1;
}
BasicStroke aLine2 = new BasicStroke(1.0F,
BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
graph.setStroke(aLine2);
//notch on numbers and grid lines
//left to right, top to bottom notches
int v2 = -5;
int v5 = 0;
while(i <= a1-1){
p.setColor(Color.lightGray);//lightgray line
p.drawLine(a,0,a,y1);//vertical lightgray
p.drawLine(0,b,x1,b);//horizontal lightgray
a = a + d;
b = b + e;
i = i + 1;
}
//notches
while(i2 <= a1){
p.setColor(Color.blue);//notch color
p.drawString("x",v2+2,y+3);//xaxis
p.drawString("x",x-4,v5+4);//yaxis
v5 = v5 + e;
v2 = v2 + d;
i2 = i2 + 1;
}
//draws the border of the graph
p.setColor(Color.black);
Rectangle2D.Float rect = new Rectangle2D.Float(0,0,x1,y1);
BasicStroke aLine = new BasicStroke(2.5F,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
graph.setStroke(aLine);
graph.draw(rect);
//draw cross
BasicStroke aLine3 = new BasicStroke(2.5F,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
graph.setStroke(aLine3);
p.drawLine(x,0,x,y1); //vertical line
p.drawLine(0,y,x1,y); //horizontal line
//display the value of graph width and graph height
String aw = String.valueOf(x1);
p.drawString("Graph Width = ", 50,90);
p.drawString(aw,150,90);
p.drawString("Graph Height = ", 50,110);
String ah = String.valueOf(y1);
p.drawString(ah,156,110);
//draw line on graph
BasicStroke aLine4 = new BasicStroke(1.5F,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
graph.setStroke(aLine4);
p.setColor(Color.red);
if(p1x <= x1 && p2x <= x1 && p1y <= y1 && p2y <= y1){
p.drawLine(p1x,p1y,p2x,p2y);
Color c = new Color(0,0,0);
p.setColor(c);
p.drawString("X", p1x-4,p1y+4);
p.drawString("X", p2x-4,p2y+4);
}
else{
p.setColor(Color.black);
p.drawRect(48,34,223,35);
p.setColor(Color.white);
p.fillRect(49,35,222,34);
p.setColor(Color.red);
p.drawString("Wrong co-ordinates!!!", 50,50);
p.drawString("Values exceede applet dimensions.", 50,65);
}
}
}
class ControlsA extends JPanel
{
private static final long serialVersionUID = 1L;
public ControlsA (Box a)
{
a = Box.createVerticalBox();
a.add(new JLabel("Please enter the values below:"));
a.add(new JLabel("a"));
JTextField g1 = new JTextField("0.0");
g1.setMaximumSize(new Dimension(100,30));
a.add(g1);
a.add(new JLabel("b"));
JTextField g2 = new JTextField("0.0");
g2.setMaximumSize(new Dimension(100,30));
a.add(g2);
a.add(new JLabel("c"));
JTextField g3 = new JTextField("0.0");
g3.setMaximumSize(new Dimension(100,30));
a.add(g3);
a.add(new JLabel("d"));
JTextField g4 = new JTextField("0.0");
g4.setMaximumSize(new Dimension(100,30));
a.add(g4);
a.add(new JButton("Plot"));
a.add(new JButton("Refine"));
add(a);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200,100));
}
}
class ControlsB extends JPanel
{
private static final long serialVersionUID = 1L;
private Graph graph;
private JButton refineButton;
public ControlsB (Box b, Graph g) {
graph = g;
b = Box.createVerticalBox();
Box boxUpper = new Box(BoxLayout.X_AXIS);
boxUpper.add(new JLabel("Please enter range: "));
b.add(boxUpper);
Box boxX = new Box(BoxLayout.X_AXIS);
boxX.add(new JLabel(" x-axis "));
boxX.add(new JLabel("from"));
// Added final keyword.
final JTextField f1 = new JTextField("-5");
f1.setMaximumSize(new Dimension(100,30));
boxX.add(f1);
boxX.add(new JLabel(" to "));
JTextField f2 = new JTextField("5");
f2.setMaximumSize(new Dimension(100,30));
boxX.add(f2);
b.add(boxX);
//b.add(new JLabel(". "));
Box boxY = new Box(BoxLayout.X_AXIS);
boxY.add(new JLabel("y-axis "));
boxY.add(new JLabel("from"));
// Added final keyword.
final JTextField f3 = new JTextField("5");
f3.setMaximumSize(new Dimension(100,30));
boxY.add(f3);
boxY.add(new JLabel("to"));
JTextField f4 = new JTextField("-5");
f4.setMaximumSize(new Dimension(100,30));
boxY.add(f4);
b.add(boxY);
Box buttonBox = new Box(BoxLayout.X_AXIS);
buttonBox.add(new JButton("Plot"));
/*
* Made this an instance variable,
* and added ActionListener to it.
*/
refineButton = new JButton("Refine");
buttonBox.add(refineButton);
refineButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int x = Integer.parseInt(f1.getText());
int y = Integer.parseInt(f3.getText());
/*
* Calling a method of Graph Class (setValues)
* and passing the values that we had got from
* the respective JTextFields.
*/
graph.setValues(x, y);
}
});
b.add(buttonBox);
add(b);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200,100));
}
}
Congrats, you just stumbled upon the subtleties of repaint :) There is a quite nice explanation at http://www.oracle.com/technetwork/java/painting-140037.html#paint_process . Here is the summary:
If you call repaint() on a heavyweight component like JFrame or JApplet, it will repaint immediately.
If you call repaint() on a JComponent, it will "schedule" the repainting to occur at some point in the future as decided by the Repaint Manager (which means, you have no control over it).
So, call the repaint() method in JApplet and you should see the changes as soon as you click the button.
Have you tried instead of paint(p) to use p.repaint() or p.update(p.getGraphics())?
I have not done Swing for ages and I can't remember exactly how it's behaving. One sure thing is that you have to be aware of when it is the good time to call paint, update or validate and how to use correctly the EventDispatcherThread (EDT). Otherwise your application will look like a lot of java swing applications : a crap filled of UI bugs...
I don't say Swing is crap, I say that if you don't know how it works, your UI will be a crap.

Multiple Bookings System

I am currently developing a booking system as a task for my degree. I need the seating plan to be "saved/stored" for each showing time (radio buttons), so that e.g. If I book 2 tickets at 13:00, I can also book 2 tickets on the same spot for 15:00. What is the best way of doing this?
PS: I'm not making use of a database and I would prefer not to; due to task's requirements.
Here's my code, please run it if you can.
// CM1203 Fundamentals of Computing with Java; Second Assignement.
// Walter Carvalho - C1001984; 2012.
// Cardiff University
// Load Libraries
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
public class cinemaSystem extends JFrame implements ActionListener {
// Global Variables
boolean lselected, rselected, mselected;
double chargeDue;
int a, b, c;
static Ticket oapticket, childticket, adultticket;
JFrame frame = new JFrame(); // Creates JFrame
JLabel title, lchild, ladult, loap, ltotalprice, time;
JTextField child, adult, oap, totalprice;
JButton submit;
JRadioButton time1, time2, time3, time4, time5; // Radio Butons
JToggleButton l[][], m[][], r[][]; // Names grid of JButtons
JPanel panel1, panel2, panel3, panel4, panel5, panel6;
ArrayList<String> seatsAvailable = new ArrayList<String>();
ArrayList<String> coupon = new ArrayList<String>();
// Constructor
public cinemaSystem(){
title = new JLabel("Cinema Booking System");
title.setFont(new Font("Helvetica", Font.BOLD, 30));
title.setLocation(12,5);
title.setSize(600, 60);
frame.setLayout(null); // Setting Grid Layout
// panel1.setLayout(new GridLayout(seat,row));
l = new JToggleButton[4][4]; // Allocating Size of Grid
panel1 = new JPanel(new GridLayout(4,4));
panel1.setBounds(20, 95, 220, 140);
for(int y = 0; y <4 ; y++){
for(int x = 0; x < 4; x++){
l[x][y] = new JToggleButton("L" + y + x); // Creates New JButton
l[x][y].addActionListener(this);
seatsAvailable.add("L" + y + x);
panel1.add(l[x][y]); //adds button to grid
}
}
m = new JToggleButton[4][2]; // Allocating Size of Grid
panel2 = new JPanel(new GridLayout(2,4));
panel2.setBounds(240, 165, 220, 70);
for(int y = 0; y <2 ; y++){
for(int x = 0; x < 4; x++){
m[x][y] = new JToggleButton("M" + y + x); // Creates New JButton
m[x][y].addActionListener(this);
seatsAvailable.add("M" + y + x);
panel2.add(m[x][y]); //adds button to grid
}
}
r = new JToggleButton[4][4]; // Allocating Size of Grid
panel3 = new JPanel(new GridLayout(4,4));
panel3.setBounds(460, 95, 220, 140);
for(int y = 0; y <4 ; y++){
for(int x = 0; x < 4; x++){
r[x][y] = new JToggleButton("R" + y + x); // Creates New JButton
r[x][y].addActionListener(this);
seatsAvailable.add("R" + y + x);
panel3.add(r[x][y]); //adds button to grid
}
}
panel4 = new JPanel(new FlowLayout());
panel4.setBounds(0, 250, 300, 70);
lchild = new JLabel("Child");
child = new JTextField("0", 2);
child.addActionListener(this);
ladult = new JLabel("Adult");
adult = new JTextField("0", 2);
adult.addActionListener(this);
loap = new JLabel("OAP");
oap = new JTextField("0", 2);
oap.addActionListener(this);
submit = new JButton("Submit");
submit.addActionListener(this);
oapticket = new Ticket(4.70);
childticket = new Ticket(3.50);
adultticket = new Ticket(6.10);
child.addKeyListener(new MyKeyAdapter());
oap.addKeyListener(new MyKeyAdapter());
adult.addKeyListener(new MyKeyAdapter());
panel4.add(lchild);
panel4.add(child);
panel4.add(ladult);
panel4.add(adult);
panel4.add(loap);
panel4.add(oap);
panel4.add(submit);
panel5 = new JPanel(new FlowLayout());
panel5.setBounds(240, 250, 300, 70);
ltotalprice = new JLabel("Charge Due (£): ");
totalprice = new JTextField("£0.00", 5);
totalprice.setEnabled(false);
panel5.add(ltotalprice);
panel5.add(totalprice);
panel6 = new JPanel(new FlowLayout());
panel6.setBounds(0, 55, 560, 30);
time = new JLabel("Please select a film time: ");
time1 = new JRadioButton("13:00", true);
time2 = new JRadioButton("15:00", false);
time3 = new JRadioButton("17:00", false);
time4 = new JRadioButton("19:00", false);
time5 = new JRadioButton("21:00", false);
ButtonGroup group = new ButtonGroup();
group.add(time1);
group.add(time2);
group.add(time3);
group.add(time4);
group.add(time5);
panel6.add(time);
panel6.add(time1);
panel6.add(time2);
panel6.add(time3);
panel6.add(time4);
panel6.add(time5);
time1.addActionListener(this);
time2.addActionListener(this);
time3.addActionListener(this);
time4.addActionListener(this);
time5.addActionListener(this);
frame.add(title);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.add(panel4);
frame.add(panel5);
frame.add(panel6);
frame.setPreferredSize(new Dimension(700, 350));
frame.setTitle("Cinema Booking");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
// Calculates Charge Due for current transaction.
public double calcChargeDue(){
DecimalFormat df = new DecimalFormat("#.##");
double chargeDue = 0.0;
chargeDue = (a*childticket.price) + (b*oapticket.price) + (c*adultticket.price);
totalprice.setText("£"+df.format(chargeDue));
return chargeDue;
}
// Method to check if the number of people matches the number of seats selected.
public void check(){
int check = coupon.size();
int noTickets = a + b + c;
if (check != noTickets){
submit.setEnabled(false);
}
else {
submit.setEnabled(true);
}
}
// Ticket Object
public class Ticket {
double price;
// Constructor
public Ticket(double cost) {
price = cost;
}
public double getTicketPrice() {
return price;
}
}
public void actionPerformed(ActionEvent e)
{
a = Integer.parseInt(child.getText());
b = Integer.parseInt(oap.getText());
c = Integer.parseInt(adult.getText());
for(int y = 0; y < 4; y++){
for(int x = 0; x < 4; x++){
lselected = l[x][y].isSelected();
rselected = r[x][y].isSelected();
if (e.getSource() == l[x][y]) {
if(lselected == true){
coupon.add(e.getActionCommand());
calcChargeDue();
check();
}
else {
coupon.remove(e.getActionCommand());
check();
}
}
if (e.getSource() == r[x][y]) {
if(rselected == true){
coupon.add(e.getActionCommand());
calcChargeDue();
check();
}
else {
coupon.remove(e.getActionCommand());
check();
}
}
if (e.getSource() == oap){
calcChargeDue();
check();
}
if (e.getSource() == adult){
calcChargeDue();
check();
}
if (e.getSource() == child){
calcChargeDue();
check();
}
}
}
for(int y = 0; y < 2; y++){
for(int x = 0; x < 4; x++){
mselected = m[x][y].isSelected();
if (e.getSource() == m[x][y]) {
if(mselected == true){
coupon.add(e.getActionCommand());
calcChargeDue();
check();
}
else {
coupon.remove(e.getActionCommand());
check();
}
}
}
}
if(time1 == e.getSource()){
}
if(time2 == e.getSource()){
}
if(time3 == e.getSource()){
}
if(time4 == e.getSource()){
}
if(time5 == e.getSource()){
}
if(submit == e.getSource()) {
for(int y = 0; y < 4; y++){
for(int x = 0; x < 4; x++){
lselected = l[x][y].isSelected();
rselected = r[x][y].isSelected();
if (lselected == true) {
l[x][y].setEnabled(false);
}
if (rselected == true) {
r[x][y].setEnabled(false);
}
}
}
for(int y = 0; y < 2; y++){
for(int x = 0; x < 4; x++){
mselected = m[x][y].isSelected();
if (mselected == true) {
m[x][y].setEnabled(false);
}
}
}
Collections.sort(coupon);
System.out.println("Here's your ticket:");
System.out.println(coupon);
System.out.println("Child: " + child.getText());
System.out.println("Adult: " + adult.getText());
System.out.println("OAP: " + oap.getText());
System.out.println("Total Price: " + totalprice.getText());
System.out.println("Thank you. Enjoy your film.");
System.out.println(" ");
coupon.clear();
child.setText("0");
adult.setText("0");
oap.setText("0");
}
}
// Main Class
public static void main(String[] args) {
new cinemaSystem(); //makes new ButtonGrid with 2 parameters
}
}
Related: Java: Disable all JToggleButtons after Submission — setEnabled(false);
If you already have it working for one booking time, all you need to do is take all your data structures used for storing information about that booking time and double them up to support several independent booking times.
For instance, ArrayList<String> seatsAvailable = new ArrayList<String>(); will become:
Dictionary<Time, ArrayList<String> > seatsAvailable =
new Dictionary<Time, ArrayList<String> >();
Time firstBooking = new Time(13,0,0);
Time secondBooking = new Time(15,0,0);
seatsAvailable.put( firstBooking , new ArrayList<String>() );
seatsAvailable.put( secondBooking , new ArrayList<String>() );
Now you can keep track of two completely seperate ArrayLists of seatsAvailable.

Categories