I'm currently having some problems regarding my homework.
Here's the Exercise:
(Plot the sine and cosine functions) Write a program that plots the sine function in red and the cosine function in blue.
hint: The Unicode for Pi is \u03c0. To display -2Pi, use g.drawString("-2\u03c0", x, y). For a trigonometric function like sin(x), x is in radians. Use the following loop to add the points to a polygon p
for (int x = -170; x <= 170; x++) {
p.addPoint(x + 200, 100 - (int)(50 * Math.sin((x / 100.0) * 2 * Math.PI)));
-2Pi is at (100, 100), the center of the axis is at (200, 100), and 2Pi is at (300, 100)
Use the drawPolyline method in the Graphics class to connect the points.
Okay, so the sin function I have is a little different from the one in the exercise but it works so it shouldn't be a problem. The cosine function on the other hand, I'm having trouble finding the code for it so I don't have that in my program.
What I also need to do is place -Pi and Pi on the graph on their respectable places.
So, here's the code.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Exercise13_12 extends JFrame {
public Exercise13_12() {
setLayout(new BorderLayout());
add(new DrawSine(), BorderLayout.CENTER);
}
public static void main(String[] args) {
Exercise13_12 frame = new Exercise13_12();
frame.setSize(400, 300);
frame.setTitle("Exercise13_12");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class DrawSine extends JPanel {
double f(double x) {
return Math.sin(x);
}
double g(double y) {
return Math.cos(y);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(10, 100, 380, 100);
g.drawLine(200, 30, 200, 190);
g.drawLine(380, 100, 370, 90);
g.drawLine(380, 100, 370, 110);
g.drawLine(200, 30, 190, 40);
g.drawLine(200, 30, 210, 40);
g.drawString("X", 360, 80);
g.drawString("Y", 220, 40);
Polygon p = new Polygon();
for (int x = -170; x <= 170; x++) {
p.addPoint(x + 200, 100 - (int) (50 * f((x / 100.0) * 2
* Math.PI)));
}
g.drawPolyline(p.xpoints, p.ypoints, p.npoints);
g.drawString("-2\u03c0", 95, 115);
g.drawString("2\u03c0", 305, 115);
g.drawString("0", 200, 115);
}
}
}
If anyone have the time to help me out I would be very grateful.
Try this:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Exercise13_12 extends JFrame {
public Exercise13_12() {
setLayout(new BorderLayout());
add(new DrawSine(), BorderLayout.CENTER);
}
public static void main(String[] args) {
Exercise13_12 frame = new Exercise13_12();
frame.setSize(400, 300);
frame.setTitle("Exercise13_12");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class DrawSine extends JPanel {
double f(double x) {
return Math.sin(x);
}
double gCos(double y) {
return Math.cos(y);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(10, 100, 380, 100);
g.drawLine(200, 30, 200, 190);
g.drawLine(380, 100, 370, 90);
g.drawLine(380, 100, 370, 110);
g.drawLine(200, 30, 190, 40);
g.drawLine(200, 30, 210, 40);
g.drawString("X", 360, 80);
g.drawString("Y", 220, 40);
Polygon p = new Polygon();
Polygon p2 = new Polygon();
for (int x = -170; x <= 170; x++) {
p.addPoint(x + 200, 100 - (int) (50 * f((x / 100.0) * 2
* Math.PI)));
}
for (int x = -170; x <= 170; x++) {
p2.addPoint(x + 200, 100 - (int) (50 * gCos((x / 100.0) * 2
* Math.PI)));
}
g.setColor(Color.red);
g.drawPolyline(p.xpoints, p.ypoints, p.npoints);
g.drawString("-2\u03c0", 95, 115);
g.drawString("2\u03c0", 305, 115);
g.drawString("0", 200, 115);
g.setColor(Color.blue);
g.drawPolyline(p2.xpoints, p2.ypoints, p2.npoints);
}
}
}
Basically it's the same code all over, but you need a new polygon to draw it. And then I set the color using the setColor() function of the Graphics.
You can add this to your paintComponent method:
//Draw pi and -pi
g.drawString("-\u03c0", 147, 100);
g.drawString("\u03c0", 253, 100);
//Create a new polygon
Polygon p2 = new Polygon();
//Add the points of the cosine
for (int x = -170; x <= 170; x++) {
p2.addPoint(x + 200, 100 - (int) (50 * g((x / 100.0) * 2
* Math.PI)));
}
//Draw the function
g.drawPolyline(p2.xpoints, p2.ypoints, p2.npoints);
With that you can have the results that you need.
Okay so now that the program is complete i ended up with this.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Exercise13_12 extends JFrame {
public Exercise13_12() {
setLayout(new BorderLayout());
add(new DrawSine(), BorderLayout.CENTER);
}
public static void main(String[] args) {
Exercise13_12 frame = new Exercise13_12();
frame.setSize(400, 300);
frame.setTitle("Exercise13_12");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class DrawSine extends JPanel {
double f(double x) {
return Math.sin(x);
}
double gCos(double y) {
return Math.cos(y);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(10, 100, 380, 100);
g.drawLine(200, 30, 200, 190);
g.drawLine(380, 100, 370, 90);
g.drawLine(380, 100, 370, 110);
g.drawLine(200, 30, 190, 40);
g.drawLine(200, 30, 210, 40);
g.drawString("X", 360, 80);
g.drawString("Y", 220, 40);
Polygon p = new Polygon();
Polygon p2 = new Polygon();
for (int x = -170; x <= 170; x++) {
p.addPoint(x + 200, 100 - (int) (50 * f((x / 100.0) * 2
* Math.PI)));
}
for (int x = -170; x <= 170; x++) {
p2.addPoint(x + 200, 100 - (int) (50 * gCos((x / 100.0) * 2
* Math.PI)));
}
g.setColor(Color.red);
g.drawPolyline(p.xpoints, p.ypoints, p.npoints);
g.drawString("-2\u03c0", 95, 115);
g.drawString("-\u03c0", 147, 115);
g.drawString("\u03c0", 253, 115);
g.drawString("2\u03c0", 305, 115);
g.drawString("0", 200, 115);
g.setColor(Color.blue);
g.drawPolyline(p2.xpoints, p2.ypoints, p2.npoints);
}
}
}
For anyone that might have the same problem as me later on.
And thanks guys for helping me out, always grateful.
check it out .....
public class GuiBasicstest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic herei
guiBasics gb = new guiBasics();
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(500,500);
jf.add(gb);
jf.setVisible(true);
}
}
................................................................................
package guibasics;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
*
* #author ALI
*/
public class guiBasics extends JPanel{
//Graphics g = null;
public void paintComponent(Graphics g){
//super.paintComponent(g);
for(double i = 0; i<200;i++){
double y= Math.sin(i);
draw(i,y,g);
}
}
private void draw(double x , double y,Graphics g ){
double x1, y1;
x+=10;
y+=10;
x*=10;
y*=30;
x1=x+1;
y1=y+1;
Double d = new Double(x);
int a = d.intValue();
int b = (new Double(y)).intValue();
int c = (new Double(x1)).intValue();
int e = (new Double(y1)).intValue();
g.drawLine(a, b, c, e);
}
}
Related
I'm working on a school project in Netbeans.
Tried to build a simple GUI panel and frame with some options to draw a few objects. I started to add some new text fields and a button to let the user draw an object with some input like hight, width and quantity.
After this the program would not run anymore, it throws an exception which looks like an Illegal argument of some kind?
This is the error:
Exception in thread "AWT-EventQueue-0"
java.lang.IllegalArgumentException: Invalid size
at javax.swing.GroupLayout.checkResizeType(GroupLayout.java:354)
at javax.swing.GroupLayout.checkSize(GroupLayout.java:339)
at javax.swing.GroupLayout.access$500(GroupLayout.java:208)
at javax.swing.GroupLayout$GapSpring.<init>(GroupLayout.java:3173)
at javax.swing.GroupLayout$Group.addGap(GroupLayout.java:1550)
at
javax.swing.GroupLayout$SequentialGroup.addGap(GroupLayout.java:1855)
at ProjectPanel.initComponents(ProjectPanel.java:322)
at ProjectPanel.<init>(ProjectPanel.java:26)
at ProjectFrame.<init>(ProjectFrame.java:18)
at ProjectFrame$1.run(ProjectFrame.java:78)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
atjava.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD STOPPED (total time: 9 seconds)
I tried to debug and see where this error is created but I can't seem to find a specific line.
I'm sorry to post this complete code but I can't seem to find another option to get this back running..
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ProjectPanel extends javax.swing.JPanel {
private int kind = 0;
private int strandstoel;
private String vliegerKleur = "Groen";
private int aantal, hoogte, breedte;
public ProjectPanel() {
initComponents();
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Strand
Color myBeach = new Color(240, 230, 140);
g.setColor(myBeach);
g.fillRect(0, 600, 1500, 400);
//Sky
Color mySky = new Color(245, 255, 250);
g.setColor(mySky);
g.fillRect(0, 0, 1500, 600);
//SunShine
if (jCheckBoxZon.isSelected()) {
Color sunShine = new Color(255, 215, 0);
g.setColor(sunShine);
g.fillOval(500, 150, 200, 200);
} else {
// REGEN + DONKERE LUCHT
Color darkSky = new Color(128, 128, 128);
g.setColor(darkSky);
g.fillRect(0, 0, 1500, 600);
Color rain = new Color(30, 144, 255);
g.setColor(rain);
g.drawLine(100, 50, 100, 200);
g.drawLine(200, 50, 200, 1);
g.drawLine(300, 50, 300, 100);
g.drawLine(400, 50, 400, 1);
g.drawLine(500, 50, 500, 100);
g.drawLine(600, 50, 600, 1);
g.drawLine(700, 50, 700, 150);
g.drawLine(800, 50, 800, 1);
g.drawLine(850, 50, 850, 200);
g.drawLine(900, 50, 900, 150);
g.drawLine(1000, 50, 1000, 1);
g.drawLine(1100, 50, 1100, 100);
g.drawLine(1150, 50, 1150, 200);
g.drawLine(1200, 50, 1200, 1);
g.drawLine(1300, 50, 1300, 150);
g.drawLine(1400, 50, 1400, 1);
g.drawLine(1500, 50, 1500, 100);
}
//Zee
Color seaShore = new Color(0, 191, 255);
g.setColor(seaShore);
g.fillRect(0, 400, 1500, 200);
//Kite
Color flyKite = new Color(0, 255, 127);
g.setColor(flyKite);
g.fillPolygon(new int[]{100, 300, 350}, new int[]{100, 300, 65},
3);
// Kinderen
int x1 = 125;
int x2 = 150;
int x3 = 130;
int x4 = 200;
int x5 = 95;
int x6 = 175;
int x7 = 205;
int y1 = 40;
int y2 = 150;
int y3 = 50;
int y4 = 200;
int y5 = 250;
int y6 = 95;
int y7 = 75;
int y8 = 205;
int y9 = 225;
for (int i = 0; i < kind; i++) {
g.setColor(Color.black);
g.fillOval( x3,330, 40,40 ); // Hoofd
g.drawLine( x2,370, y2,380 ); // Nek
g.fillRect( x1,380, 50,150 ); // Lichaam
g.drawLine( x2,400, y4,470 ); // R Arm
g.drawLine( x4,430, y5,470 );
g.drawLine( x1,430, y1,490 ); // L Arm
g.drawLine( x1,530, y6,620 ); // L Been
g.drawLine( x5,620, y7,620 );
g.drawLine( x6,530, y8,620 ); // R Been
g.drawLine( x7,620, y9,620 );
x1 = 100 + x1;
x2 = x2 + 100;
x3 = x3 + 100;
x4 = x4 + 100;
x5 = x5 + 100;
x6 = x6 + 100;
x7 = x7 + 100;
y1 = 100 + y1;
y2 = y2 + 100;
y3 = y3 + 100;
y4 = y4 + 100;
y5 = y5 + 100;
y6 = y6 + 100;
y7 = y7 + 100;
y8 = y8 + 100;
}
//afbeelding
int tel;
int xSS = 100;
int ySS = 550;
for (tel = 1; tel <= strandstoel; tel++) {
Graphics2D g2d = (Graphics2D) g;
ImageIcon strandstoel = new
ImageIcon(this.getClass().getResource("/images/beach-chair.png"));
g2d.drawImage(strandstoel.getImage(), xSS, ySS, null);
xSS = xSS + 250;
ySS = ySS + 0;
}
//RookPluim
int teller;
for (teller = 1; teller <= aantal; teller++) {
g.setColor(Color.GRAY);
}
// Versiering Vlieger
if (null != vliegerKleur) {
switch (vliegerKleur) {
case "Rood":
g.setColor(Color.RED);
g.fillOval(120, 100, 10, 10);
g.fillOval(160, 95, 10, 10);
g.fillOval(200, 90, 10, 10);
g.fillOval(240, 85, 10, 10);
g.fillOval(280, 80, 10, 10);
g.fillOval(320, 70, 20, 20);
g.fillOval(320, 120, 10, 10);
g.fillOval(310, 160, 10, 10);
g.fillOval(305, 200, 10, 10);
g.fillOval(299, 240, 10, 10);
g.fillOval(294, 280, 10, 10);
break;
case "Oranje":
g.setColor(Color.ORANGE);
g.fillOval(120, 100, 10, 10);
g.fillOval(160, 95, 10, 10);
g.fillOval(200, 90, 10, 10);
g.fillOval(240, 85, 10, 10);
g.fillOval(280, 80, 10, 10);
g.fillOval(320, 70, 20, 20);
g.fillOval(320, 120, 10, 10);
g.fillOval(310, 160, 10, 10);
g.fillOval(305, 200, 10, 10);
g.fillOval(299, 240, 10, 10);
g.fillOval(294, 280, 10, 10);
break;
case "Blauw": // Was normaal groen vlgs de opdracht,
maar dit was niet zo goed zichtbaar
g.setColor(Color.BLUE);
g.fillOval(120, 100, 10, 10);
g.fillOval(160, 95, 10, 10);
g.fillOval(200, 90, 10, 10);
g.fillOval(240, 85, 10, 10);
g.fillOval(280, 80, 10, 10);
g.fillOval(320, 70, 20, 20);
g.fillOval(320, 120, 10, 10);
g.fillOval(310, 160, 10, 10);
g.fillOval(305, 200, 10, 10);
g.fillOval(299, 240, 10, 10);
g.fillOval(294, 280, 10, 10);
break;
default:
break;
}
}
repaint();
}
private void jCheckBoxZonActionPerformed(java.awt.event.ActionEvent
evt) {
// TODO add your handling code here:
repaint();
}
private void jSliderKinderenMouseReleased(java.awt.event.MouseEvent
evt) {
// TODO add your handling code here:
kind = this.jSliderKinderen.getValue();
repaint();
}
private void
jTextFieldAantalStoelenActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
try{
strandstoel =
Integer.parseInt(this.jTextFieldAantalStoelen.getText());
} catch(Exception e){
JOptionPane.showMessageDialog(null,"Vul een getal in");
}
repaint();
}
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
vliegerKleur = this.jList1.getSelectedValue();
repaint();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
aantal = Integer.parseInt(this.jTextFieldAantal.getText());
breedte = Integer.parseInt(this.jTextFieldBreedte.getText());
hoogte = Integer.parseInt(this.jTextFieldHoogte.getText());
} catch(Exception e){
JOptionPane.showMessageDialog(null,"Vul een aantal + Hoogte en
Breedte in");
}
repaint();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JCheckBox jCheckBoxZon;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JList<String> jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSlider jSliderKinderen;
private javax.swing.JTextField jTextFieldAantal;
private javax.swing.JTextField jTextFieldAantalStoelen;
private javax.swing.JTextField jTextFieldBreedte;
private javax.swing.JTextField jTextFieldHoogte;
// End of variables declaration
}
Also another possible cause for that error, which was the case for mine, is that you may unknowingly have added an element such as a JLabel, JTextField, etc. but it's very very tiny small that you are unable to recognize its presence thus while you compile it has an invalid smaller size.
To solve this, open your navigator and click on each element checking where it on the JFrame so that you can also see that tiny one.
I got it to work like that.
Well, that error is because sometimes when you create jFrame with textBox and Labels or another component and you forgot the identifier for example label
My piechart in java isn't showing, for my class we are to make a piechart using graphics and the values are user-input based. even after trying to input any values, my piechart would not show up at all.
What am i doing wrong?
My code:
package ass15;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.HeadlessException;
import javax.swing.JFrame;
public class PieChart extends JFrame {
private int iNorth, iSouth, iEast, iWest, iMidWest;
public PieChart(int North, int South, int East, int West, int MidWest) throws HeadlessException {
super("Assignment 15");
this.iNorth = North;
this.iSouth = South;
this.iEast = East;
this.iWest = West;
this.iMidWest = MidWest;
}
public void Paint(Graphics g) {
//Integer to percent
double dNorth,dSouth,dEast,dWest,dMidWest, total;
dNorth = 0.00 + iNorth;
dSouth = 0.00 + iSouth;
dEast = 0.00 + iEast;
dWest = 0.00 + iWest;
dMidWest = 0.00 + iMidWest;
total = dNorth + dSouth + dEast + dWest + dMidWest;
//initial arc
int startAngle = 0;
double curValue = 0.00;
startAngle = (int) (curValue * 360/total);
int arcAngle = (int) (dNorth * 360/total);
g.setColor(Color.red);
g.fillArc(50, 50, 100, 100, startAngle, arcAngle);
//new arc
curValue += dNorth;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dSouth * 360/total);
g.setColor(Color.green);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//new arc
curValue += dSouth;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dEast * 360/total);
g.setColor(Color.blue);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//new arc
curValue += dEast;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dWest * 360/total);
g.setColor(Color.magenta);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//new arc
curValue += dWest;
startAngle = (int) (curValue * 360/total);
arcAngle = (int) (dMidWest * 360/total);
g.setColor(Color.yellow);
g.fillArc(50, 50, 50, 50, startAngle, arcAngle);
//background circle
g.setColor( Color.black );
g.drawArc( 50, 50, 50, 50, 0, 360 );
}
}
and my main is:
package ass15;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TestPieChart {
public static void main(String[] args) {
int north,south,east,west,midwest;
String token;
String in = "";
in = JOptionPane.showInputDialog("Input sales for regions");
StringTokenizer stk = new StringTokenizer(in, ",");
token = stk.nextToken().trim();
north = Integer.parseInt(token);
token = stk.nextToken().trim();
south = Integer.parseInt(token);
token = stk.nextToken().trim();
east = Integer.parseInt(token);
token = stk.nextToken().trim();
west = Integer.parseInt(token);
token = stk.nextToken().trim();
midwest = Integer.parseInt(token);
PieChart pi = new PieChart(north,south,east,west,midwest);
pi.setVisible(true);
pi.setSize(500, 500);
}
}
It was a stupid mistake...
ANSWER:
the method
Paint(Graphics g)
should be
paint(Graphics g)
did not realize that until i played with the code.
Ok so i need help changing the hue of this slider. I cant seem to figure it out. Please no #override. I need something that will run on Ready to Program. The hue will change back to normal when the slider is back at 0. I dont need to get too complex. Just a simple Hue slider will be great. Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import javax.swing.event.*;
import java.applet.*;
public class test extends Applet implements ActionListener, ChangeListener
{
//Widgets, Panels
JSlider slider;
Panel flow;
int colorr;
int colorg;
int colorb;
int stars;
//House Coordinates, initialized to 1. (Top Right and No Scaling)
public void init ()
{ //Set Up Input Fields for House Coordinates
resize (380, 240);
setBackground (new Color (102, 179, 255));
slider = new JSlider ();
slider.setValue (0);
slider.setBackground (new Color (102, 179, 255));
slider.setForeground (Color.white);
slider.setMajorTickSpacing (20);
slider.setMinorTickSpacing (5);
slider.setPaintTicks (true);
slider.addChangeListener (this);
//Set up layout, add widgets
setLayout (new BorderLayout ());
flow = new Panel (new FlowLayout ());
flow.add (slider);
add (flow, "South");
}
public void paint (Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground ();
Color color2 = color1.darker ();
int x = getWidth ();
int y = getHeight () - 30;
GradientPaint gp = new GradientPaint (
0, 0, color1,
0, y, color2);
g2d.setPaint (gp);
g2d.fillRect (0, 0, x, y);
stars (10, 10);
}
public void stars (int x, int y)
{
Graphics g = getGraphics ();
//sun
g.setColor (new Color (139, 166, 211));
g.fillOval (-200, 170, 1000, 400);
g.setColor (new Color (206, 75, 239));
g.fillOval (x, y, 10, 10); //First medium star
g.drawLine (x + 5, y, x + 5, 0);
g.drawLine (x, y + 5, 0, y + 5);
g.drawLine (x + 5, y + 10, x + 5, y + 20);
g.drawLine (x + 10, y + 5, x + 20, y + 5);
g.fillOval (x + 80, y + 30, 12, 12); //Middle medium star
g.drawLine (x + 86, y + 30, x + 86, y + 18);
g.drawLine (x + 80, y + 36, x + 68, y + 36);
g.drawLine (x + 92, y + 36, x + 104, y + 36);
g.drawLine (x + 86, y + 42, x + 86, y + 52);
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
int randomx = (int) (Math.random () * 300) + 10;
int randomy = (int) (Math.random () * 150) + 10;
stars = 50; //Change for more stars
int ax[] = new int [stars];
int ay[] = new int [stars];
for (int i = 0 ; i < stars ; i++)
{
g.setColor (new Color (colorr, colorg, colorb));
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
while ((randomx > 88 && randomx < 116) && (randomy < 65 && randomy > 15))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
while ((randomx > 0 && randomx < 25) && (randomy > 5 && randomy < 35))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.drawOval (randomx, randomy, 5, 5);
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.setColor (Color.white);
g.drawLine (320, 0, 315, 40);
g.drawLine (320, 0, 325, 40);
g.drawLine (320, 120, 315, 80);
g.drawLine (320, 120, 325, 80);
g.drawLine (260, 60, 300, 55);
g.drawLine (260, 60, 300, 65);
g.drawLine (380, 60, 340, 55);
g.drawLine (380, 60, 340, 65);
fillGradOval (280, 20, 80, 80, new Color (254, 238, 44), new Color (255, 251, 191), g);
g.setColor (new Color (255, 251, 191));
fillGradOval (300, 40, 40, 40, new Color (255, 251, 191), new Color (254, 238, 44), g);
}
public void fillGradOval (int X, int Y, int H2, int W2, Color c1, Color c2, Graphics g)
{
g.setColor (c1);
g.fillOval (X, Y, W2, H2);
Color Gradient = c1;
float red = (c2.getRed () - c1.getRed ()) / (W2 / 2);
float blue = (c2.getBlue () - c1.getBlue ()) / (W2 / 2);
float green = (c2.getGreen () - c1.getGreen ()) / (W2 / 2);
int scale = 1;
int r = c1.getRed ();
int gr = c1.getGreen ();
int b = c1.getBlue ();
while (W2 > 10)
{
r = (int) (r + red);
gr = (int) (gr + green);
b = (int) (b + blue);
Gradient = new Color (r, gr, b);
g.setColor (Gradient);
W2 = W2 - 2 * scale;
H2 = H2 - 2 * scale;
X = X + scale;
Y = Y + scale;
g.fillOval (X, Y, W2, H2);
}
}
public void actionPerformed (ActionEvent e)
{
}
public void stateChanged (ChangeEvent e)
{
JSlider source = (JSlider) e.getSource ();
if (!source.getValueIsAdjusting ())
{
}
}
}
I wasn't sure what 'color' you were referring to, so I made some guesses. Here is an hybrid application/applet (much easier for development and testing) that links the color of the bottom panel, as well as the bottom color of the gradient paint, to a hue as defined using the slider.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/* <applet code=HueSlider width=380 height=240></applet> */
public class HueSlider extends JApplet
{
public void init() {
add(new HueSliderGui());
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
HueSliderGui hsg = new HueSliderGui();
JOptionPane.showMessageDialog(null, hsg);
}
};
SwingUtilities.invokeLater(r);
}
}
class HueSliderGui extends JPanel implements ChangeListener {
//Widgets, Panels
JSlider slider;
JPanel flow;
int colorr;
int colorg;
int colorb;
Color bg = new Color (102, 179, 255);
int stars;
//House Coordinates, initialized to 1. (Top Right and No Scaling)
Dimension prefSize = new Dimension(380, 240);
HueSliderGui() {
initGui();
}
public void initGui()
{
//Set Up Input Fields for House Coordinates
// an applet size is set in HTML
//resize (380, 240);
setBackground (bg);
slider = new JSlider ();
slider.setValue (0);
slider.setBackground (new Color (102, 179, 255));
slider.setForeground (Color.white);
slider.setMajorTickSpacing (20);
slider.setMinorTickSpacing (5);
slider.setPaintTicks (true);
slider.addChangeListener (this);
//Set up layout, add widgets
setLayout (new BorderLayout ());
flow = new JPanel (new FlowLayout ());
flow.add (slider);
add (flow, "South");
validate();
}
#Override
public Dimension getPreferredSize() {
return prefSize;
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground ();
Color color2 = color1.darker ();
int x = getWidth ();
int y = getHeight () - 30;
GradientPaint gp = new GradientPaint (
0, 0, color1,
0, y, flow.getBackground());
g2d.setPaint (gp);
g2d.fillRect (0, 0, x, y);
stars (10, 10, g2d);
}
public void stars (int x, int y, Graphics g)
{
// Graphics g = getGraphics (); we should never call getGraphics
//sun
g.setColor (new Color (139, 166, 211));
g.fillOval (-200, 170, 1000, 400);
g.setColor (new Color (206, 75, 239));
g.fillOval (x, y, 10, 10); //First medium star
g.drawLine (x + 5, y, x + 5, 0);
g.drawLine (x, y + 5, 0, y + 5);
g.drawLine (x + 5, y + 10, x + 5, y + 20);
g.drawLine (x + 10, y + 5, x + 20, y + 5);
g.fillOval (x + 80, y + 30, 12, 12); //Middle medium star
g.drawLine (x + 86, y + 30, x + 86, y + 18);
g.drawLine (x + 80, y + 36, x + 68, y + 36);
g.drawLine (x + 92, y + 36, x + 104, y + 36);
g.drawLine (x + 86, y + 42, x + 86, y + 52);
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
int randomx = (int) (Math.random () * 300) + 10;
int randomy = (int) (Math.random () * 150) + 10;
stars = 50; //Change for more stars
int ax[] = new int [stars];
int ay[] = new int [stars];
for (int i = 0 ; i < stars ; i++)
{
g.setColor (new Color (colorr, colorg, colorb));
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
while ((randomx > 88 && randomx < 116) && (randomy < 65 && randomy > 15))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
while ((randomx > 0 && randomx < 25) && (randomy > 5 && randomy < 35))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.drawOval (randomx, randomy, 5, 5);
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.setColor (Color.white);
g.drawLine (320, 0, 315, 40);
g.drawLine (320, 0, 325, 40);
g.drawLine (320, 120, 315, 80);
g.drawLine (320, 120, 325, 80);
g.drawLine (260, 60, 300, 55);
g.drawLine (260, 60, 300, 65);
g.drawLine (380, 60, 340, 55);
g.drawLine (380, 60, 340, 65);
fillGradOval (280, 20, 80, 80, new Color (254, 238, 44), new Color (255, 251, 191), g);
g.setColor (new Color (255, 251, 191));
fillGradOval (300, 40, 40, 40, new Color (255, 251, 191), new Color (254, 238, 44), g);
}
public void fillGradOval (int X, int Y, int H2, int W2, Color c1, Color c2, Graphics g)
{
g.setColor (c1);
g.fillOval (X, Y, W2, H2);
Color Gradient = c1;
float red = (c2.getRed () - c1.getRed ()) / (W2 / 2);
float blue = (c2.getBlue () - c1.getBlue ()) / (W2 / 2);
float green = (c2.getGreen () - c1.getGreen ()) / (W2 / 2);
int scale = 1;
int r = c1.getRed ();
int gr = c1.getGreen ();
int b = c1.getBlue ();
while (W2 > 10)
{
r = (int) (r + red);
gr = (int) (gr + green);
b = (int) (b + blue);
Gradient = new Color (r, gr, b);
g.setColor (Gradient);
W2 = W2 - 2 * scale;
H2 = H2 - 2 * scale;
X = X + scale;
Y = Y + scale;
g.fillOval (X, Y, W2, H2);
}
}
public void stateChanged (ChangeEvent e)
{
JSlider source = (JSlider) e.getSource ();
if (!source.getValueIsAdjusting ())
{
int i = source.getValue();
System.out.println(i);
float[] hsb = Color.RGBtoHSB(bg.getRed(),bg.getGreen(),bg.getBlue(),null);
int colorHue = Color.HSBtoRGB((float)i/100f, hsb[1], hsb[2]);
Color c = new Color(colorHue);
flow.setBackground(c);
this.repaint();
}
}
}
I'm tyring to link to circles with drawline , but I have a problem here is my code :
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panneau extends JPanel {
public void paintComponent(Graphics g){
// declaration
String text = "test";
int x = 250, y = 200;
int height = 50, width = 50;
g.setColor(Color.yellow);
g.fillOval(x-height/2, y-width/2,width, height);
g.fillOval((x-height/2)+100, (y-width/2)+50,width, height);
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(text, g).getWidth();
g.setColor(Color.black);
g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent() / 2));
g.drawString(text, (int) (x - textWidth/2)+100,(int) (y + fm.getMaxAscent() / 2)+50);
g.setColor(Color.black);
g.drawLine(x,y,x+100,y+50);
}
}
the problem , the line I drawed start from center of circle , I want to draw Line from circle (like Graph node!) thanks for helping ! :)
Actually, I realized there was a way to 'hack it' by drawing the graphic elements in a different order. This still draws the entire line, but then effectively 'erases the unwanted bits' by ..drawing over the top of them!
import java.awt.*;
import javax.swing.*;
public class Panneau extends JPanel {
public void paintComponent(Graphics g){
// declaration
String text = "test";
int x = 250, y = 200;
int height = 50, width = 50;
g.setColor(Color.black);
g.drawLine(x,y,x+100,y+50);
g.setColor(Color.yellow);
g.fillOval(x-height/2, y-width/2,width, height);
g.fillOval((x-height/2)+100, (y-width/2)+50,width, height);
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(text, g).getWidth();
g.setColor(Color.black);
g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent() / 2));
g.drawString(text, (int) (x - textWidth/2)+100,(int) (y + fm.getMaxAscent() / 2)+50);
}
public Dimension getPreferredSize() {
return new Dimension(400,280);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
Panneau p = new Panneau();
JOptionPane.showMessageDialog(null, p);
}
};
SwingUtilities.invokeLater(r);
}
}
I have a problem where my frame shows up as grey, but then after a few seconds it displays the image as my for loop is finishing. I need to make it so that it displays the image correctly once it opens in order to show the loop. Here is my entire code, sorry about the length:
import java.awt.*;
import javax.swing.*;
public class MainFrame extends JFrame{
public void MainFrame() {
setTitle("Game");
setSize(1300, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBackground(Color.WHITE);
Dice diceObject = new Dice();
add(diceObject);
}
}
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class Dice extends JPanel {
public static int pause(int n)
{
try {
Thread.sleep(n);
} catch(InterruptedException e) {
}
return n;
}
public void Dice() {
setDoubleBuffered(true);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int num = 0;
for (int i = 0; i < 7; i++) {
Random generator= new Random();
int number = generator.nextInt(6)+1;
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRoundRect(550, 150, 200, 200, 50, 50);
System.out.println("Test");
if (number == 1) { //Roll one
num = 1;
g.setColor(new Color (0, 0, 0));
g.fillOval(640, 240, 20, 20);
pause(100);
} if (number == 2) { //Roll two
num = 2;
g.setColor(new Color (0, 0, 0));
g.fillOval(590, 290, 20, 20);
g.fillOval(690, 190, 20, 20);
pause(100);
} if (number == 3) { //Roll three
num = 3;
g.setColor(new Color (0, 0, 0));
g.fillOval(590, 290, 20, 20);
g.fillOval(640, 240, 20, 20);
g.fillOval(690, 190, 20, 20);
pause(100);
} if (number == 4) { //Roll four
num = 4;
g.setColor(new Color (0, 0, 0));
g.fillOval(590, 290, 20, 20);
g.fillOval(590, 190, 20, 20);
g.fillOval(690, 290, 20, 20);
g.fillOval(690, 190, 20, 20);
pause(100);
} if (number == 5) { //Roll five
num = 5;
g.setColor(new Color (0, 0, 0));
g.fillOval(590, 290, 20, 20);
g.fillOval(590, 190, 20, 20);
g.fillOval(640, 240, 20, 20);
g.fillOval(690, 290, 20, 20);
g.fillOval(690, 190, 20, 20);
pause(100);
} if (number == 6) { //Roll six
num = 6;
g.setColor(new Color (0, 0, 0));
g.fillOval(590, 190, 20, 20);
g.fillOval(590, 240, 20, 20);
g.fillOval(590, 290, 20, 20);
g.fillOval(690, 190, 20, 20);
g.fillOval(690, 240, 20, 20);
g.fillOval(690, 290, 20, 20);
pause(100);
}
}
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.drawString("You rolled a " + num, 590, 100);
pause(1000);
}
}
Thanks in advance.
The first problem is the fact that you are setting the frame visible BEFORE you add anything to it...
Instead, try calling setVisible last
public class MainFrame extends JFrame{
public void MainFrame() {
setTitle("Game");
setSize(1300, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.WHITE);
Dice diceObject = new Dice();
add(diceObject);
setVisible(true);
}
}
You should also avoid extending directly from JFrame as you're not adding any new functionality to the class and need to take into consideration Initial Threads and ensure you are starting the main UI within the context of the Event Dispatching Thread.
The rest of your problems relate to your previous question
Updated with working example
Cause I'm lazy, I've utilised the Graphics 2D API to draw the dots. I did this because many of the dots appear in the same locations for many of the numbers...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DiceRoller {
public static void main(String[] args) {
new DiceRoller();
}
public DiceRoller() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Die());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Die extends JPanel {
private int number = 1;
public Die() {
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
number = (int) (Math.round((Math.random() * 5) + 1));
repaint();
}
});
timer.setRepeats(true);
timer.setInitialDelay(0);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(220, 220);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setColor(Color.BLACK);
g2d.drawRoundRect(10, 10, width - 20, height - 20, 50, 50);
List<Shape> dots = new ArrayList<>(6);
if (number == 1 || number == 3 || number == 5) {
int x = (width - 20) / 2;
int y = (height - 20) / 2;
dots.add(new Ellipse2D.Float(x, y, 20, 20));
}
if (number == 2 || number == 3 || number == 4 || number == 5 || number == 6) {
int x = ((width / 2) - 20) / 2;
int y = ((height / 2) - 20) / 2;
dots.add(new Ellipse2D.Float(x, y, 20, 20));
dots.add(new Ellipse2D.Float(x + (width / 2), y + (height / 2), 20, 20));
}
if (number == 4 || number == 5 || number == 6) {
int x = (width / 2) + (((width / 2) - 20) / 2);
int y = ((height / 2) - 20) / 2;
dots.add(new Ellipse2D.Float(x, y, 20, 20));
dots.add(new Ellipse2D.Float(x - (width / 2), y + (height / 2), 20, 20));
}
if (number == 6) {
int x = (((width / 2) - 20) / 2);
int y = (height - 20) / 2;
dots.add(new Ellipse2D.Float(x, y, 20, 20));
dots.add(new Ellipse2D.Float(x + (width / 2), y, 20, 20));
}
for (Shape dot : dots) {
g2d.fill(dot);
}
g2d.dispose();
}
}
}