What is wrong with my listener? - java

I have created the interface gui and added the buttons. But now I am stuck with the "Steady" button. When I click it I want to the circle "light bulb" to change color from yellow to orange.
What am I doing wrong in my code and when I press the "Steady" button nothing is happening?
/**
* Created by Metallion on 30/03/2015.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BelishaBeacon {
public class Drawing extends JPanel {
private int x = 125;
private int y = 80;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(165, 180, 20, 45);
Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(165, 270, 20, 45);
Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(165, 360, 20, 45);
Rectangle box6 = new Rectangle(165, 405, 20, 45);
//drawing the shapes
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
g2.draw(ball);
g2.draw(box1);
g2.draw(box2);
g2.draw(box3);
g2.draw(box4);
g2.draw(box5);
g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.YELLOW);
g2.fill(ball);
}
}
public class changeColors extends JPanel {
private boolean choseColor = false;
private int x = 125;
private int y = 80;
public void changeColor(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.ORANGE);
if (!choseColor) {
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
}
public void changeColor() { choseColor = false; }
}
public BelishaBeacon() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(350, 570);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
final changeColors colorinG = new changeColors();
JButton jbtFlash = new JButton("Flash");
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorinG.changeColor();
colorinG.repaint();
}
});
//Positioning
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new BelishaBeacon();
}
}

You need to add handling logic to your Drawing Swing component, e.g.:
add method to your Drawing to change the color
modify the paintComponent(Graphics) according to the first step
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BelishaBeacon {
public class Drawing extends JPanel {
private int x = 125;
private int y = 80;
private boolean changeColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(165, 180, 20, 45);
Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(165, 270, 20, 45);
Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(165, 360, 20, 45);
Rectangle box6 = new Rectangle(165, 405, 20, 45);
//drawing the shapes
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
g2.draw(ball);
g2.draw(box1);
g2.draw(box2);
g2.draw(box3);
g2.draw(box4);
g2.draw(box5);
g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.YELLOW);
g2.fill(ball);
if (changeColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
changeColors = false;
}
public void changeColors() {
changeColors = true;
repaint();
}
}
public BelishaBeacon() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(350, 570);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
JButton jbtFlash = new JButton("Flash");
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.changeColors();
}
});
//Positioning
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new BelishaBeacon();
}
}

Related

JButton query in Belisha Beacon Program

Basically my Belisha Beacon has to stay Orange when I click on the Steady button but in my Program when I click the Steady Button, the Beacon stays as Light Grey instead. Can someone please identify where I am going wrong please? Thank you much :). Here is my code:
package Homework;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.Timer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BelishaBeacon {
private static Timer timer;
public class Drawing extends JPanel {
private int x = 125;
private int y = 80;
private boolean changeColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle box1 = new Rectangle(165, 180, 20, 45);
Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(165, 270, 20, 45);
Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(165, 360, 20, 45);
Rectangle box6 = new Rectangle(165, 405, 20, 45);
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
g2.draw(ball);
g2.draw(box1);
g2.draw(box2);
g2.draw(box3);
g2.draw(box4);
g2.draw(box5);
g2.draw(box6);
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.ORANGE);
g2.fill(ball);
changeColors = !changeColors;
if (changeColors) {
g2.setColor(Color.lightGray);
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
}
public void changeColors() {
changeColors = true;
repaint();
}
}
public BelishaBeacon() {
JFrame frame = new JFrame();
frame.setSize(350, 570);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
shapes.repaint();
}
});
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Flashing");
if (!timer.isRunning()) {
timer.start();
}
}
});
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new BelishaBeacon();
timer.start();
}
}
Instead of trying to toggle the color in paintComponent(), give Drawing a Color and use it to render the ball:
private Color color = Color.lightGray;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
…
g2.setColor(color);
g2.fill(ball);
…
}
Make changeColors() actually change colors:
public void changeColors() {
if (Color.orange.equals(color)) {
color = Color.lightGray;
} else {
color = Color.orange;
}
repaint();
}
And add a makeSteady() method:
public void makeSteady() {
color = Color.orange;
repaint();
}
Now, your timer's action can just do shapes.changeColors(), your Flash button handler can just do timer.restart() and your Steady button handler can just do this:
timer.stop();
shapes.makeSteady();
Also, don't forget to invokeLater().
try this:
public class BelishaBeacon {
private static Timer timer;
public class Drawing extends JPanel {
private int x = 125;
private int y = 80;
private boolean changeColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle box1 = new Rectangle(165, 180, 20, 45);
Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(165, 270, 20, 45);
Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(165, 360, 20, 45);
Rectangle box6 = new Rectangle(165, 405, 20, 45);
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
g2.draw(ball);
g2.draw(box1);
g2.draw(box2);
g2.draw(box3);
g2.draw(box4);
g2.draw(box5);
g2.draw(box6);
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.ORANGE);
g2.fill(ball);
// changeColors = !changeColors;
if (changeColors) {
g2.setColor(Color.lightGray);
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
}
public void changeColors() {
changeColors = !changeColors;
repaint();
}
public boolean getChangeColors() {
return changeColors;
}
}
public BelishaBeacon() {
JFrame frame = new JFrame();
frame.setSize(350, 570);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//shapes.repaint();
shapes.changeColors();
}
});
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Flashing");
if (!timer.isRunning()) {
timer.start();
}
}
});
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
if(shapes.getChangeColors()) {
shapes.changeColors();
}
}
});
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new BelishaBeacon();
timer.start();
}
}

Graphics2D on JPanel and adding JPanel to JFrame

I am trying to draw on a JPanel and add it to a JFrame in my createAndShowGui method. I have tried a few different things: creating the JPanel in the createAndShowGui method, adding the drawing to the JFrame, etc... The one thing that is common, I don't see any of my graphics!
Note: I am able to get the graphics to display in a JTabbedPane but not on a JPanel, which is what I actually want them to show up on to make the code more object oriented.
Edit:
Here is the working concept self contained example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DrawPanelMain extends JPanel {
/*
* Variables used to set the value of preferred height and width
*/
public static final double version = 0.0;
JPanel switchPanel = new JPanel();
JPanel testPanel = new JPanel();
JPanel btnPanel = new JPanel();
DrawEllipses drawEllipses = new DrawEllipses(POINT_LIST);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initializePointList();
createAndShowGui();
}
});
}
public static java.util.List<Point> POINT_LIST = new ArrayList<>();
/*
* This loop will initialize POINT_LIST with the set of points for drawing the ellipses.
* The for each loop initializes points for the top row and the second for loop draws the
* right triangle.
*/
public static void initializePointList() {
int ellipsePointsYCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620};
int ellipsePointsXCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620, 680};
int xx = 80;
for (int aXt : ellipsePointsXCoordinate) {
POINT_LIST.add(new Point(aXt, xx));
}
for (int i = 0; i < ellipsePointsYCoordinate.length; i++) {
for (int j = i; j < ellipsePointsYCoordinate.length; j++) {
POINT_LIST.add(new Point(ellipsePointsXCoordinate[i], ellipsePointsYCoordinate[j]));
}
}
}
public DrawPanelMain() {
testPanel.setBackground(Color.RED);
switchPanel.add(drawEllipses);
setLayout(new BorderLayout());
add(switchPanel, BorderLayout.CENTER);
add(testPanel, BorderLayout.EAST);
add(btnPanel, BorderLayout.SOUTH);
getPreferredSize();
btnPanel.add(new JButton(new AddSwitchAction("Add Switch Panel")));
}
public static void createAndShowGui() {
JFrame frame = new JFrame("RF Connection Panel " + version);
frame.setLayout(new BorderLayout());
frame.add(new DrawPanelMain());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(false);
//frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
/*
* AddSwitchAction will add a new pane to the tabbedPane when the add switch button is clicked
*/
private class AddSwitchAction extends AbstractAction {
public AddSwitchAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
int index = 0;
DrawEllipses tabComponent = new DrawEllipses(POINT_LIST);
switchPanel.add(tabComponent, index++);
}
}
}
#SuppressWarnings("serial")
class DrawEllipses extends JPanel {
private final int PREF_W = 750; //Window width
private final int PREF_H = 750; //Window height
private static final int OVAL_WIDTH = 30;
private static final Color INACTIVE_COLOR = Color.RED;
private static final Color ACTIVE_COLOR = Color.green;
private java.util.List<Point> points;
private java.util.List<Ellipse2D> ellipses = new ArrayList<>();
private Map<Ellipse2D, Color> ellipseColorMap = new HashMap<>();
/*
* This method is used to populate "ellipses" with the initialized ellipse2D dimensions
*/
public DrawEllipses(java.util.List<Point> points) {
this.points = points;
for (Point p : points) {
int x = p.x - OVAL_WIDTH / 2;
int y = p.y - OVAL_WIDTH / 2;
int w = OVAL_WIDTH;
int h = OVAL_WIDTH;
Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h);
ellipses.add(ellipse);
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
MyMouseAdapter mListener = new MyMouseAdapter();
addMouseListener(mListener);
addMouseMotionListener(mListener);
}
/*
* paintComponent is used to paint the ellipses
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ellipse2D ellipse : ellipses) {
g2.setColor(ellipseColorMap.get(ellipse));
g2.fill(ellipse);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(2));
g2.draw(ellipse);
}
/*
* Set the font characteristics, color, and draw the row labels.
*/
g.setFont(new Font("TimesRoman", Font.BOLD, 18));
g.setColor(Color.BLACK);
//Along the top row
g.drawString("External Port", 10, 50);
g.drawString("1", 135, 50);
g.drawString("2", 195, 50);
g.drawString("3", 255, 50);
g.drawString("4", 315, 50);
g.drawString("5", 375, 50);
g.drawString("6", 435, 50);
g.drawString("7", 495, 50);
g.drawString("8", 555, 50);
g.drawString("9", 615, 50);
g.drawString("10", 672, 50);
//Along the Y-axis
g.drawString("Radio 2", 40, 145);
g.drawString("3", 90, 205);
g.drawString("4", 90, 265);
g.drawString("5", 90, 325);
g.drawString("6", 90, 385);
g.drawString("7", 90, 445);
g.drawString("8", 90, 505);
g.drawString("9", 90, 565);
g.drawString("10", 90, 625);
//Along the X-Axis
g.drawString("1", 135, 670);
g.drawString("2", 195, 670);
g.drawString("3", 255, 670);
g.drawString("4", 315, 670);
g.drawString("5", 375, 670);
g.drawString("6", 435, 670);
g.drawString("7", 495, 670);
g.drawString("8", 555, 670);
g.drawString("9", 615, 670);
//Draws a 3DRect around the top row of ellipse2D objects
g2.setColor(Color.lightGray);
g2.draw3DRect(120, 60, 580, 40, true);
g2.draw3DRect(121, 61, 578, 38, true);
g2.draw3DRect(122, 62, 576, 36, true);
}
/*
* MouseAdapter is extended for mousePressed Event that detects if the x, y coordinates
* of a drawn ellipse are clicked. If the color is INACTIVE it is changed to ACTIVE and
* vice versa.
*/
private class MyMouseAdapter extends MouseAdapter {
#Override
/*
* When mousePressed event occurs, the color is toggled between ACTIVE and INACTIVE
*/
public void mousePressed(MouseEvent e) {
Color c;
for (Ellipse2D ellipse : ellipses) {
if (ellipse.contains(e.getPoint())) {
c = (ellipseColorMap.get(ellipse) == INACTIVE_COLOR) ? ACTIVE_COLOR : INACTIVE_COLOR;
ellipseColorMap.put(ellipse, c);
}
}
repaint();
}
}
/*
* This method will set the dimensions of the JFrame equal to the preferred H x W
*/
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
switchPanel.add(title, tabComponent);
By default a JPanel uses a FlowLayout which respects the preferred size of the component. The preferred size of your component is (0, 0) so there is nothing to paint. Also, you are using the "title" string which is incorrect (and obsolete as has already been mentioned). That string represents a constraint for the layout manager. You can't just make up a String value. In any case FlowLayout does not accept any contraints so you should just be using:
switchPanel.add(tabComponent);
I am trying to draw on a JPanel
When doing custom painting you need to override the getPreferredSize() of the panel so the layout manager can use the information. If you don't override this method then the size is (0, 0) so there is nothing to paint.
Edit:
First some general comments:
Don't hardcode sizes of the panel. Your hardcoded size of (1200 x 750) is too large for my monitor. If you want full screen then use frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
Post code that you are actually testing. As has already been mentioned your posted code doesn't even add the "switchPanel" to the frame.
You haven't updated the code to show how you override the getPreferredSize() method.
Finally, I see in your code that you add the panel dynamically to the visible GUI. In this case the general code should be:
panel.add(....);
panel.revalidate(); // to invoke the layout manager otherwise size is still (0, 0)
panel.repaint();
You are adding DrawEllipses instances to switchPanel using an obsolete method add(String,Component); you should use something like add(component, index). Also, You don't add switchPanel to anything (commented out in DrawPanelMain ctor).

How to make a section of code start first-Java Small error/last little step

So the task I've been set is to make an animation of a lamp. There are buttons added that do different actions such as change colour of the sphere etc.
Code: Sphere Class
public class Sphere extends JPanel {
private boolean flashinglights = false;
private int x = 168;
private int y = 75;
private Color[] colors = new Color[] {Color.ORANGE, Color.LIGHT_GRAY };
private int colorIndex = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Graphics2D g3 = (Graphics2D) g;
if (!flashinglights) {
Rectangle box0 = new Rectangle(x+16, y+50,14, 50);
g3.setColor(Color.black);
g3.draw(box0);
g3.fill(box0);
Rectangle box1 = new Rectangle(x+16, y+90,14, 50);
g3.setColor(Color.white);
g3.draw(box1);
g3.fill(box1);
Rectangle box2 = new Rectangle(x+16, y+130,14, 50);
g3.setColor(Color.black);
g3.draw(box2);
g3.fill(box2);
Rectangle box3 = new Rectangle(x+16, y+170,14, 50);
g3.setColor(Color.white);
g3.draw(box3);
g3.fill(box3);
Rectangle box4 = new Rectangle(x+16, y+210,14, 50);
g3.setColor(Color.black);
g3.draw(box4);
g3.fill(box4);
Rectangle box5 = new Rectangle(x+16, y+250,14, 50);
g3.setColor(Color.white);
g3.draw(box5);
g3.fill(box5);
Rectangle box6 = new Rectangle(x+16, y+290,14, 50);
g3.setColor(Color.black);
g3.draw(box6);
g3.fill(box6);
Rectangle box7 = new Rectangle(x+16, y+330,14, 50);
g3.setColor(Color.white);
g3.draw(box7);
g3.fill(box7);
Rectangle box8 = new Rectangle(x+16, y+370,14, 50);
g3.setColor(Color.black);
g3.draw(box8);
g3.fill(box8);
Rectangle box9 = new Rectangle(x+16, y+410,14, 50);
g3.setColor(Color.white);
g3.draw(box9);
g3.fill(box9);
Rectangle box10 = new Rectangle(x+16, y+450,14, 50);
g3.setColor(Color.black);
g3.draw(box10);
g3.fill(box10);
g2.setColor(Color.ORANGE);
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 50, 50);
g2.draw(ball);
g2.fill(ball);
} else {
if(colorIndex > colors.length - 1)
colorIndex = 0;
Rectangle box0 = new Rectangle(x+16, y+50,14, 50);
g3.setColor(Color.black);
g3.draw(box0);
g3.fill(box0);
Rectangle box1 = new Rectangle(x+16, y+90,14, 50);
g3.setColor(Color.white);
g3.draw(box1);
g3.fill(box1);
Rectangle box2 = new Rectangle(x+16, y+130,14, 50);
g3.setColor(Color.black);
g3.draw(box2);
g3.fill(box2);
Rectangle box3 = new Rectangle(x+16, y+170,14, 50);
g3.setColor(Color.white);
g3.draw(box3);
g3.fill(box3);
Rectangle box4 = new Rectangle(x+16, y+210,14, 50);
g3.setColor(Color.black);
g3.draw(box4);
g3.fill(box4);
Rectangle box5 = new Rectangle(x+16, y+250,14, 50);
g3.setColor(Color.white);
g3.draw(box5);
g3.fill(box5);
Rectangle box6 = new Rectangle(x+16, y+290,14, 50);
g3.setColor(Color.black);
g3.draw(box6);
g3.fill(box6);
Rectangle box7 = new Rectangle(x+16, y+330,14, 50);
g3.setColor(Color.white);
g3.draw(box7);
g3.fill(box7);
Rectangle box8 = new Rectangle(x+16, y+370,14, 50);
g3.setColor(Color.black);
g3.draw(box8);
g3.fill(box8);
Rectangle box9 = new Rectangle(x+16, y+410,14, 50);
g3.setColor(Color.white);
g3.draw(box9);
g3.fill(box9);
Rectangle box10 = new Rectangle(x+16, y+450,14, 50);
g3.setColor(Color.black);
g3.draw(box10);
g3.fill(box10);
g2.setColor(colors[colorIndex++]);
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 50, 50);
g2.draw(ball);
g2.fill(ball);
}
}
public void chooseflashinglights(){
flashinglights = true;
}
public void choosesteady(){
flashinglights = false;
}
public static void main(String[] args) {
JFrame scFrame = new AnimationViewer();
scFrame.setTitle("Belisha Beacon");
scFrame.setSize(400, 500);
scFrame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
scFrame.setVisible(true);
}
}
Code: Animation Viewer CLass
public class AnimationViewer extends JFrame {
JButton jbtFlash = new JButton("Flash");
JButton jbtSteady = new JButton("Steady");
JPanel bPanel = new JPanel();
Sphere sphPanel = new Sphere();
Timer timer;
public AnimationViewer() {
timer = new Timer(500, new TimerListener());
this.add(bPanel, BorderLayout.SOUTH);
bPanel.add(jbtFlash);
bPanel.setLayout(new GridLayout(1, 1));
bPanel.add(jbtSteady);
this.add(sphPanel, BorderLayout.CENTER);
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sphPanel.chooseflashinglights();
timer.start();
}
});
jbtSteady.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sphPanel.choosesteady();
timer.stop();
sphPanel.repaint();
}
});
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
sphPanel.repaint();
}
}
}
The main two buttons do two different things. One makes the sphere stay a solid orange colour (Steady) and the other makes the sphere alternate from Orange to grey. (flashing)
NOW THE PROBLEM:
When you start the program the sphere starts of in Steady mode were the colour is just solid orange.
I want the program to START in flashing mode. So when you click run the sphere should be straight in the flashing stage alternating from orange to grey straight away.
So how can I make it so I can start a piece of code first so it goes straight to the flashing lights mode?
Extract the code used to switch the mode to flashing in a method, to avoid code duplication:
private void flash() {
sphPanel.chooseflashinglights();
timer.start();
}
Call this method from the action listener:
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
flash();
}
});
And also call it in the constructor:
public AnimationViewer() {
// existing code omitted
flash();
}

The Button wont show and The Shape keep Disappearing when create new one

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)

2D Transformation (Translation, Rotation, Scaling) Program In Java

I have a problem with 2D transformation program
I have the source code
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class House extends JPanel {
MyCanvas canvas;
JSlider sliderTransX, sliderTransY, sliderRotateTheta, sliderRotateX,
sliderRotateY, sliderScaleX, sliderScaleY, sliderWidth;
double transX = 0.0;
double transY = 0.0;
double rotateTheta = 0.0;
double rotateX = 150.0;
double rotateY = 150.0;
double scaleX = 1.0;
double scaleY = 1.0;
float width = 1.0f;
public House() {
super(new BorderLayout());
JPanel controlPanel = new JPanel(new GridLayout(3, 3));
add(controlPanel, BorderLayout.NORTH);
controlPanel.add(new JLabel("Translate(dx,dy): "));
sliderTransX = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 300, 150,
100, 50);
sliderTransY = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 300, 150,
100, 50);
// To control rotation
controlPanel.add(new JLabel("Rotate(Theta,ox,oy): "));
sliderRotateTheta = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 360,
0, 90, 45);
JPanel subPanel = new JPanel();
subPanel.setLayout(new GridLayout(1, 2));
sliderRotateX = setSlider(subPanel, JSlider.HORIZONTAL, 0, 300, 150,
150, 50);
sliderRotateY = setSlider(subPanel, JSlider.HORIZONTAL, 0, 300, 150,
150, 50);
controlPanel.add(subPanel);
// To control scaling
controlPanel.add(new JLabel("Scale(sx,sy)x10E-2:"));
sliderScaleX = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 200, 100,
100, 10);
sliderScaleY = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 200, 100,
100, 10);
// To control width of line segments
JLabel label4 = new JLabel("Width Control:", JLabel.RIGHT);
sliderWidth = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);
sliderWidth.setPaintTicks(true);
sliderWidth.setMajorTickSpacing(5);
sliderWidth.setMinorTickSpacing(1);
sliderWidth.setPaintLabels(true);
sliderWidth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
width = sliderWidth.getValue();
canvas.repaint();
}
});
JPanel widthPanel = new JPanel();
widthPanel.setLayout(new GridLayout(1, 2));
widthPanel.add(label4);
widthPanel.add(sliderWidth);
add(widthPanel, BorderLayout.SOUTH);
canvas = new MyCanvas();
add(canvas, "Center");
}
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.setPaintTicks(true);
slider.setMajorTickSpacing(majorTickSpacing);
slider.setMinorTickSpacing(minorTickSpacing);
slider.setPaintLabels(true);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider tempSlider = (JSlider) e.getSource();
if (tempSlider.equals(sliderTransX)) {
transX = sliderTransX.getValue() - 150.0;
canvas.repaint();
} else if (tempSlider.equals(sliderTransY)) {
transY = sliderTransY.getValue() - 150.0;
canvas.repaint();
} else if (tempSlider.equals(sliderRotateTheta)) {
rotateTheta = sliderRotateTheta.getValue() * Math.PI / 180;
canvas.repaint();
} else if (tempSlider.equals(sliderRotateX)) {
rotateX = sliderRotateX.getValue();
canvas.repaint();
} else if (tempSlider.equals(sliderRotateY)) {
rotateY = sliderRotateY.getValue();
canvas.repaint();
} else if (tempSlider.equals(sliderScaleX)) {
if (sliderScaleX.getValue() != 0.0) {
scaleX = sliderScaleX.getValue() / 100.0;
canvas.repaint();
}
} else if (tempSlider.equals(sliderScaleY)) {
if (sliderScaleY.getValue() != 0.0) {
scaleY = sliderScaleY.getValue() / 100.0;
canvas.repaint();
}
}
}
});
panel.add(slider);
return slider;
}
class MyCanvas extends Canvas {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.translate(transX, transY);
g2D.rotate(rotateTheta, rotateX, rotateY);
g2D.scale(scaleX, scaleY);
BasicStroke stroke = new BasicStroke(width);
g2D.setStroke(stroke);
drawHome(g2D);
}
public void drawHome(Graphics2D g2D) {
Line2D line1 = new Line2D.Float(100f, 200f, 200f, 200f);
Line2D line2 = new Line2D.Float(100f, 200f, 100f, 100f);
Line2D line3 = new Line2D.Float(100f, 100f, 200f, 100f);
Line2D line5 = new Line2D.Float(200f, 100f, 200f, 200f);
g2D.draw(line1);
g2D.draw(line2);
g2D.draw(line3);
g2D.draw(line5);
}
}
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);
}
}
Please help me.
Don't mix AWT and Swing components needlessly: extend JPanel and override paintComponent(). A call to super.paintComponent(g) will clean up rendering, and RenderingHints will improve rotated drawing.
class MyCanvas extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2D.translate(transX, transY);
g2D.rotate(rotateTheta, rotateX, rotateY);
g2D.scale(scaleX, scaleY);
BasicStroke stroke = new BasicStroke(width);
g2D.setStroke(stroke);
drawHome(g2D);
}
...
}

Categories