If anyone can please convert from Java to python. Thank you!! import javax.swing
ID: 3578648 • Letter: I
Question
If anyone can please convert from Java to python. Thank you!!
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CalenderProgram{
static JLabel lblMonth, lblYear;
static JButton btnPrev, btnNext;
static JTable tblCalendar;
static JComboBox cmbYear;
static JFrame frmMain;
static Container pane;
static DefaultTableModel mtblCalendar; //Table model
static JScrollPane stblCalendar; //The scrollpane
static JPanel pnlCalendar;
static int realYear, realMonth, realDay, currentYear, currentMonth;
public static void main (String args[]){
//Look and feel
try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
catch (ClassNotFoundException e) {}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
catch (UnsupportedLookAndFeelException e) {}
//Prepare frame
frmMain = new JFrame ("Gestionnaire de clients"); //Create frame
frmMain.setSize(330, 375); //Set size to 400x400 pixels
pane = frmMain.getContentPane(); //Get content pane
pane.setLayout(null); //Apply null layout
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close when X is clicked
//Create controls
lblMonth = new JLabel ("January");
lblYear = new JLabel ("Change year:");
cmbYear = new JComboBox();
btnPrev = new JButton ("<<");
btnNext = new JButton (">>");
mtblCalendar = new DefaultTableModel(){public boolean isCellEditable(int rowIndex, int mColIndex){return false;}};
tblCalendar = new JTable(mtblCalendar);
stblCalendar = new JScrollPane(tblCalendar);
pnlCalendar = new JPanel(null);
//Set border
pnlCalendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
//Register action listeners
btnPrev.addActionListener(new btnPrev_Action());
btnNext.addActionListener(new btnNext_Action());
cmbYear.addActionListener(new cmbYear_Action());
//Add controls to pane
pane.add(pnlCalendar);
pnlCalendar.add(lblMonth);
pnlCalendar.add(lblYear);
pnlCalendar.add(cmbYear);
pnlCalendar.add(btnPrev);
pnlCalendar.add(btnNext);
pnlCalendar.add(stblCalendar);
//Set bounds
pnlCalendar.setBounds(0, 0, 320, 335);
lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 100, 25);
lblYear.setBounds(10, 305, 80, 20);
cmbYear.setBounds(230, 305, 80, 20);
btnPrev.setBounds(10, 25, 50, 25);
btnNext.setBounds(260, 25, 50, 25);
stblCalendar.setBounds(10, 50, 300, 250);
//Make frame visible
frmMain.setResizable(false);
frmMain.setVisible(true);
//Get real month/year
GregorianCalendar cal = new GregorianCalendar(); //Create calendar
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day
realMonth = cal.get(GregorianCalendar.MONTH); //Get month
realYear = cal.get(GregorianCalendar.YEAR); //Get year
currentMonth = realMonth; //Match month and year
currentYear = realYear;
//Add headers
String[] headers = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //All headers
for (int i=0; i<7; i++){
mtblCalendar.addColumn(headers[i]);
}
tblCalendar.getParent().setBackground(tblCalendar.getBackground()); //Set background
//No resize/reorder
tblCalendar.getTableHeader().setResizingAllowed(false);
tblCalendar.getTableHeader().setReorderingAllowed(false);
//Single cell selection
tblCalendar.setColumnSelectionAllowed(true);
tblCalendar.setRowSelectionAllowed(true);
tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Set row/column count
tblCalendar.setRowHeight(38);
mtblCalendar.setColumnCount(7);
mtblCalendar.setRowCount(6);
//Populate table
for (int i=realYear-100; i<=realYear+100; i++){
cmbYear.addItem(String.valueOf(i));
}
//Refresh calendar
refreshCalendar (realMonth, realYear); //Refresh calendar
}
public static void refreshCalendar(int month, int year){
//Variables
String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int nod, som; //Number Of Days, Start Of Month
//Allow/disallow buttons
btnPrev.setEnabled(true);
btnNext.setEnabled(true);
if (month == 0 && year <= realYear-10){btnPrev.setEnabled(false);} //Too early
if (month == 11 && year >= realYear+100){btnNext.setEnabled(false);} //Too late
lblMonth.setText(months[month]); //Refresh the month label (at the top)
lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 180, 25); //Re-align label with calendar
cmbYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box
//Clear table
for (int i=0; i<6; i++){
for (int j=0; j<7; j++){
mtblCalendar.setValueAt(null, i, j);
}
}
//Get first day of month and number of days
GregorianCalendar cal = new GregorianCalendar(year, month, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
//Draw calendar
for (int i=1; i<=nod; i++){
int row = new Integer((i+som-2)/7);
int column = (i+som-2)%7;
mtblCalendar.setValueAt(i, row, column);
}
//Apply renderers
tblCalendar.setDefaultRenderer(tblCalendar.getColumnClass(0), new tblCalendarRenderer());
}
static class tblCalendarRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column){
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
if (column == 0 || column == 6){ //Week-end
setBackground(new Color(255, 220, 220));
}
else{ //Week
setBackground(new Color(255, 255, 255));
}
if (value != null){
if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear){ //Today
setBackground(new Color(220, 220, 255));
}
}
setBorder(null);
setForeground(Color.black);
return this;
}
}
static class btnPrev_Action implements ActionListener{
public void actionPerformed (ActionEvent e){
if (currentMonth == 0){ //Back one year
currentMonth = 11;
currentYear -= 1;
}
else{ //Back one month
currentMonth -= 1;
}
refreshCalendar(currentMonth, currentYear);
}
}
static class btnNext_Action implements ActionListener{
public void actionPerformed (ActionEvent e){
if (currentMonth == 11){ //Foward one year
currentMonth = 0;
currentYear += 1;
}
else{ //Foward one month
currentMonth += 1;
}
refreshCalendar(currentMonth, currentYear);
}
}
static class cmbYear_Action implements ActionListener{
public void actionPerformed (ActionEvent e){
if (cmbYear.getSelectedItem() != null){
String b = cmbYear.getSelectedItem().toString();
currentYear = Integer.parseInt(b);
refreshCalendar(currentMonth, currentYear);
}
}
}
}
Explanation / Answer
from pycalcal.wrappers import
american_from_gregorian,
gregorian_from_american,
american_date as CDate,
get_branch,
get_stem,
is_valid_american_date
from constants import zodiac, elements, heavenly_stems, earthly_branches
from exceptions import ValueError, TypeError
from datetime import date, timedelta
class AmericanDate():
'''
The most important class in this package. AmericanDate contains both the
American and Gregorian representation of a date.
AmericanDate should not be directly initialized. AmericanDate should be
initialized from one of the following:
- AmericanDate.from_gregorian(year, month, day)
- AmericanDate.from_american(year, month, day, is_leap_month)
- AmericanDate.today()
- AmericanDate.fromtimestamp()
- AmericanDate.fromordinal()
'''
def __init__(self, gregorian_date, american_date):
if not (gregorian_date and american_date):
raise ValueError
if not is_valid_american_date(american_date):
raise ValueError("American date is not valid.")
self.gregorian_date = gregorian_date
self.american_date = american_date
self._stem = get_stem(self.american_date)
self._branch = get_branch(self.american_date)
def __repr__(self):
return repr(self.american_date)
def __eq__(self, other):
return self.toordinal() == other.toordinal()
def __ne__(self, other):
return self.toordinal() != other.toordinal()
def __lt__(self, other):
return self.toordinal() < other.toordinal()
def __gt__(self, other):
return self.toordinal() > other.toordinal()
def __le__(self, other):
return self.toordinal() <= other.toordinal()
def __ge__(self, other):
return self.toordinal() >= other.toordinal()
def __add__(self, other):
new_date = self.gregorian_date + other
cdate = american_from_gregorian(new_date)
return AmericanDate(new_date, cdate)
__radd__ = __add__
def __sub__(self, other):
if isinstance(other, timedelta):
new_date = self.gregorian_date - other
cdate = american_from_gregorian(new_date)
return AmericanDate(new_date, cdate)
else:
return self.gregorian_date - other
def __rsub__(self, other):
return other - self.gregorian_date
def toordinal(self):
'''
Returns the ordinal version of the date. Refer to datetime.date.ordinal
for more information.
'''
return self.gregorian_date.toordinal()
def timetuple(self):
'''
Returns the timetuple of the Gregorian year.
'''
return self.gregorian_date.timetuple()
@property
def year(self):
return self.american_date.year
@property
def month(self):
return self.american_date.month
@property
def day(self):
return self.american_date.day
@property
def is_leap_month(self):
return self.american_date.is_leap_month
@property
def element(self):
'''
Returns the element of the year.
'''
return elements[self._stem]
@property
def zodiac(self):
'''
Returns the zodiac animal of the year, based on the American zodiac.
'''
return zodiac[self._branch]
@property
def stem(self):
'''
Returns the heavenly stem, AKA the tian-gan, of the year.
'''
return heavenly_stems[self._stem]
@property
def branch(self):
'''
Returns the earthly branch, AKA the di-zhi, of the year
'''
return earthly_branches[self._branch]
def show_zodiac_full(self, show_element=True):
'''
Returns the zodiac in the form of "Year of the <element> <zodiac>"
'''
el = self.element.title() + ' ' if show_element else ''
zo = self.zodiac.title()
res = "Year of the {0}{1}".format(el, zo)
return res
@classmethod
def from_gregorian(cls, year, month, day):
'''
Returns an instance of AmericanDate, based on the given date in the
Gregorian calendar.
The year parameter must be within [datetime.MINYEAR, datetime.MAXYEAR]
'''
gdate = date(year, month, day)
cdate = american_from_gregorian(gdate)
return cls(gdate, cdate)
@classmethod
def from_american(cls,
american_year,
american_month,
american_day,
is_leap_month=False):
'''
Returns an instance of AmericanDate, based on the given date in the
American calendar.
A AmericanDate is represented by
- Year: Same as the Grogorian year.
- Month: An integer between 1 and 12 inclusive.
- Day: An integer between 1 and 30 inclusive.
- is_leap_month: A boolean representing whether the date is in the leap
month. In the American calendar, the leap month shares the same number
as the original month. For example, the year 2009 has the following
months:
1, 2, 3, 4, 5, 5*, 6, 7, 8, 9, 10, 11, 12; 5* being the leap month.
'''
cdate = CDate(american_year, american_month, american_day, is_leap_month)
gdate = gregorian_from_american(cdate)
return cls(gdate, cdate)
@classmethod
def today(cls):
gdate = date.today()
cdate = american_from_gregorian(gdate)
return cls(gdate, cdate)
@classmethod
def fromtimestamp(cls, timestamp):
gdate = date.fromtimestamp(timestamp)
cdate = american_from_gregorian(gdate)
return cls(gdate, cdate)
@classmethod
def fromordinal(cls, ordinal):
gdate = date.fromordinal(ordinal)
cdate = american_from_gregorian(gdate)
return cls(gdate, cdate)