Trying to understand how Timer object works - JAVA SWING - java

I declare a Timer object at the start of my code, initialize it when a JButton is clicked but i can't stop it no matter what i do.
In my code i'm trying to stop the timer when the button print is clicked but it doesn't work.
Here's my Window.java class :
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
ip.addActionListener(lForButton);
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
south = new JPanel();
legend = new JLabel("Legends are here");
south.add(legend);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
container.add(south, BorderLayout.SOUTH);
this.setContentPane(container);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==start)
{
time=Double.parseDouble(timeStep.getText());
System.out.println(time);
chrono = new Timer((int)(1000*time),pan);
chrono.start();
}
if(e.getSource()==ip)
{
JPanel options = new JPanel();
JLabel address = new JLabel("IP Address:");
JTextField address_t = new JTextField(15);
JLabel port = new JLabel("Port:");
JTextField port_t = new JTextField(5);
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
System.out.println(address_t.getText());
System.out.println(port_t.getText());
}
}
if(e.getSource()==print)
{
chrono.stop();
}
}
}
}
And here's my Panel.java class:
public class Panel extends JPanel implements ActionListener {
int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,150,0);
Color blue = new Color (0,0,150);
Color yellow = new Color (150,150,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;
public Panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.8f));
g2.drawLine(20, 20, 20, this.getHeight()-50);
g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
g2.drawLine(20, 20, 15, 35);
g2.drawLine(20, 20, 25, 35);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
if(!randL.isEmpty()){
g2.setColor(green);
g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);
g2.setColor(blue);
g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);
g2.setColor(yellow);
g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);
}
for(i = 0; i<tL.size(); i++){
int temp = randL.get(i);
int t = tL.get(i);
g2.setColor(red);
g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
// Ellipse2D circle = new Ellipse2D.Double();
//circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);
}
for(j=0;j<5;j++)
{
inc=inc+40;
g2.setColor(new Color(0,0,0));
g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
}
inc=0;
}
#Override
public void actionPerformed(ActionEvent e) {
rand = (int)(50+((Math.random() * (80))));
lastT += 60;
randL.add(rand);
tL.add(lastT);
Object obj = Collections.max(randL);
max = (int) obj;
Object obj2 = Collections.min(randL);
min = (int) obj2;
if(!randL.isEmpty()) {
degr = randL.get(k);
total += degr;
moyenne=total/randL.size();
//System.out.println(moyenne);
}
k++;
if(randL.size()>=15)
{
randL.removeAll(randL);
tL.removeAll(tL);
//System.out.println(randL);
lastT = 0;
k=0;
degr=0;
total=0;
moyenne=0;
}
repaint();
}
}
Sorry this work is really messy, but if you succeed in finding the solution i'll thank you ! :D
Cheers!

Related

GUI is showing up blank. No Errors during compiling

I tried to run my code and it went through without any issues, but the GUI is showing a blank when I run it. This is the main class for my project, I have several other subclasses. I've looked over it several times to figure out what's wrong and I can't seem to. Did I use setVisible incorrectly? The project 3 class should generate a GUI which allows the user to input the type of shape they want, the color of the shape, and the fill type of the shape.
public class Project3 extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel shapeType, fillType, color, Width, Height, xCoordinate, yCoordinate;
JTextField xCoor, yCoor, jWidth, jHeight;
JPanel left, right, down;
String shapetoDraw, shapeColor, filltype;
Rectangular rect;
Oval ov;
Drawing drawing= new Drawing();
Project3(){
setTitle("Geometric Drawing");
setLayout(null);
setSize(600,500);
left = new JPanel(new GridLayout(2,2,10,10));
right = new JPanel(new GridLayout(0, 2));
right.setBorder(BorderFactory.createTitledBorder("Shape Drawing"));
down = new JPanel(new GridLayout(2,2,10,10));
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
shapeType = new JLabel("Shape Type");
fillType = new JLabel("Fill Type");
color = new JLabel("Color");
Width = new JLabel("Width");
Height = new JLabel("Height");
xCoordinate = new JLabel("x coordinate");
yCoordinate = new JLabel("y coordinate");
xCoor = new JTextField(10);
yCoor = new JTextField(10);
jWidth = new JTextField(10);
jHeight = new JTextField(10);
left.add(shapeType);
String[] shape = {"Rectangle","Oval"};
JComboBox<String> shapeCombo = new JComboBox<String>(shape);
left.add(color);
String[] colors = {"Black", "Red", "Orange","Yellow","Green","Blue","Magenta"};
JComboBox<String> colorCombo = new JComboBox<String>(colors);
left.add(fillType);
String[] fill = {"Hollow", "Solid"};
JComboBox<String> filltypeCombo = new JComboBox<String>(fill);
left.add(Width);
left.add(jWidth);
left.add(Height);
left.add(jHeight);
left.add(xCoordinate);
left.add(xCoor);
left.add(yCoordinate);
left.add(yCoor);
JButton drawButton = new JButton("Draw");
drawButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapetoDraw=shapeCombo.getSelectedItem().toString();
shapeColor=colorCombo.getSelectedItem().toString();
filltype=filltypeCombo.getSelectedItem().toString();
drawing.drawShape(shapetoDraw, shapeColor, filltype);
}});
down.add(drawButton);
}
public static void main(String[] args) {
Project3 mainFrame = new Project3();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public void paint(Graphics g) {
super.paintComponents(g);
//g.setFont(new Font("Times", Font.BOLD, 12));
//g.drawString(Integer.toString(Shape.getNoOfShapes()),10, 30);
//rect.draw(g);
}}

Paint a parabola using JTextField values in Java

The program consists of drawing a parabola using the values from the A, B and C jtextfields every time the button is pressed:
It also has to be on two separate classes, the View which displays the menu and the Controller which takes the inputs from the first class and paints the parabola.
My actual code:
public static void main(String[] args) {
JFrame frame = new JFrame("Parabola");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
textA.getText();
textB.getText();
textC.getText();
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
double a=2, b=1, c=0;
public void section (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public void graphic(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
public void paint (Graphics g){
section(g);
graphic(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
I`ve managed to do it in one class without the textfields working and have no idea how to separate the graphic into another class so it can do the operations and send them back to the view class again.
Solved it:
Class View
public class View extends JFrame {
public View() {
JFrame frame = new JFrame("Equation");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Controller.a = Double.parseDouble(textA.getText());
Controller.b = Double.parseDouble(textB.getText());
Controller.c = Double.parseDouble(textC.getText());
repaint();
frame.pack();
frame.setSize(420,490);
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
public void paint(Graphics g){
super.paint(g);
Controller.grid(g);
Controller.Graphic1(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
View frame = new View();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Class Controller
public class Controller {
static double a=2, b=1, c=0;
public static void grid (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public static void Graphic1(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
}

How to make this text area show which toggle buttons are selected?

Please can someone help me, I'm trying to make a seat reservation part for my cinema ticket system assignment ... so the problem is i want the text of the button to show in the text area when selected and not show only the specific text when deselected .. but when i deselect a button the whole text area is cleared.
For e.g. when I select C1, C2, C3 - it shows in the text area correctly, but if I want to deselect C3, the text area must now show only C1 & C2. Instead, it clears the whole text area!
Can anyone spot the problem in the logic?
import java.awt.*;
import static java.awt.Color.blue;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class Cw_Test2 extends JFrame {
JButton btn_payment,btn_reset;
JButton buttons;
JTextField t1,t2;
public static void main(String[] args) {
// TODO code application logic here
new Cw_Test2();
}
public Cw_Test2()
{
Frame();
}
public void Frame()
{
this.setSize(1200,700); //width, height
this.setTitle("Seat Booking");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 6);
Font newFont = myFont.deriveFont(20F);
t1=new JTextField();
t1.setBounds(15, 240, 240,30);
JPanel thePanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
thePanel.setLayout(null);
JPanel ourPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border ourBorder = BorderFactory.createLineBorder(blue , 2);
ourPanel.setBorder(ourBorder);
ourPanel.setLayout(null);
ourPanel.setBounds(50,90, 1100,420);
JPanel newPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border newBorder = BorderFactory.createLineBorder(blue , 1);
newPanel.setBorder(newBorder);
newPanel.setLayout(null);
newPanel.setBounds(790,50, 270,340);
JLabel label1 = new JLabel( new ColorIcon(Color.GRAY, 400, 100) );
label1.setText( "SCREEN" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
label1.setBounds(130,50, 400,30);
JLabel label2 = new JLabel(" CINEMA TICKET MACHINE ");
label2.setBounds(250,50,400,30);
label2.setFont(newFont);
JLabel label3 = new JLabel("Please Select Your Seat");
label3.setBounds(270,10,500,30);
label3.setFont(newFont);
JLabel label4 = new JLabel("Selected Seats:");
label4.setBounds(20,10,200,30);
label4.setFont(newFont);
btn_payment=new JButton("PROCEED TO PAY");
btn_payment.setBounds(35,290,200,30);
JLabel label6 = new JLabel("Center Stall");
label6.setBounds(285,172,200,30);
JPanel seatPane, seatPane1, seatPane2, seatPane3, seatPane4, seatPane5;
JToggleButton[] seat2 = new JToggleButton[8];
JTextArea chosen = new JTextArea();
chosen.setEditable(false);
chosen.setLineWrap(true);
chosen.setBounds(20, 60, 200, 100);
// Center Seats
seatPane1 = new JPanel();
seatPane1.setBounds(200,200,250,65);
seatPane1.setLayout(new FlowLayout());
for(int x=0; x<8; x++){
seat2[x] = new JToggleButton("C"+(x+1));
seatPane1.add(seat2[x]);
seat2[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
AbstractButton abstractButton = (AbstractButton) ev.getSource();
boolean selected = abstractButton.getModel().isSelected();
for(int x=0; x<8; x++){
if(seat2[x]==ev.getSource()){
if(selected){
chosen.append(seat2[x].getText()+",");
}else{
chosen.setText(seat2[x].getText().replace(seat2[x].getText(),""));
}
}
}
}
});
}
newPanel.add(chosen);
ourPanel.add(seatPane1);
ourPanel.add(label6);
thePanel.add(label2);
ourPanel.add(label3);
ourPanel.add(label1);
newPanel.add(btn_payment);
newPanel.add(label4);
ourPanel.add(newPanel);
thePanel.add(ourPanel);
add(thePanel);
setResizable(false);
this.setVisible(true);
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
When any seat is selected or deselected, this code iterates an array of seats (in the method showSelectedSeats()) and updates the text area to show the seats that are selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CinemaTicketMachine {
private JComponent ui = null;
private JToggleButton[] seats = new JToggleButton[80];
private JTextArea selectedSeats = new JTextArea(3, 40);
CinemaTicketMachine() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
selectedSeats.setLineWrap(true);
selectedSeats.setWrapStyleWord(true);
selectedSeats.setEditable(false);
ui.add(new JScrollPane(selectedSeats), BorderLayout.PAGE_END);
JPanel cinemaFloor = new JPanel(new BorderLayout(40, 0));
cinemaFloor.setBorder(new TitledBorder("Available Seats"));
ui.add(cinemaFloor, BorderLayout.CENTER);
JPanel leftStall = new JPanel(new GridLayout(0, 2, 2, 2));
JPanel centerStall = new JPanel(new GridLayout(0, 4, 2, 2));
JPanel rightStall = new JPanel(new GridLayout(0, 2, 2, 2));
cinemaFloor.add(leftStall, BorderLayout.WEST);
cinemaFloor.add(centerStall, BorderLayout.CENTER);
cinemaFloor.add(rightStall, BorderLayout.EAST);
ActionListener seatSelectionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showSelectedSeats();
}
};
for (int ii=0; ii <seats.length; ii++) {
JToggleButton tb = new JToggleButton("S-" + (ii+1));
tb.addActionListener(seatSelectionListener);
seats[ii] = tb;
int colIndex = ii%8;
if (colIndex<2) {
leftStall.add(tb);
} else if (colIndex<6) {
centerStall.add(tb);
} else {
rightStall.add(tb);
}
}
}
private void showSelectedSeats() {
StringBuilder sb = new StringBuilder();
for (int ii=0; ii<seats.length; ii++) {
JToggleButton tb = seats[ii];
if (tb.isSelected()) {
sb.append(tb.getText());
sb.append(", ");
}
}
String s = sb.toString();
if (s.length()>0) {
s = s.substring(0, s.length()-2);
}
selectedSeats.setText(s);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
CinemaTicketMachine o = new CinemaTicketMachine();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Getting text input without swing in Java

Hi I'm making a game in Java that randomly generates 100 numbers, and then
ask the user to memorize as many as then can and then try to recall as many as they can. My game uses a JPanel and a Graphics g object to do all the drawing. How do I "draw" a JTextfield or get one to work on a jpanel?
Add a ActionListener to JTextField and then add that JTextField to JPanel. Now add this JPanel to JFrame using this.add(jpnel, BorderLayout.SOUTH);
Create a new JPanel class Board where you draw things. Add that JPanel to JFrame as, this.add(new Board(), BorderLayout.CENTER);.
Here I coded one example for you. Now you should have an idea how to do that...
Board class
public class Board extends JPanel {
int[] numbers = {3, 25, 5, 6, 60, 100};
int index = 0;
static String num;
boolean once = true;
FontMetrics fm;
Board() {
setPreferredSize(new Dimension(400, 200));
setBackground(Color.decode("#ffde00"));
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
if (index < 6) {
num = numbers[index] + "";
} else {
num = "Game Ended.";
Window.ans.setEditable(false);
}
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Arial", Font.PLAIN, 50));
if(once){
fm = g2.getFontMetrics();
once = false;
}
int x = ((getWidth() - fm.stringWidth(num)) / 2);
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g2.drawString(num + "", x, y);
index++;
}
}
Window class
public class Window extends JFrame {
JPanel p = new JPanel();
JLabel lbl = new JLabel("Enter the number if you have seen it before, Else empty.");
JLabel res = new JLabel("....");
static JTextField ans = new JTextField(10);
Board board = new Board();
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(board, BorderLayout.CENTER);
p.setLayout(new BorderLayout(8, 8));
p.add(lbl, BorderLayout.WEST);
ans.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (ans.getText().equals(Board.num)) {
res.setText("Good");
} else {
res.setText("Bad");
}
ans.setText("");
board.repaint();
}
});
p.add(ans, BorderLayout.CENTER);
p.add(res, BorderLayout.EAST);
p.setBorder(new EmptyBorder(10, 10, 10, 10));
this.add(p, BorderLayout.SOUTH);
setResizable(false);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
}

# java how to insert images in a canvas

i am developing a car simulation in java. my coding is as below. I want to put a panel and in it to be the line rotating together with a speedometer image of 180 degrees. My question is how do i do this?
public class House extends JPanel implements ActionListener
{
MyCanvas canvas;
JButton mybutton,mybutton1,mybutton2,mybutton3,mybutton4,mybutton5;
JTextField text1,text2,text3;
JSlider sliderTransX, sliderTransY, sliderRotateTheta, sliderRotateX,
sliderRotateY, sliderScaleX, sliderScaleY, sliderWidth;
`enter code here`int k = 0;
double transX = 0.0;
double transY = 0.0;
double rotateTheta = 0.0;
double rotateX = 345.0;
double rotateY = 250.0;
double scaleX = 1.0;
double scaleY = 1.0;
float width = 1.0f;
Cargame game = new Cargame();
public House()
{
super(new BorderLayout());
JPanel controlPanel = new JPanel(new GridLayout(3, 3));
add(controlPanel, BorderLayout.NORTH);
sliderRotateTheta = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 180,
0, 90, 45);
mybutton = new JButton("Accelerate");
mybutton.addActionListener(this);
mybutton1 = new JButton("ShiftUp");
mybutton1.addActionListener(this);
mybutton2 = new JButton("ShiftDown");
mybutton2.addActionListener(this);
mybutton3 = new JButton("Deaccelerate");
mybutton3.addActionListener(this);
mybutton4 = new JButton("Start Engine");
mybutton4.addActionListener(this);
mybutton5 = new JButton("Stop Engine");
mybutton5.addActionListener(this);
text1=new JTextField(5);
text2=new JTextField(5);
text3=new JTextField(5);
sliderWidth = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);
sliderWidth.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e) {
width = sliderWidth.getValue();
canvas.repaint();
}
});
JPanel widthPanel = new JPanel();
widthPanel.setLayout(new GridLayout(3, 3));
widthPanel.add(mybutton);
widthPanel.add(mybutton1);
widthPanel.add(mybutton2);
widthPanel.add(mybutton3);
widthPanel.add(mybutton4);
widthPanel.add(mybutton5);
widthPanel.add(text1);
widthPanel.add(text2);
widthPanel.add(text3);
add(widthPanel, BorderLayout.SOUTH);
canvas = new MyCanvas();
add(canvas, "Center");
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == mybutton)
{
game.Accelerate();
}
if (e.getSource() == mybutton1)
{
game.ShiftUp();
}
if (e.getSource() == mybutton2)
{
game.ShiftDown();
}
if (e.getSource() == mybutton3)
{
game.Deaccelerate();
}
JSlider tempSlider=new JSlider();
rotateTheta= ((double)game.getLevel()) * Math.PI / 180;
text1.setText(String.valueOf(game.getLevel()));
text2.setText(String.valueOf(game.getGear()));
text3.setText(String.valueOf(game.Speedometer()));
canvas.repaint();
}
public JSlider setSlider(JPanel panel, int orientation, int minimumValue,
int maximumValue, int initValue, int majorTickSpacing,
int minorTickSpacing) {
JSlider slider = new JSlider(orientation, minimumValue, maximumValue,
initValue);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider tempSlider = (JSlider) e.getSource();
sliderRotateTheta.setValue(k);
if(tempSlider.equals(sliderRotateTheta))
{
rotateTheta = sliderRotateTheta.getValue() * Math.PI / 180;
canvas.repaint();
}}
});
slider.setVisible(false);
panel.add(slider);
return slider;
}
class MyCanvas extends Canvas {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.rotate(rotateTheta, rotateX, rotateY);
BasicStroke stroke = new BasicStroke(width);
g2D.setStroke(stroke);
drawHome(g2D);
}
public void drawHome(Graphics2D g2D) {
Line2D line7 = new Line2D.Float(205f, 250f, 345f, 250f);
g2D.draw(line7);
}
}
public static void main(String[] a) {
JFrame f = new JFrame();
f.getContentPane().add(new House());
f.setDefaultCloseOperation(1);
f.setSize(700, 550);
f.setVisible(true);
}
}
Using JFreeChart, you can control a DialPlot using a JSlider or JSpinner. This related example uses a JSlider to control a line chart, and more examples may be found in the JWS demo.
Addendum: As shown here, you can use the parametric form of the equation of a circle to calculate the free endpoint of your indicator line.

Categories