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.
Related
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);
}
}
}
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!
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();
}
});
}
}
Thank you I finally got the button to work properly but now I'm stuck at making the shape I just create to stay on screen. Every time I click to create new shape I select the other shape I just create disappear. I look at custom paint but still confuse
public class ShapeStamps extends JFrame {
Random numGen = new Random();
public int x;
public int y;
private JPanel mousePanel, Bpanel;
private JButton circle, square, rectangle, oval;
private int choice = 0;
public ShapeStamps() {
super("Shape Stamps");
Bpanel = new JPanel();
circle = new JButton("Circle");
square = new JButton("Square");
rectangle = new JButton("Rectangle");
oval = new JButton("Oval");
circle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 1;
}
});
square.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 2;
}
});
rectangle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 3;
}
});
oval.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 4;
}
});
mousePanel = new JPanel();
mousePanel.setBackground(Color.WHITE);
MouseHandler handler = new MouseHandler();
setVisible(true);
addMouseListener(handler);
addMouseMotionListener(handler);
add(mousePanel);
Bpanel.add(circle);
Bpanel.add(square);
Bpanel.add(rectangle);
Bpanel.add(oval);
add(Bpanel, BorderLayout.SOUTH);
setSize(500, 500);
setVisible(true);
}
private class MouseHandler extends MouseAdapter implements
MouseMotionListener {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
}
public void paint(Graphics g) {
super.paintComponents(g);
setBounds(0, 0, 500, 500);
Graphics2D g2d = (Graphics2D) g;
if (choice == 0) {
g2d.setFont(new Font("Serif", Font.BOLD, 32));
g2d.drawString("Shape Stamper!", 150, 220);
g2d.setFont(new Font("Serif", Font.ITALIC, 16));
g2d.drawString("Programmed by: None", 150, 245);
}
if (choice == 1) {
Color randomColor1 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor1);
g2d.drawOval(x - 50, y - 50, 100, 100);
}
if (choice == 2) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.drawRect(x - 50, y - 50, 100, 100);
}
if (choice == 3) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Rectangle2D.Double(x - 75, y - 50, 150, 100));
}
if (choice == 4) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Ellipse2D.Double(x - 50, y - 25, 100, 50));
}
}
}
Everytime the JFrame gets repainted it will go through the drawing process, somif you stamp something on the screen you would have to have a data structure to hold the "objects" that were stamped. This way, each time the drawing process gets called it will repaint the objects on their correct position (and maybe colors with you decide to change this too)
I have a JScrollPane that contains a custom JLabel with an ImageIcon. I want the user to be able to zoom in and out on the image. I'm trying to use the scale() method in the Graphics2D class to do it, but whenever I zoom, the image is being shifted down/up and right/left depending on whether I'm zooming in or out. I don't know why this is happening or how to tell how much I need to translate() the Graphics2D object to counteract this. I really appreciate any help you guys can give me. Here's my code:
class ImageViewer extends JFrame implements ActionListener{
private int WIDTH = 800;
private int HEIGHT = 600;
private JScrollPane scrollPane;
JMenuItem zoomIn, zoomOut;
JPanel panel;
MyLabel label;
private String imageUrl = "picture.jpg";
double scale = 1.0;
public static void main(String[] args) {
ImageViewer viewer = new ImageViewer();
viewer.setVisible(true);
}
private ImageViewer() {
this.setTitle("Image Viewer");
this.setSize(WIDTH, HEIGHT);
this.setBackground(Color.gray);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new BorderLayout());
this.getContentPane().add(panel);
JMenuBar menubar = new JMenuBar();
JMenu zoom = new JMenu("Zoom");
zoomIn = new JMenuItem("Zoom In");
zoom.add(zoomIn);
zoomIn.addActionListener(this);
zoomOut = new JMenuItem("Zoom Out");
zoom.add(zoomOut);
zoomOut.addActionListener(this);
menubar.add(zoom);
this.add(menubar, BorderLayout.NORTH);
Icon image = new ImageIcon(imageUrl);
label = new MyLabel(image);
scrollPane = new JScrollPane();
scrollPane.getViewport().add(label);
panel.add(scrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
Object ob = e.getSource();
if (ob == zoomIn) {
scale += .1;
label.revalidate();
label.repaint();
}
if (ob == zoomOut) {
scale -= .1;
label.revalidate();
label.repaint();
}
}
class MyLabel extends JLabel{
public MyLabel(Icon i){
super(i);
}
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
AffineTransform at = g2.getTransform();
g2.scale(scale, scale);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paintComponent(g2);
g2.setTransform(at);
}
public Dimension getPreferredSize(){
int w = (int)(scale * getIcon().getIconWidth()),
h = (int)(scale * getIcon().getIconHeight());
return new Dimension(w, h);
}
}
}
Before g2.scale(scale, scale); add g2.translate(desiredX, desiredY);