kalender machen

Status
Nicht offen für weitere Antworten.

SebiB90

Top Contributor
ich wollt jetzt mal ein kalender machen in dem man termine eintragen kann.
nur ich hab kein plan wie man sowas machen kann.
könnt ihr mir paar tips geben und/oder links zu tuts?

Danke
 
fehlt dir das konzept oder die programmierkenntnis?

wenn dir das konzept fehlt, kannste dir den kalender von outlook anschauen. bei letzterem hilft nur lernen, lernen, lernen 😉 😀
 
schau dir mal das Dashboard2 von Roar an, das hat einen Kalender drinnen...

anfangen wie man immer anfangen sollte - welche Klassen werden benötigt, welche Klasse ist für was zuständig... vll an einer kleinen first-try GUI rumprobieren usw
 
Hier einmal als Anregung für eine GUI einige Zeilen Code:

Code:
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;

import javax.swing.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.plaf.ComboBoxUI;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.EmptyBorder;

import com.sun.java.swing.plaf.motif.MotifComboBoxUI;
import com.sun.java.swing.plaf.windows.WindowsComboBoxUI;

public class DateExampleJCombo extends JComboBox {

	protected SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MMM.yyyy");

	public void setDateFormat(SimpleDateFormat dateFormat) {
		this.dateFormat = dateFormat;
	}

	public void setSelectedItem(Object item) {
		removeAllItems(); // unterdrückt Popup, wenn sichtbar
		addItem(item);
		super.setSelectedItem(item);
	}

	public void updateUI() {
		ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
		if (cui instanceof MetalComboBoxUI) {
			cui = new MetalDateComboBoxUI();
		} else if (cui instanceof MotifComboBoxUI) {
			cui = new MotifDateComboBoxUI();
		} else if (cui instanceof WindowsComboBoxUI) {
			cui = new WindowsDateComboBoxUI();
		}
		setUI(cui);
	}

	// Innere Klassen nur dazu, um die DateComboBox-Komponente 
	// in einer Datei zu halten

	// UI-Klassen

	class MetalDateComboBoxUI extends MetalComboBoxUI {
		protected ComboPopup createPopup() {
			return new DatePopup(comboBox);
		}
	}

	class WindowsDateComboBoxUI extends WindowsComboBoxUI {
		protected ComboPopup createPopup() {
			return new DatePopup(comboBox);
		}
	}

	class MotifDateComboBoxUI extends MotifComboBoxUI {
		protected ComboPopup createPopup() {
			return new DatePopup(comboBox);
		}
	}

	class DatePopup implements ComboPopup, MouseMotionListener, MouseListener,
			KeyListener, PopupMenuListener {

		protected JComboBox comboBox;

		protected Calendar calendar;

		protected JPopupMenu popup;

		protected JLabel monthLabel;

		protected JPanel days = null;

		protected SimpleDateFormat monthFormat = new SimpleDateFormat(
				"dd MMM yyyy");

		protected Color selectedBackground;

		protected Color selectedForeground;

		protected Color background;

		protected Color foreground;

		public DatePopup(JComboBox comboBox) {
			this.comboBox = comboBox;
			calendar = Calendar.getInstance();
			// Prüfe L&F
			background = UIManager.getColor("ComboBox.background");
			foreground = UIManager.getColor("ComboBox.foreground");
			selectedBackground = UIManager
					.getColor("ComboBox.selectionBackground");
			selectedForeground = UIManager
					.getColor("ComboBox.selectionForeground");

			initializePopup();
		}

		// Combo-Popup Methode implementieren
		public void show() {
			try {
				// wenn setSelectedItem() mit einem gültigen Datum aufgerufen -> Kalender einstellen
				calendar.setTime(dateFormat.parse(comboBox.getSelectedItem()
						.toString()));
			} catch (Exception e) {
			}
			updatePopup();
			popup.show(comboBox, 0, comboBox.getHeight());
		}

		public void hide() {
			popup.setVisible(false);
		}

		protected JList list = new JList();

		public JList getList() {
			return list;
		}

		public MouseListener getMouseListener() {
			return this;
		}

		public MouseMotionListener getMouseMotionListener() {
			return this;
		}

		public KeyListener getKeyListener() {
			return this;
		}

		public boolean isVisible() {
			return popup.isVisible();
		}

		public void uninstallingUI() {
			popup.removePopupMenuListener(this);
		}

		public void mousePressed(MouseEvent e) {
		}

		public void mouseReleased(MouseEvent e) {
		}

		// ... was anderes
		public void mouseClicked(MouseEvent e) {
			if (!SwingUtilities.isLeftMouseButton(e))
				return;
			if (!comboBox.isEnabled())
				return;
			if (comboBox.isEditable()) {
				comboBox.getEditor().getEditorComponent().requestFocus();
			} else {
				comboBox.requestFocus();
			}
			togglePopup();
		}

		protected boolean mouseInside = false;

		public void mouseEntered(MouseEvent e) {
			mouseInside = true;
		}

		public void mouseExited(MouseEvent e) {
			mouseInside = false;
		}

		// MouseMotionListener
		public void mouseDragged(MouseEvent e) {
		}

		public void mouseMoved(MouseEvent e) {
		}

		// KeyListener
		public void keyPressed(KeyEvent e) {
		}

		public void keyTyped(KeyEvent e) {
		}

		public void keyReleased(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_SPACE
					|| e.getKeyCode() == KeyEvent.VK_ENTER) {
				togglePopup();
			}
		}

		/**
		 * Variables hideNext and mouseInside are used to 
		 * hide the popupMenu by clicking the mouse in the JComboBox
		 */
		public void popupMenuCanceled(PopupMenuEvent e) {
		}

		protected boolean hideNext = false;

		public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
			hideNext = mouseInside;
		}

		public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
		}

		protected void togglePopup() {
			if (isVisible() || hideNext) {
				hide();
			} else {
				show();
			}
			hideNext = false;
		}

		// Bemerkung: JButton nicht benutzt, da ....
		protected JLabel createUpdateButton(final int field, final int amount) {
			final JLabel label = new JLabel();
			final Border selectedBorder = new EtchedBorder();
			final Border unselectedBorder = new EmptyBorder(selectedBorder
					.getBorderInsets(new JLabel()));
			label.setBorder(unselectedBorder);
			label.setForeground(foreground);
			label.addMouseListener(new MouseAdapter() {
				public void mouseReleased(MouseEvent e) {
					calendar.add(field, amount);
					updatePopup();
				}

				public void mouseEntered(MouseEvent e) {
					label.setBorder(selectedBorder);
				}

				public void mouseExited(MouseEvent e) {
					label.setBorder(unselectedBorder);
				}
			});
			return label;
		}

		protected void initializePopup() {
			JPanel header = new JPanel();
			header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
			header.setBackground(background);
			header.setOpaque(true);

			JLabel label;
			label = createUpdateButton(Calendar.YEAR, -1);
			label.setText("<<");
			label.setToolTipText("Vorheriges Jahr");

			header.add(Box.createHorizontalStrut(12));
			header.add(label);
			header.add(Box.createHorizontalStrut(12));

			label = createUpdateButton(Calendar.MONTH, -1);
			label.setText("<");
			label.setToolTipText("Vorheriger Monat");
			header.add(label);

			monthLabel = new JLabel("", JLabel.CENTER);
			monthLabel.setForeground(foreground);
			header.add(Box.createHorizontalGlue());
			header.add(monthLabel);
			header.add(Box.createHorizontalGlue());

			label = createUpdateButton(Calendar.MONTH, 1);
			label.setText(">");
			label.setToolTipText("Nächster Monat");
			header.add(label);

			label = createUpdateButton(Calendar.YEAR, 1);
			label.setText(">>");
			label.setToolTipText("Nächstes Jahr");

			header.add(Box.createHorizontalStrut(12));
			header.add(label);
			header.add(Box.createHorizontalStrut(12));

			popup = new JPopupMenu();
			popup.setBorder(BorderFactory.createLineBorder(Color.black));
			popup.setLayout(new BorderLayout());
			popup.setBackground(background);
			popup.addPopupMenuListener(this);
			popup.add(BorderLayout.NORTH, header);
		}

		protected void updatePopup() {
			monthLabel.setText(monthFormat.format(calendar.getTime()));
			if (days != null) {
				popup.remove(days);
			}
			days = new JPanel(new GridLayout(0, 7));
			days.setBackground(background);
			days.setOpaque(true);

			Calendar setupCalendar = (Calendar) calendar.clone();
			setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar
					.getFirstDayOfWeek());
			for (int i = 0; i < 7; i++) {
				int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
				JLabel label = new JLabel();
				label.setHorizontalAlignment(JLabel.CENTER);
				label.setForeground(foreground);
				if (dayInt == Calendar.SUNDAY) {
					label.setText("Son");
				} else if (dayInt == Calendar.MONDAY) {
					label.setText("Mon");
				} else if (dayInt == Calendar.TUESDAY) {
					label.setText("Die");
				} else if (dayInt == Calendar.WEDNESDAY) {
					label.setText("Mit");
				} else if (dayInt == Calendar.THURSDAY) {
					label.setText("Don");
				} else if (dayInt == Calendar.FRIDAY) {
					label.setText("Fre");
				} else if (dayInt == Calendar.SATURDAY) {
					label.setText("Sam");
				}
				days.add(label);
				setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
			}

			setupCalendar = (Calendar) calendar.clone();
			setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
			int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
			for (int i = 0; i < (first - 1); i++) {
				days.add(new JLabel(""));
			}
			for (int i = 1; i <= setupCalendar
					.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
				final int day = i;
				final JLabel label = new JLabel(String.valueOf(day));
				label.setHorizontalAlignment(JLabel.CENTER);
				label.setForeground(foreground);
				label.addMouseListener(new MouseListener() {
					public void mousePressed(MouseEvent e) {
					}

					public void mouseClicked(MouseEvent e) {
					}

					public void mouseReleased(MouseEvent e) {
						label.setOpaque(false);
						label.setBackground(background);
						label.setForeground(foreground);
						calendar.set(Calendar.DAY_OF_MONTH, day);
						comboBox.setSelectedItem(dateFormat.format(calendar
								.getTime()));
						// hide();
						// hide is called with setSelectedItem() ... removeAll()
						comboBox.requestFocus();
					}

					public void mouseEntered(MouseEvent e) {
						label.setOpaque(true);
						label.setBackground(selectedBackground);
						label.setForeground(selectedForeground);
					}

					public void mouseExited(MouseEvent e) {
						label.setOpaque(false);
						label.setBackground(background);
						label.setForeground(foreground);
					}
				});

				days.add(label);
			}

			popup.add(BorderLayout.CENTER, days);
			popup.pack();
		}
	}

	// Beispiel-GUI
	public static void main(String args[]) {
		JFrame f = new JFrame("Demo für DateComboBox -> Kalender");
		Container c = f.getContentPane();
		c.setLayout(new FlowLayout());
		c.add(new JLabel("Termin 1:"));
		c.add(new DateExampleJCombo());
		c.add(new JLabel("Termin 2:"));
		c.add(new DateExampleJCombo());
		c.add(new JLabel("Termin 3:"));
		DateExampleJCombo dcb3 = new DateExampleJCombo();
		dcb3.setEditable(true);
		c.add(dcb3);
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		f.setSize(640, 200);
		f.setVisible(true);
	}

}
 
Illuvatar hat gesagt.:
Die Date-Popupklasse is ja cool 😉

Ja, enthält aber noch einen kleinen Fehler, deshalb bitte folgende Zeile(n) verwenden (Ursache ist wie so oft, der unterschiedliche Wochenbeginn zwischen amerikanischem und deutschem Kalender):
Code:
...
			for (int i = 0; i < 7; i++) {
				int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
				JLabel label = new JLabel();
				label.setHorizontalAlignment(JLabel.CENTER);
				label.setForeground(foreground);
				if (dayInt == Calendar.MONDAY) {
					label.setText("Mon");
				} else if (dayInt == Calendar.TUESDAY) {
					label.setText("Die");
				} else if (dayInt == Calendar.WEDNESDAY) {
					label.setText("Mit");
				} else if (dayInt == Calendar.THURSDAY) {
					label.setText("Don");
				} else if (dayInt == Calendar.FRIDAY) {
					label.setText("Fre");
				} else if (dayInt == Calendar.SATURDAY) {
					label.setText("Sam");
				} else if  (dayInt == Calendar.SUNDAY) {
					label.setText("Son");
				} 
				
				days.add(label);
				setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
			}

			setupCalendar = (Calendar) calendar.clone();
			setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
			int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
			for (int i = 0; i < (first -2); i++) {
				days.add(new JLabel(""));
			}
...
Konkret ist eigentlich nur eine Zeile verändert worden (-> first -2). Ich habe aber aus Gründen des besseren Auffindens mehrere Zeilen gepostet.
 
:shock:
ich hoffe du hast das nicht nur wegen mir geschrieben
ich werd´s mir morgen ansehen. für heute ist das zu viel für mich

Schonmal Danke abollm
 
abollm hat gesagt.:
]Ja, enthält aber noch einen kleinen Fehler, deshalb bitte folgende Zeile(n) verwenden (Ursache ist wie so oft, der unterschiedliche Wochenbeginn zwischen amerikanischem und deutschem Kalender):

hmm das kann man aber auch einfacherer internationalisieren :roll:

so hier ist mein senf dazu:

Code:
	private void setCalendar(Calendar cal) {
		Calendar tempCal = (Calendar) cal.clone(); // blaaa
		tempCal.set(Calendar.DAY_OF_MONTH, 1);
		int firstDayOfWeek = tempCal.getFirstDayOfWeek();
		int firstDay = tempCal.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek;
		if (firstDay < 0) {
			firstDay += 7;
		}
		Object[] colHeads = new String[7];
		Object[][] rowData = new String[6][7];
		DateFormatSymbols dfs = new DateFormatSymbols(); // <-wichtig
		String[] days = dfs.getShortWeekdays(); // <- auch
		int actualday = firstDayOfWeek;
		for(int i=0; i<7; i++) {
			colHeads[i] = days[actualday];
			if(actualday < 7) {
				actualday++;
			} else {
				actualday -= 6;
			}
		}
		tempCal.add(Calendar.MONTH, 1);
		Date firstDayInNextMonth = tempCal.getTime();
		tempCal.add(Calendar.MONTH, -1);
		Date day = tempCal.getTime();
		int n = 0;
		int col = firstDay;
		int row = 0;
		while (day.before(firstDayInNextMonth)) {
			SimpleDateFormat f = new SimpleDateFormat("dd");
			if(col == 7) {
				col = 0;
				row++;
			}
			rowData[row][col] = f.format(day);
			col++;
			n++;
			tempCal.add(Calendar.DATE, 1);
			day = tempCal.getTime();
		}
		model.setDataVector(rowData, colHeads); // model für JTable
		yearSpinnerModel.setValue(new Integer(cal.get(Calendar.YEAR))); // so n JSpinner
		monthSpinnerModel.setValue(monthSpinnerModel.getList().get(cal.get(Calendar.MONTH))); // noch son spinner model
	}

die wichtigen stelllen sind gekennzeichnet, die restlichen nur zur vollständigkeit halber da. also wenn du die Locale änderst, sollte nach nem erneuten aufruf der methode die wochentage entsrepchend anders angeordnet sein und das Mon, Die, Mit und so wird auch automatisch gesetzt.
 
Roar hat gesagt.:
...

hmm das kann man aber auch einfacherer internationalisieren :roll:

Das ist schon klar, nur schreib ich hier nicht aus einem engl. Beispiel heraus auch noch groß Klassen zum Internationalisieren von Datumswerten.
Das Trum da oben ist eh schon zu lang für ein einfaches Beispiel

Trotzdem danke für den Code, denn so etwas kann man immer mal gebrauchen.
 
irgendwie kapierich den code noch nicht.
ich muss mal mit mit der calendar class auseinandersetzen
aber irgendwie ist der kalender nicht richtig.
manchmal stimmt der wochentag nicht über ein.
z.B der 5.4.1987 war ein sonntag aber das prog zeigt ein anderen wochentag an
kann es sein das die schaltjahre nicht mitgerechent werden???

und hab noch ne frage für was ist die funktion opaque da?
 
ich ahb das jetzt versucht umzuschreiben. ich will das als jpanel haben. das funzt auch, nur das upadeten nicht 🙁 also wenn man jahr/monat vor/zurück schaltet.

hier der code
Code:
package organizer.gui;

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class Kalender extends JPanel {
  private Calendar calendar;
  private JPanel days;
  
  public Kalender() {
    super();
    this.calendar=Calendar.getInstance();
    this.initializeJPanel();
    this.updatePanel();
  }
  
  protected void updatePanel() {
    System.out.println("update");
    days = new JPanel(new GridLayout(0, 7));
    days.setOpaque(true);
    Calendar setupCalendar = (Calendar) calendar.clone();
    System.out.println("setup: " + setupCalendar.toString());
    setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar
                      .getFirstDayOfWeek());
    for (int i = 0; i < 7; i++) {
      int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
      JLabel label = new JLabel();
      label.setHorizontalAlignment(JLabel.CENTER);
      if (dayInt == Calendar.SUNDAY) {
        label.setText("Son");
      }
      else if (dayInt == Calendar.MONDAY) {
        label.setText("Mon");
      }
      else if (dayInt == Calendar.TUESDAY) {
        label.setText("Die");
      }
      else if (dayInt == Calendar.WEDNESDAY) {
        label.setText("Mit");
      }
      else if (dayInt == Calendar.THURSDAY) {
        label.setText("Don");
      }
      else if (dayInt == Calendar.FRIDAY) {
        label.setText("Fre");
      }
      else if (dayInt == Calendar.SATURDAY) {
        label.setText("Sam");
      }
      days.add(label);
      setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
    }

    setupCalendar = (Calendar) calendar.clone();
    setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
    int firstday = setupCalendar.get(Calendar.DAY_OF_WEEK);
    System.out.println("first:" + firstday);
    for (int i = 1; i < (firstday - 1); i++) {
      days.add(new JLabel(""));
    }
    for (int i = 1; i < setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
      int day = i;
      JLabel label = new JLabel(String.valueOf(day));
      label.setHorizontalAlignment(JLabel.CENTER);
      days.add(label);
    }
    this.add(days, BorderLayout.CENTER);
  }
  
  private JLabel createUpdateButton(final int field,final int amount) {
    final JLabel label = new JLabel();
    final Border selectedBorder = new EtchedBorder();
    final Border unselectedBorder = new EmptyBorder(selectedBorder
        .getBorderInsets(new JLabel()));
    label.setBorder(unselectedBorder);
    label.addMouseListener(new MouseAdapter() {
      public void mouseReleased(MouseEvent e) {
        calendar.add(field, amount);
        Kalender.this.updatePanel();
        System.out.println(calendar.toString());
      }

      public void mouseEntered(MouseEvent e) {
        label.setBorder(selectedBorder);
      }

      public void mouseExited(MouseEvent e) {
        label.setBorder(unselectedBorder);
      }
    });
    return label;
  }
  
  private void initializeJPanel() {
    JPanel header = new JPanel();
    JLabel label;
    label = this.createUpdateButton(Calendar.YEAR, -1);
    label.setText("<<");
    header.add(label);

    label = this.createUpdateButton(Calendar.MONTH, -1);
    label.setText("<");
    header.add(label);

    label = this.createUpdateButton(Calendar.MONTH, 1);
    label.setText(">");
    header.add(label);

    label = this.createUpdateButton(Calendar.YEAR, 1);
    label.setText(">>");
    header.add(label);

    this.setLayout(new BorderLayout());
    this.add(header, BorderLayout.NORTH);
  }
}
 
schonmal ein revalidate() versucht? :-/

edit: mein 3000er beitrag 🙂 🙂
 
ne funktion?? :autsch:

edit: hmm... sry ich hab grad gta gespielt :lol:
 
@Roar:
Herzlichen und so, na du weißt schon.

@SebiB90:
Das Teil, was ich da gepostet habe, ist aus einer englischen Vorlage. Soweit ich erkennen kann, hast du die notwendige Änderung (s. mein zweites Posting oben), nicht eingefügt.
Ich habe hier aber noch ein wesentlich besseres Teil herumliegen, das allerdings noch in eine "Swing"-Form gegossen werden müsste. Werde mich mal morgen versuchen damit zu beschäftigen. Wenn ich ertwas halbwegs Brauchbares habe, poste ich es hier.
 
abollm hat gesagt.:
@SebiB90:
Das Teil, was ich da gepostet habe, ist aus einer englischen Vorlage. Soweit ich erkennen kann, hast du die notwendige Änderung (s. mein zweites Posting oben), nicht eingefügt.
welche änderung?

das das ne methode is weiß ich. auchich wollte wissen was die bewirkt
 
könnt ihr bitte antworten

und hab noch ein problem.wenn ein anderes fenster mein erzeugtes fenster überdeckt verschwinden alle JLabel. erst wenn man drüber her fährt und der listener was tut sind die wieder da. wieso ist das so?
 
in der class DateExampleJCombo will ich eine funktion setDate einfügen diese muss dann die variable calendar in der popup class ändern.nur ich weiß nicht wie ich auf die variable zugreifen kann
 
SebiB90 hat gesagt.:
in der class DateExampleJCombo will ich eine funktion setDate einfügen diese muss dann die variable calendar in der popup class ändern.nur ich weiß nicht wie ich auf die variable zugreifen kann

Ich habe als _Anregung_ einmal die folgende Methode in der Klasse verändert, damit du siehst, wie du das Datum in einem bestimmten Format ausgeben kannst. Du musst jetzt nur noch geeignet mit betr. Variablen hantieren, dann dürftest du dein Problem in den Griff bekommen.


Code:
...
public class DateExampleJCombo extends JComboBox {

	protected SimpleDateFormat dateFormat = new SimpleDateFormat("dd. MMMM yyyy");

	public void setDateFormat(SimpleDateFormat dateFormat) {
		this.dateFormat = dateFormat;
	}

	public void setSelectedItem(Object item) {
		removeAllItems(); // unterdrückt Popup, wenn sichtbar
		addItem(item);
		super.setSelectedItem(item);
		String s = item.toString();
		try {
			Date theDate = dateFormat.parse(s);
			System.out
					.println("Aktuelles Datum: " + dateFormat.format(theDate));
		} catch (ParseException pe) {
			System.out.println("Eingegebenes Datum (" + s
					+ ") entspricht nicht Format \"dd.MMM.yyyy\"");
		}
	}

...
Hoffe es nützt.
 
du hast mich nich verstanden was ich mein

Code:
public class DateJCombo extends JComboBox {

   protected SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MMM.yyyy");

   public DateJCombo() {
     this.calendar = Calendar.getInstance();
   }

   public void setDateFormat(SimpleDateFormat dateFormat) {
      this.dateFormat = dateFormat;
   }

   public void setSelectedItem(Object item) {
      removeAllItems(); // unterdrückt Popup, wenn sichtbar
      addItem(item);
      super.setSelectedItem(item);
   }

   public void updateUI() {
      ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
      if (cui instanceof MetalComboBoxUI) {
         cui = new MetalDateComboBoxUI();
      } else if (cui instanceof MotifComboBoxUI) {
         cui = new MotifDateComboBoxUI();
      } else if (cui instanceof WindowsComboBoxUI) {
         cui = new WindowsDateComboBoxUI();
      }
      setUI(cui);
   }

   
   public void setDate(Date d) {
     //diese methode muss die variable calendar in der class DatePopup verändern nur wie kann ich die ansprechen?
   }

   //...

   class DatePopup implements ComboPopup, MouseMotionListener, MouseListener,
         KeyListener, PopupMenuListener {
      //diese variablesoll mit der methode geändert werden
      protected Calendar calendar;
    //...
   }
}
 
Hallo SebiB90,

ich habe dich nicht falsch verstanden, sondern nur geglaubt, dass du das selbst
hinbekommst, denn eine eigene Methode ist gar nicht notwendig, sofern du der
JComboBox nur (irgend-)einen festen Datumswert zuweisen willst.

Die von mir im vohergehenden Posting eingefügten Zeilen kannst du bis auf einige
kalenderspezifische Dinge fast 1:1 hernehmen.

Ich habe dir hier einmal den kompletten, überarbeiteten Code gepostet, dann
siehst du wahrscheinlich, wie "einfach" die Lösung ist.

Das ist alles natürlich nicht perfekt (Stichwort: führende Null bei
Tageswerten < 10), aber man kann damit arbeiten.

Code:
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.swing.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.plaf.ComboBoxUI;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.EmptyBorder;

import com.sun.java.swing.plaf.motif.MotifComboBoxUI;
import com.sun.java.swing.plaf.windows.WindowsComboBoxUI;

public class DateExampleJCombo extends JComboBox {

	protected static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"dd.MM.yyyy");

	public void setDateFormat(SimpleDateFormat dateFormat) {
		DateExampleJCombo.dateFormat = dateFormat;
	}

	public void setSelectedItem(Object item) {
		removeAllItems(); // unterdrückt Popup, wenn sichtbar
		addItem(item);
		super.setSelectedItem(item);
		String s = item.toString();
		try {
			Date theDate = dateFormat.parse(s);
			System.out.println("Nach Aufruf Combo3 - aktuelles Datum: "
					+ dateFormat.format(theDate));
		} catch (ParseException pe) {
			System.out.println("Eingegebenes Datum (" + s
					+ ") entspricht nicht Format \"dd.MM.yyyy\"");
		}
	}

	public void updateUI() {
		ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
		if (cui instanceof MetalComboBoxUI) {
			cui = new MetalDateComboBoxUI();
		} else if (cui instanceof MotifComboBoxUI) {
			cui = new MotifDateComboBoxUI();
		} else if (cui instanceof WindowsComboBoxUI) {
			cui = new WindowsDateComboBoxUI();
		}
		setUI(cui);
	}

	// Innere Klassen nur dazu, um die DateComboBox-Komponente 
	// in einer Datei zu halten

	// UI-Klassen

	class MetalDateComboBoxUI extends MetalComboBoxUI {
		protected ComboPopup createPopup() {
			return new DatePopup(comboBox);
		}
	}

	class WindowsDateComboBoxUI extends WindowsComboBoxUI {
		protected ComboPopup createPopup() {
			return new DatePopup(comboBox);
		}
	}

	class MotifDateComboBoxUI extends MotifComboBoxUI {
		protected ComboPopup createPopup() {
			return new DatePopup(comboBox);
		}
	}

	class DatePopup implements ComboPopup, MouseMotionListener, MouseListener,
			KeyListener, PopupMenuListener {

		protected JComboBox comboBox;

		protected Calendar calendar;

		protected JPopupMenu popup;

		protected JLabel monthLabel;

		protected JPanel days = null;

		protected SimpleDateFormat monthFormat = new SimpleDateFormat(
				"dd MMM yyyy");

		protected Color selectedBackground;

		protected Color selectedForeground;

		protected Color background;

		protected Color foreground;

		public DatePopup(JComboBox comboBox) {
			this.comboBox = comboBox;
			calendar = Calendar.getInstance();

			// Prüfe L&F
			background = UIManager.getColor("ComboBox.background");
			foreground = UIManager.getColor("ComboBox.foreground");
			selectedBackground = UIManager
					.getColor("ComboBox.selectionBackground");
			selectedForeground = UIManager
					.getColor("ComboBox.selectionForeground");

			initializePopup();
		}

		// Combo-Popup Methode implementieren
		public void show() {
			try {
				// wenn setSelectedItem() mit einem gültigen Datum aufgerufen -> Kalender einstellen
				calendar.setTime(dateFormat.parse(comboBox.getSelectedItem()
						.toString()));

			} catch (Exception e) {
			}
			updatePopup();
			popup.show(comboBox, 0, comboBox.getHeight());
		}

		public void hide() {
			popup.setVisible(false);
		}

		protected JList list = new JList();

		public JList getList() {
			return list;
		}

		public MouseListener getMouseListener() {
			return this;
		}

		public MouseMotionListener getMouseMotionListener() {
			return this;
		}

		public KeyListener getKeyListener() {
			return this;
		}

		public boolean isVisible() {
			return popup.isVisible();
		}

		public void uninstallingUI() {
			popup.removePopupMenuListener(this);
		}

		public void mousePressed(MouseEvent e) {
		}

		public void mouseReleased(MouseEvent e) {
		}

		// ... was anderes
		public void mouseClicked(MouseEvent e) {
			if (!SwingUtilities.isLeftMouseButton(e))
				return;
			if (!comboBox.isEnabled())
				return;
			if (comboBox.isEditable()) {
				comboBox.getEditor().getEditorComponent().requestFocus();
			} else {
				comboBox.requestFocus();
			}
			togglePopup();
		}

		protected boolean mouseInside = false;

		public void mouseEntered(MouseEvent e) {
			mouseInside = true;
		}

		public void mouseExited(MouseEvent e) {
			mouseInside = false;
		}

		// MouseMotionListener
		public void mouseDragged(MouseEvent e) {
		}

		public void mouseMoved(MouseEvent e) {
		}

		// KeyListener
		public void keyPressed(KeyEvent e) {
		}

		public void keyTyped(KeyEvent e) {
		}

		public void keyReleased(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_SPACE
					|| e.getKeyCode() == KeyEvent.VK_ENTER) {
				togglePopup();
			}
		}

		/**
		 * Variables hideNext and mouseInside are used to 
		 * hide the popupMenu by clicking the mouse in the JComboBox
		 */
		public void popupMenuCanceled(PopupMenuEvent e) {
		}

		protected boolean hideNext = false;

		public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
			hideNext = mouseInside;
		}

		public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
		}

		protected void togglePopup() {
			if (isVisible() || hideNext) {
				hide();
			} else {
				show();
			}
			hideNext = false;
		}

		// Bemerkung: JButton nicht benutzt, da ....
		protected JLabel createUpdateButton(final int field, final int amount) {
			final JLabel label = new JLabel();
			final Border selectedBorder = new EtchedBorder();
			final Border unselectedBorder = new EmptyBorder(selectedBorder
					.getBorderInsets(new JLabel()));
			label.setBorder(unselectedBorder);
			label.setForeground(foreground);
			label.addMouseListener(new MouseAdapter() {
				public void mouseReleased(MouseEvent e) {
					calendar.add(field, amount);
					updatePopup();
				}

				public void mouseEntered(MouseEvent e) {
					label.setBorder(selectedBorder);
				}

				public void mouseExited(MouseEvent e) {
					label.setBorder(unselectedBorder);
				}
			});
			return label;
		}

		protected void initializePopup() {
			JPanel header = new JPanel();
			header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
			header.setBackground(background);
			header.setOpaque(true);

			JLabel label;
			label = createUpdateButton(Calendar.YEAR, -1);
			label.setText("<<");
			label.setToolTipText("Vorheriges Jahr");

			header.add(Box.createHorizontalStrut(12));
			header.add(label);
			header.add(Box.createHorizontalStrut(12));

			label = createUpdateButton(Calendar.MONTH, -1);
			label.setText("<");
			label.setToolTipText("Vorheriger Monat");
			header.add(label);

			monthLabel = new JLabel("", JLabel.CENTER);
			monthLabel.setForeground(foreground);
			header.add(Box.createHorizontalGlue());
			header.add(monthLabel);
			header.add(Box.createHorizontalGlue());

			label = createUpdateButton(Calendar.MONTH, 1);
			label.setText(">");
			label.setToolTipText("Nächster Monat");
			header.add(label);

			label = createUpdateButton(Calendar.YEAR, 1);
			label.setText(">>");
			label.setToolTipText("Nächstes Jahr");

			header.add(Box.createHorizontalStrut(12));
			header.add(label);
			header.add(Box.createHorizontalStrut(12));

			popup = new JPopupMenu();
			popup.setBorder(BorderFactory.createLineBorder(Color.black));
			popup.setLayout(new BorderLayout());
			popup.setBackground(background);
			popup.addPopupMenuListener(this);
			popup.add(BorderLayout.NORTH, header);
		}

		protected void updatePopup() {
			monthLabel.setText(monthFormat.format(calendar.getTime()));
			if (days != null) {
				popup.remove(days);
			}
			days = new JPanel(new GridLayout(0, 7));
			days.setBackground(background);
			days.setOpaque(true);

			Calendar setupCalendar = (Calendar) calendar.clone();
			setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar
					.getFirstDayOfWeek());
			for (int i = 0; i < 7; i++) {
				int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
				JLabel label = new JLabel();
				label.setHorizontalAlignment(JLabel.CENTER);
				label.setForeground(foreground);
				if (dayInt == Calendar.MONDAY) {
					label.setText("Mon");
				} else if (dayInt == Calendar.TUESDAY) {
					label.setText("Die");
				} else if (dayInt == Calendar.WEDNESDAY) {
					label.setText("Mit");
				} else if (dayInt == Calendar.THURSDAY) {
					label.setText("Don");
				} else if (dayInt == Calendar.FRIDAY) {
					label.setText("Fre");
				} else if (dayInt == Calendar.SATURDAY) {
					label.setText("Sam");
				} else if (dayInt == Calendar.SUNDAY) {
					label.setText("Son");
				}

				days.add(label);
				setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
			}

			setupCalendar = (Calendar) calendar.clone();
			setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
			int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
			for (int i = 0; i < (first - 2); i++) {
				days.add(new JLabel(""));
			}
			for (int i = 1; i <= setupCalendar
					.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
				final int day = i;
				final JLabel label = new JLabel(String.valueOf(day));
				label.setHorizontalAlignment(JLabel.CENTER);
				label.setForeground(foreground);
				label.addMouseListener(new MouseListener() {
					public void mousePressed(MouseEvent e) {
					}

					public void mouseClicked(MouseEvent e) {
					}

					public void mouseReleased(MouseEvent e) {
						label.setOpaque(false);
						label.setBackground(background);
						label.setForeground(foreground);
						calendar.set(Calendar.DAY_OF_MONTH, day);
						//
						comboBox.setSelectedItem(dateFormat.format(calendar
								.getTime()));
						// hide();
						// hide is called with setSelectedItem() ... removeAll()
						comboBox.requestFocus();
					}

					public void mouseEntered(MouseEvent e) {
						label.setOpaque(true);
						label.setBackground(selectedBackground);
						label.setForeground(selectedForeground);
					}

					public void mouseExited(MouseEvent e) {
						label.setOpaque(false);
						label.setBackground(background);
						label.setForeground(foreground);
					}
				});

				days.add(label);
			}

			popup.add(BorderLayout.CENTER, days);
			popup.pack();
		}
	}

	// Beispiel-GUI
	public static void main(String args[]) {
		JFrame f = new JFrame("Demo für DateComboBox -> Kalender");
		Container c = f.getContentPane();
		c.setLayout(new FlowLayout());
		c.add(new JLabel("Termin 1:"));
		c.add(new DateExampleJCombo());
		c.add(new JLabel("Termin 2:"));
		c.add(new DateExampleJCombo());
		c.add(new JLabel("Termin 3:"));
		DateExampleJCombo dcb3 = new DateExampleJCombo();
		dcb3.setEditable(true);
		c.add(dcb3);
		//
		GregorianCalendar cal = new GregorianCalendar();
		cal.set(Calendar.DATE, 1);
		cal.set(Calendar.MONTH, 2 - 1);
		cal.set(Calendar.YEAR, 2003);
		//	Zuweisung JCombo3 mit Datum "01.02.2003";
		String s = cal.get(Calendar.DATE) + "." + (cal.get(Calendar.MONTH) + 1)
				+ "." + cal.get(Calendar.YEAR);
		System.out.println("Vor Aufruf Combo3 - aktuelles zugew. Datum: " + s);
		try {
			Date datum1 = dateFormat.parse(s);
			dcb3.setSelectedItem(s);
		} catch (ParseException pe) {
			System.out.println("Eingegebenes Datum (" + s
					+ ") entspricht nicht Format \"dd.MM.yyyy\"");
		}

		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		f.setSize(640, 200);
		f.setVisible(true);
	}

}

PS: Den "try ...catch"-Block unten kannst du dir grundsätzlich auch sparen. Ich hatte damit lediglich ein wenig herumgespielt.
 
und was ist mit dem anderen problem?
das mit den kalender,das ich schon angesprochen hab

die JLabel´s verschwinden wenn ich mindest einmal einen anderen monat ausgewählt habe und dann ein anderes fenster über das fenster gelegt wird oder wenn ich im JTabbedPane, in dem das JPanel drin ist, eine andere "karteikarte" auswähle. wieso ist das so?

der der code
Code:
package organizer.gui;

import organizer.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class Kalender extends JPanel {
  private Calendar calendar;
  private JPanel days;
  private JLabel monthLabel;
  private SimpleDateFormat monthFormat = new SimpleDateFormat("dd MMM yyyy");
  private TerminManager manger;

  public Kalender(TerminManager manager) {
    super();
    this.manger=manager;
    this.calendar=Calendar.getInstance();
    this.initializeJPanel();
    this.updatePanel();
  }

  protected void updatePanel() {
    monthLabel.setText(monthFormat.format(calendar.getTime()));
    if(days!=null) {
      days.removeAll();
    }
    days = new JPanel(new GridLayout(0, 7));
    days.setOpaque(true);
    for (int i = 1; i <=7; i++) {
      int dayInt = ( (i + 1) == 8) ? 1 : i + 1;
      JLabel label = new JLabel();
      label.setHorizontalAlignment(JLabel.CENTER);
      if (dayInt == Calendar.SUNDAY) {
        label.setText("Son");
      }
      else if (dayInt == Calendar.MONDAY) {
        label.setText("Mon");
      }
      else if (dayInt == Calendar.TUESDAY) {
        label.setText("Die");
      }
      else if (dayInt == Calendar.WEDNESDAY) {
        label.setText("Mit");
      }
      else if (dayInt == Calendar.THURSDAY) {
        label.setText("Don");
      }
      else if (dayInt == Calendar.FRIDAY) {
        label.setText("Fre");
      }
      else if (dayInt == Calendar.SATURDAY) {
        label.setText("Sam");
      }
      days.add(label);
    }

    Calendar setupCalendar = (Calendar) calendar.clone();
    setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
    int firstday = setupCalendar.get(Calendar.DAY_OF_WEEK);
    for (int i = 1; i < (firstday - 1); i++) {
      days.add(new JLabel(""));
    }
    for (int i = 1; i <=setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
      int day = setupCalendar.get(Calendar.DAY_OF_MONTH);
      final Date d = setupCalendar.getTime();
      final JLabel label = new JLabel(String.valueOf(day));
      label.setOpaque(true);
      if(this.manger.isTerminAtDay(d)) {
        String s="<html><center>" + day + "
";
        if(this.manger.isBirthdayAtDay(d)) {
          s+="Geburtstag
";
        }
        if(this.manger.isOtherTerminAtDay(d)) {
          s+="Termin";
        }
        label.setText(s);
        label.addMouseListener(new MouseListener() {
          /**
           * mouseClicked
           *
           * @param e MouseEvent
           */
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              Termin[] t = Kalender.this.manger.getTermineAtDay(d);
              if (t.length == 1) {
                new TerminDialog(null, t[0]);
              }
            }
          }

          /**
           * mouseEntered
           *
           * @param e MouseEvent
           */
          public void mouseEntered(MouseEvent e) {
          }

          /**
           * mouseExited
           *
           * @param e MouseEvent
           */
          public void mouseExited(MouseEvent e) {
          }

          /**
           * mousePressed
           *
           * @param e MouseEvent
           */
          public void mousePressed(MouseEvent e) {
          }

          /**
           * mouseReleased
           *
           * @param e MouseEvent
           */
          public void mouseReleased(MouseEvent e) {
          }

        });
      }
      final Color background=label.getBackground();
      final Color foreground=label.getForeground();
      label.setHorizontalAlignment(JLabel.CENTER);
      label.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
          label.setBackground(Color.BLUE);
          label.setForeground(Color.RED);
        }

        public void mouseExited(MouseEvent e) {
          label.setBackground(background);
          label.setForeground(foreground);
        }
      });
      days.add(label);
      setupCalendar.roll(Calendar.DAY_OF_MONTH,true);
    }
    this.add(days, BorderLayout.CENTER);
    this.revalidate();
  }

  private JLabel createUpdateButton(final int field,final int amount) {
    final JLabel label = new JLabel();
    final Border selectedBorder = new EtchedBorder();
    final Border unselectedBorder = new EmptyBorder(selectedBorder
        .getBorderInsets(new JLabel()));
    label.setBorder(unselectedBorder);
    label.addMouseListener(new MouseAdapter() {
      public void mouseReleased(MouseEvent e) {
        calendar.add(field, amount);
        Kalender.this.updatePanel();
      }

      public void mouseEntered(MouseEvent e) {
        label.setBorder(selectedBorder);
      }

      public void mouseExited(MouseEvent e) {
        label.setBorder(unselectedBorder);
      }
    });
    return label;
  }

  private void initializeJPanel() {
    JPanel header = new JPanel();
    JLabel label;
    label = this.createUpdateButton(Calendar.YEAR, -1);
    label.setText("<<");
    header.add(label);

    label = this.createUpdateButton(Calendar.MONTH, -1);
    label.setText("<");
    header.add(label);

    monthLabel=new JLabel("");
    header.add(monthLabel);

    label = this.createUpdateButton(Calendar.MONTH, 1);
    label.setText(">");
    header.add(label);

    label = this.createUpdateButton(Calendar.YEAR, 1);
    label.setText(">>");
    header.add(label);

    this.setLayout(new BorderLayout());
    this.add(header, BorderLayout.NORTH);
  }
}
 
SebiB90 hat gesagt.:
hast du keine ferien? wie alt bist du überhaupt?

schonmal danke
du hilfst mir sehr viel 😀

Seit heute habe ich Ferien, endlich.

Leider schaffe ich das doch erst frühestens heute abend, mir dein Problem näher anzuschauen (in meinem Alter brauche ich einfach mehr Pausen :wink: ).
 
abollm hat gesagt.:
SebiB90 hat gesagt.:
hast du keine ferien? wie alt bist du überhaupt?

schonmal danke
du hilfst mir sehr viel 😀

Seit heute habe ich Ferien, endlich.

Leider schaffe ich das doch erst frühestens heute abend, mir dein Problem näher anzuschauen (in meinem Alter brauche ich einfach mehr Pausen :wink: ).
wie alt bist du denn? wenn du mehr pause brauchst?

Dann mach ich erst mal ein anderes programm/bzw. erweitere es, bis du zeit hast.
 
Hallo an alle,

ich möchte diesen Kalender auch in meinem Programmm benutzen.
Implementiert habe ich ihn schon und läuft ganz gut.
Mein Problem ist aber das ich das ausgewählte Datum in einer anderen Klasse weiter verwenden möchte.
Irgendwie bekomm ich das nicht ohne Fehlermeldung hin.

Beispiel:

Ich habe die Klasse DateComboBox erstellt mit dem Kalender und möchte nun das ausgewählte Datum als String in einer anderen Klasse weiterverwenden.
Code:
...
 DateComboBox dcb = new DateComboBox();
			    this.getContentPane().add(dcb);
				dcb.setEditable(true);
				dcb.setBounds(773,460,173,37);
...
dann die Abfrage nach drücken eines Buttons

String tempItem = dcb.getSelectedItem().toString();
		System.out.println(tempItem);

...
Also ich versuche mich da reinzufitzen aber irgendwie komme ich nicht weiter.

Vielleicht kann mir bitte jemand helfen, solange beschäftige ich mich mit Java noch nicht.


Vielen Dank
BobbyDD
 
Hallo,

kann mir bitte jemand bei o.g. Problem helfen. Ich komme einfach nicht weiter.

Ich möchte einfach das aus dem Kalender gewählte Datum in einer anderen Klasse in eine Datei schreiben.
Wie kann ich das ausgewählte Datum übertragen????


Vielen Dank für die Mühe


BobbyDD
 
Status
Nicht offen für weitere Antworten.

Zurück
Oben