import java.awt.Event;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class SkemaFrame extends JFrame implements ActionListener {
private static final int N_LEKTIONER_PR_DAG = 8;
private static final String[] LESSON_TYPES = { "Fri", "SWK", "SWD", "ITO",
"Studie" };
private static final String[] DAY_NAMES = { "mandag", "tirsdag", "onsdag",
"torsdag", "fredag" };
private JMenuItem printMI;
private JComboBox[][] lektioner;
public SkemaFrame(String title) {
super( title );
setJMenuBar( createMenuBar() );
buildSkema();
setDefaultCloseOperation( EXIT_ON_CLOSE );
pack();
setVisible( true );
}
private void buildSkema() {
getContentPane().setLayout(
new GridLayout( 1 + N_LEKTIONER_PR_DAG, 1 + DAY_NAMES.length ) );
getContentPane().add( new JLabel() );
for (int i = 0; i < DAY_NAMES.length; i++) {
JLabel dayName = new JLabel( DAY_NAMES[i] );
dayName.setHorizontalAlignment( SwingConstants.CENTER );
getContentPane().add( dayName );
}
lektioner = new JComboBox[DAY_NAMES.length][N_LEKTIONER_PR_DAG];
for (int lesson = 0; lesson < N_LEKTIONER_PR_DAG; lesson++) {
JLabel lektionsNummer = new JLabel( (lesson + 1) + ". " );
lektionsNummer.setHorizontalAlignment( SwingConstants.RIGHT );
getContentPane().add( lektionsNummer );
for (int day = 0; day < DAY_NAMES.length; day++) {
lektioner[day][lesson] = new JComboBox( LESSON_TYPES );
getContentPane().add( lektioner[day][lesson] );
}
}
}
private JMenuBar createMenuBar() {
JMenuBar bar = new JMenuBar();
JMenu fileMenu = new JMenu( "File" );
{
printMI = new JMenuItem( "Print" );
printMI.setAccelerator( KeyStroke.getKeyStroke( 'P', Event.CTRL_MASK ) );
printMI.addActionListener( this );
fileMenu.add( printMI );
}
bar.add( fileMenu );
return bar;
}
private static final int COLUMN_WIDTH = 10;
public void actionPerformed( ActionEvent e ) {
Object source = e.getSource();
System.out.print( " " );
for (int i = 0; i < DAY_NAMES.length; i++)
System.out.print( tekstFormat( DAY_NAMES[i], COLUMN_WIDTH, CENTER ) );
System.out.println();
if (source == printMI) {
for (int lesson = 0; lesson < N_LEKTIONER_PR_DAG; lesson++) {
System.out.print( tekstFormat( (lesson + 1) + ". ", COLUMN_WIDTH, RIGHT ) );
for (int day = 0; day < DAY_NAMES.length; day++)
System.out.print(
tekstFormat( " " + lektioner[day][lesson].getSelectedItem(), COLUMN_WIDTH, LEFT ) );
System.out.println();
}
}
}
// konstanter for positioner
private static final int LEFT = 0;
private static final int CENTER = 1;
private static final int RIGHT = 2;
private String tekstFormat( Object obj, int width, int position ) {
String txt = obj.toString();
switch (position) {
case LEFT:
while (txt.length() < width)
txt = txt + " ";
break;
case CENTER:
while (txt.length() < width)
// modulus er blot et trick til at få det at skifte hver gang
if (txt.length() % 2 == 0)
txt = txt + " ";
else
txt = " " + txt;
break;
case RIGHT:
while (txt.length() < width)
txt = " " + txt;
break;
}
return txt;
}
} |