Question

If anyone can please convert from Java to python. Thank you!! import javax.swing.*; import javax.swing.event.*; import...

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);
}
}
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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)

Add a comment
Know the answer?
Add Answer to:
If anyone can please convert from Java to python. Thank you!! import javax.swing.*; import javax.swing.event.*; import...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Modify Java Code below: - Remove Button Try the Number -Instead of Try the Number button...

    Modify Java Code below: - Remove Button Try the Number -Instead of Try the Number button just hit enter on keyboard to try number -Remove Button Quit import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; // Main Class public class GuessGame extends JFrame { // Declare class variables private static final long serialVersionUID = 1L; public static Object prompt1; private JTextField userInput; private JLabel comment = new JLabel(" "); private JLabel comment2 = new JLabel(" "); private int...

  • Can you help me to link two frames in Java Swing and then if you click...

    Can you help me to link two frames in Java Swing and then if you click "Proceed button" it will link to the Second Frame...Thank you :) First frame code: //First import javax.swing.*; import java.awt.event.*; import java.io.*; public class Sample extends JFrame implements ActionListener { JMenuBar mb; JMenu file; JMenuItem open; JTextArea ta; JButton proceed= new JButton("Proceed"); Sample() { open = new JMenuItem("Open File"); open.addActionListener(this); file = new JMenu("File"); file.add(open); mb = new JMenuBar(); mb.setBounds(0, 0, 400, 20); mb.add(file); ta...

  • Simple java GUI language translator. English to Spanish, French, or German import javax.swing.*; import java.awt.*; import...

    Simple java GUI language translator. English to Spanish, French, or German import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class translatorApp extends JFrame implements ActionListener {    public static final int width = 500;    public static final int height = 300;    public static final int no_of_lines = 10;    public static final int chars_per_line = 20;    private JTextArea lan1;    private JTextArea lan2;    public static void main(String[] args){        translatorApp gui = new translatorApp();...

  • import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.BorderFactory; import javax.swing.border.Border; public class Q1 extends JFrame {...

    import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.BorderFactory; import javax.swing.border.Border; public class Q1 extends JFrame {    public static void createAndShowGUI() {        JFrame frame = new JFrame("Q1");        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        Font courierFont = new Font("Courier", Font.BOLD, 40);        Font arialFont = new Font("Arial", Font.BOLD, 40);        Font sansFont = new Font("Sans-serif", Font.BOLD, 20);        JLabel label = new JLabel("Enter a word"); label.setFont(sansFont);        Font font1 = new Font("Sans-serif", Font.BOLD, 40);       ...

  • I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label;...

    I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Fall_2017 {    public TextArea courseInput;    public Label textAreaLabel;    public JButton addData;    public Dialog confirmDialog;    HashMap<Integer, ArrayList<String>> students;    public Fall_2017(){    courseInput = new TextArea(20, 40);    textAreaLabel = new Label("Student's data:");    addData = new JButton("Add...

  • Need some help fixing these compilation errors that start around line 20, thank you import javax.swing.*;...

    Need some help fixing these compilation errors that start around line 20, thank you import javax.swing.*; public class PropertyTax1 extends JFrame {    private static final int WIDTH = 400, HEIGHT = 300;       public PropertyTax1()    {        setTitle("Calculation of Property Taxes");        setSize(WIDTH, HEIGHT);        setVisible(true);        setDefaultCloseOperation(EXIT_ON_CLOSE);    } // end of the constructor method       public static void main(String[] args)    {        PropertyTax1 proptax = new PropertyTax1();   ...

  • Can you please fix the error. package com.IST240Apps; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*;...

    Can you please fix the error. package com.IST240Apps; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; import java.net.*; public class LinkRotator extends JFrame implements Runnable, ActionListener { String[] pageTitle = new String[5]; URI[] pageLink = new URI[5]; int current = 0; Thread runner; JLabel siteLabel = new Jlabel(); public LinkRotator() { setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); setSize(300, 100); FlowLayout flo = new Flowlayout(); setLayout(flo); add(siteLabel); pageTitle = new String[] { "Oracle Java Site", "Server Side", "JavaWorld", "Google", "Yahoo", "Penn State" }; pageLink[0] = getUR1("http://www.oracle.com/technetwork/java");...

  • Can you please help me to run this Java program? I have no idea why it...

    Can you please help me to run this Java program? I have no idea why it is not running. import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @SuppressWarnings({"unchecked", "rawtypes"}) public class SmartPhonePackages extends JFrame { private static final long serialVersionID= 6548829860028144965L; private static final int windowWidth = 400; private static final int windowHeight = 200; private static final double SalesTax = 1.06; private static JPanel panel;...

  • I have currently a functional Java progam with a gui. Its a simple table of contacts...

    I have currently a functional Java progam with a gui. Its a simple table of contacts with 3 buttons: add, remove, and edit. Right now the buttons are in the program but they do not work yet. I need the buttons to actually be able to add, remove, or edit things on the table. Thanks so much. Here is the working code so far: //PersonTableModel.java import java.util.List; import javax.swing.table.AbstractTableModel; public class PersonTableModel extends AbstractTableModel {     private static final int...

  • GUI in java: Run the below code before doing the actionlistener: import java.awt.*; import javax.swing.*; public...

    GUI in java: Run the below code before doing the actionlistener: import java.awt.*; import javax.swing.*; public class DrawingFrame extends JFrame {    JButton loadButton, saveButton, drawButton;    JComboBox colorList, shapesList;    JTextField parametersTextField;       DrawingFrame() {        super("Drawing Application");        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        JToolBar toolbar = new JToolBar();        toolbar.setRollover(true);        toolbar.add(loadButton=new JButton("Load"));        toolbar.add(saveButton=new JButton("Save"));        toolbar.addSeparator();        toolbar.add(drawButton=new JButton("Draw"));               toolbar.addSeparator();        toolbar.addSeparator();        toolbar.add(new...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT