Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

NetBeans Analog clock change hands color

Status
Not open for further replies.

picia2222

Technical User
Jan 8, 2013
5
Hello. I have analog clock app and want to change hands color using setter and getter. I write some code but not work. Can You help me?
My code:

file zegarek.java:
Java:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import static java.lang.Math.*;
import java.util.Calendar;
import javax.swing.*;

class ClockComponent extends JComponent{

        //zmienne prywatne
	private Calendar systemTime = Calendar.getInstance();
	private int centerX = 200 ;
	private int centerY = 200;
        
        private Color tloKolor;
	BufferedImage clockFace ;
	
        //konstruktor bezparametrowy public ClockComponent(){};
        public ClockComponent(){};
	
      public void setKolor (Color R) {tloKolor=R;}
      public Color getKolor () {return tloKolor;}
   
      
        
       
        
        @Override
	public void paint(Graphics g){
                 //rysowanie ogólnego wyglądu zegarka
		Graphics2D graphics = (Graphics2D)g;
                //włączenie antialiasingu aby grafika ładniej wyglądała
		graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

		if (clockFace==null) {
                        //wczytanie obrazka z tarczą
			clockFace = new BufferedImage(400, 400, BufferedImage.BITMASK);
			Graphics2D face = clockFace.createGraphics();
			face.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			drawTiks(face);
                        
                        //szerokość piura  
			BasicStroke width = new BasicStroke(3);
			face.setStroke(width);
			face.setPaint(Color.BLACK);
			//face.drawOval(0, 0, 400, 400);
			drawHands(face, 0, 0, 0, 10);
		}

		graphics.drawImage(clockFace, null, 0, 0);
		drawSecond(graphics);
		drawMinute(graphics);
		drawHour(graphics);
		
	}
        //parametry wskazówki sekund
	private void drawSecond(Graphics2D graphics){
		int seconds = systemTime.get(Calendar.SECOND);//pobieranie sekund z kalendarza
		int secondsAngle = seconds*6;//ustawienie kąta dla wskazówki
		drawHands(graphics, -30, 160, secondsAngle,1);//rysowanie wskazówki
	}
        //parametry wskazówki minut
	private void drawMinute(Graphics2D graphics){
		int minutes = systemTime.get(Calendar.MINUTE);//pobieranie minut z kalendarza
		double minuteAngle = (minutes)*6;//ustawienie kąta dla wskazówki
		drawHands(graphics, 0, 150, minuteAngle,2);//rysowanie wskazówki
	}

        //parametry wskazówki godzin
	private void drawHour(Graphics2D graphics){
		int hours = systemTime.get(Calendar.HOUR); //pobieranie godziny z kalendarza
		double hourAngle = (hours+ (double)(systemTime.get(Calendar.MINUTE))/60)*30; //ustawienie kąta dla wskazówki
		drawHands(graphics, 0, 110, hourAngle,4);//rysowanie wskazówki
	}
        
        //rysowanie wskazówek
	private void drawTiks(Graphics2D graphics){
		int x=0;
		
		while(true){
			int y =180;
			if(x%30==0)y=170;
			drawHands(graphics, y, 180, x,2);
			if (x==360) break;
			x += 6;

		}
	}


	//ustawienia wyglądu wskazówki
	private void drawHands(Graphics2D graphics, int startRadius, int endRadius, double teta,int width){

		double radian = toRadians(teta-90);
		int startX = centerX+ (int)(startRadius*cos(radian));
		int startY = centerY+ (int)(startRadius*sin(radian));
		int endX = centerX+ (int)(endRadius*cos(radian));
		int endY = centerY+ (int)(endRadius*sin(radian));
        

                BasicStroke line = new BasicStroke(width,BasicStroke.JOIN_ROUND,BasicStroke.CAP_ROUND);
		graphics.setStroke(line);
		graphics.setColor(tloKolor);
		graphics.drawLine(startX, startY, endX, endY);
                
	}

	ActionListener update = new ActionListener() {

		public void actionPerformed(ActionEvent e) {
			systemTime.setTimeInMillis(System.currentTimeMillis());
			repaint();
		}
	};


	Timer fireUpdate = new Timer(1000, update);
}

file okno.java:
Java:
import java.awt.Color;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Admin
 */
public class okno extends javax.swing.JFrame {

    /**
     * Creates new form okno
     */
    public okno() {
        initComponents();
        ClockComponent clock = new ClockComponent();
		clock.setSize(600, 600);
		jPanel1.add(clock);
		clock.fireUpdate.start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jColorChooser1 = new javax.swing.JColorChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/clock.png"))); // NOI18N

        jLabel2.setText("Ustaw kolor zegara");

        jButton1.setText("Zmień");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ZmienKolor(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "RED", "GREEN" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(134, 134, 134))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(112, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void ZmienKolor(java.awt.event.ActionEvent evt) {                            
       ClockComponent kolor = new ClockComponent();
       String stringR = jComboBox1.getSelectedItem().toString();
       if (stringR.equals("RED")) {
                Color S = Color.RED;
                kolor.setKolor(S);
                kolor.repaint();
                jButton1.setBackground(S);
                kolor.repaint();
                
                } 
                else if (stringR.equals("GREEN")){
                Color S = Color.GREEN;
                kolor.setKolor(S);
                kolor.repaint();
                jButton1.setBackground(S);
                kolor.repaint();
                }
       
         
       
    }                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see [URL unfurl="true"]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/URL] 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new okno().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JColorChooser jColorChooser1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top