ActionListener() interface
I have used actionListener() interface quite often for GUI applications.
But I'm still fuzzy about logic behind that--I mean I can't make my code work but
don't know why/where this interface is used in the whole program. I wish I can find
a better expression about that. Let me put it another way--the core reason for interface is for multiinheritance, where we can see the multiinheritance case in ActionListener() interface.
I'll be extremely grateful if someone can illustrate the logic behind that
Thanks. yylx
Well first I'd like to clear up a point, multiple inheritance is impossible in java, Some will argue, but the fact remains that you must implement each method of an interface...
Now to the point.....
the interface defines a single method,(at least I think its just one), public void actionPerformed(ActionEvent e);
Any class that implements this interface must have this method defined, as such any class implementing this method may be treated as , "an instance of ActionListener"
That allows the AbstractButton class, subsequently all subclasses, to define a method, addActionListener(ActionListener al)
The point being that this method requires an instance of a class that has the actionPerformed(ActionEvent e) method defined, it depends on it!!!
There are quite a few uses of interfaces, and you should probably take some time to explore them, if you havent allready...
Hope this helps, a little at the very least...
J.Prisco
Similar Messages
-
Hi
I am creating a very basic program that has two buttons and a text field. When any button is clicked, then the text in the text field should change. However, I've run into a problem with the actionPerformed method - it doesn't seem to recognise the names of my buttons i.e. *'+button_name +cannot be resolved'*. So, when I click the button then nothing happens. The code is not very large so I'll provide it below.
import javax.swing.*;*
import java.awt.event.;
import java.awt.*;
public class SGUI extends JPanel implements ActionListener{
public SGUI() {
ImageIcon hello = createImageIcon("images/hello.gif");
ImageIcon bye = createImageIcon("images/bye.gif");
JButton sayHello = new JButton(hello);
JButton sayBye = new JButton(bye);
JTextField message = new JTextField("What shall I say?");
message.setBackground(Color.blue);
message.setForeground(Color.WHITE);
//Listen for actions on the 2 buttons and text field.
sayHello.addActionListener(this);
sayBye.addActionListener(this);
message.addActionListener(this);
sayHello.setToolTipText("display greeting");
sayBye.setToolTipText("display farewell");
//add components to container using flowLayout
add(sayHello);
add(sayBye);
add(message);
public void actionPerformed(ActionEvent ae){
if (ae.getSource()==sayHello){
message.setText("Hello!");
} //respond to the button pressed
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SGUI.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloGoodbye");
//Create and set up the content pane.
SGUI newContentPane = new SGUI();
newContentPane.setOpaque(true); //content panes must be opaque
newContentPane.setBackground(Color.yellow);
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setSize(300, 300);
frame.setVisible(true);
//run the program
public static void main(String[] args) {
createAndShowGUI();
}The _{color:#ff0000}red lines{color}_ appear underneath sayBye+ and message in the actionPerformed() method, which results in the actionPerformed method not working - although the actual program still runs*. Please help!
Edited by: aras298 on May 5, 2008 8:49 AMyou appear to have a problem of scope: your JButtons are declared and defined in the constructor and have a scope that is confined to the constructor. Anything that's outside of the constructor will thus not be able to "see" these components. One solution: make the buttons declared in the class. You can still construct them in the constructor, but make sure that their scope is the entire class, not just the constructor.
Also, I recommend that you start getting in the habit of not having your main GUI classes implement the ActionListener interface, but rather using anonymous inner classes, or private inner classes, or stand-alone classes for your actionlisteners. It's much cleaner this way. -
=Urgent===anonymous ActionListener===
Hi,
I want to realize the function like "search" in Windows Notepad. Persue-code is like the following:
Press "Find" icon
If(string is found)
highlight the string
else
pop up the dialog window
Dialog window is in the following:
else
JOptionPane cannotDialog = new JOptionPane();
cannotDialog.showMessageDialog(this,"Cannot Find
"+typedText,"Othello",JOptionPane.INFORMATION_MESSAGE);
when compling the file, there is a error message:
=====
symbol : method showMessageDialog (<anonymous
java.awt.event.ActionListener>,java.lang.String,java.lang.String,int)
location: class javax.swing.JOptionPane
cannotDialog.showMessageDialog(this,"Cannot Find
"+typedText,"Find",JOptionPane.INFORMATION_MESSAGE);
======
Generally speaking, i've got the ActionListener after clicking the icon/menu item, but i really don't know how to solve this problem, would u please give me some hint?
Any information are appreciated...
Thanks...Hi,
The prototype of showMessageDialog() method in JOptionPane is:
public static void showMessageDialog(Component parentComponent,
Object message,
String title,
int messageType)
So, the first parametter must be a Component object or a sub-class of Component object. In your case, I think you caught event for "Find" icon in anonymous object and "this" identifier is not understood as a Component.
I can imagine your code like the following:
JButton findButton = ....................
findButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
if(String is found)
else
JOptionPane cannotDialog = new JOptionPane();
cannotDialog.showMessageDialog(this,"Cannot Find
"+typedText,"Othello",JOptionPane.INFORMATION_MESSAGE);
To fix this error, you can change "this" to "null" or you implements ActionListener interface in a sub-class of Component class. Example:
public class A extends Component // or a sub-class as JDialog or a any class you want
implements ActionListener
public void actionPerformed(ActionEvent e)
if(e.getSource() == findButton)
//your code is placed here
A a = ................
findButton.addActionListener(a); -
Swing ActionListener help?
Hi there,
I'm trying to get to grips with Swing and I'm reasonably comfortable with laying out the GUI now. However, I'm still trying to get to grips with ActionListeners. As I understand it, you can have any old class as an ActionListener as long as it implements the ActionListener interface.....then you can just add this ActionListener to a component using .addActionListener().
Couple of questions though....
1. Is it generally bad design to just have a component call <whatever>.addActionListener(this) and then just implement the actionPerformed() method within the same class?
2. Do you have to define a seperate ActionListener class for each type of component, or can you use one ActionListener for, say, one whole GUI screen? How do you usually organise these things?
3. Anyone point me towards some decent tutorials on Java Swing event-handling?....preferably not the Sun ones, although if they are regarded as the best, I'll take 'em. :)
Thanks for your time.URgent help need.
i need to link the page together : by clicking the button on the index page.
it will show the revelant class file. I have try my ationPerformed method to the actionlistener, it cannot work.
Thanks in advance.
// class mtab
// the tab menu where it display the gui
import javax.swing.*;
import java.awt.*;
public class mtab {
private static final int frame_height = 480;
private static final int frame_width = 680;
public static void main (String [] args){
JFrame frame = new JFrame ("Mrt Timing System");
frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE);
frame.setSize(frame_width,frame_height);
JTabbedPane tp = new JTabbedPane ();
tp.addTab("Mrt Timing System", new sample());
frame.setResizable(false);
frame.getContentPane().add(tp);
frame.setSize(680,480);
frame.show();
// index page
// class sample
import java.awt.*;
import java.awt.event.*;
import java.awt.Image;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.text.*;
import javax.swing.border.*;
class sample extends JPanel implements ActionListener
//button
private JButton TimingButton;
private JButton ViewButton;
private JButton FrequencyButton;
private JButton calculateButton;
private CardLayout mycard;
private JPanel SelectXPanel;
private JPanel SelectYPanel;
private JPanel SelectZPanel;
private JPanel bigFrame, mainPane;
// constructor
public sample() {
super(new BorderLayout());
//create the object
//create button and set it
TimingButton = new JButton("MRT Timing Calculator");
TimingButton.addActionListener(this);
ViewButton = new JButton("View First and Last Train");
ViewButton.addActionListener(this);
FrequencyButton = new JButton("Show the Train Frequency");
FrequencyButton.addActionListener(this);
// Layout
//Lay out the button in a panel.
JPanel buttonPane = new JPanel(new GridLayout(3,0));
buttonPane.add(TimingButton);
buttonPane.add(ViewButton);
buttonPane.add(FrequencyButton);
// Layout the button panel into another panel.
JPanel buttonPane2 = new JPanel(new GridLayout(0,1));
buttonPane2.add(buttonPane);
tfrequency x = new tfrequency();
fviewl2 y = new fviewl2 ();
timing z = new timing ();
JPanel SelectXPanel = new JPanel(new GridLayout(0,1));
SelectXPanel.add(x);
JPanel SelectYPanel = new JPanel(new GridLayout(0,1));
SelectYPanel.add(y);
JPanel SelectZPanel = new JPanel(new GridLayout(0,1));
SelectZPanel.add(z);
// Layout the button by putting in between the rigid area
JPanel mainPane = new JPanel(new GridLayout(3,0));
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.add(buttonPane2);
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.setBorder(new TitledBorder("MRT Timing System"));
// x = new tfrequency();
// The overall panel -- divide the frame into two parts: west and east.
JPanel bigFrame = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
//bigFrame.add(x,BorderLayout.EAST); // this is where i want to link the page
// this page being the index page. there being nothing to display.
add(bigFrame);
//Create the GUI and show it. For thread safety,
public void actionPerformed (ActionEvent e){
if (e.getSource() == TimingButton ){
JPanel bigFrame = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
bigFrame.add(SelectZPanel,BorderLayout.EAST);
add(bigFrame);
else if (e.getSource() == ViewButton ){
JPanel bigFrame = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
bigFrame.add(SelectYPanel,BorderLayout.EAST);
add(bigFrame);
else if (e.getSource() == FrequencyButton ){
JPanel bigFrame2 = new JPanel(new GridLayout(0,2));
bigFrame.add(mainPane, BorderLayout.WEST);
bigFrame.add(SelectXPanel,BorderLayout.EAST);
add(bigFrame);
// Train Frequency Page
// class fviewl2
import java.awt.*;
import java.awt.event.*;
import java.awt.Image;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.text.*;
import javax.swing.border.*;
class fviewl2 extends JPanel implements ActionListener
//Labels to identify the fields
private JLabel stationLabel;
private JLabel firstLabel;
private JLabel lastLabel;
//Strings for the labels
private static String station = "MRT Station:";
private static String first = "First Train Time:";
private static String last = "Last Train Time:";
//Fields for data entry
private JFormattedTextField stationField;
private JFormattedTextField firstField;
private JFormattedTextField lastField;
//button
private JButton homeButton;
private JButton cancelButton;
private JButton calculateButton;
public fviewl2()
super(new BorderLayout());
//create the object
//Create the Labels
stationLabel = new JLabel(station);
firstLabel = new JLabel (first);
lastLabel = new JLabel (last) ;
//Create the text fields .// MRT Station:
stationField = new JFormattedTextField();
stationField.setColumns(10);
stationField.setBounds(300,300,5,5);
//Create the text fields // First Train Time:
firstField = new JFormattedTextField();
firstField.setColumns(10);
firstField.setBounds(300,300,5,5);
//Create the text fields //Last Train Time:
lastField = new JFormattedTextField();
lastField.setColumns(10);
lastField.setBounds(300,300,5,5);
//Tell accessibility tools about label/textfield pairs, matching label for the field
stationLabel.setLabelFor(stationField);
firstLabel.setLabelFor(firstField);
lastLabel.setLabelFor(lastField);
//create button and set it
homeButton = new JButton("Home");
//homeButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
calculateButton = new JButton("Get Time");
// Layout
//MRT Station Label // insert into the panel
JPanel StationPane = new JPanel(new GridLayout(0,1));
StationPane.add(stationLabel);
//MRT Station input field // insert into the panel
JPanel StationInput = new JPanel(new GridLayout(0,1));
StationInput.add(stationField);
//Get Time Button // insert into the panel
JPanel GetTime = new JPanel(new GridLayout(0,1));
GetTime.add(calculateButton);
//Lay out the labels in a panel.
JPanel FlabelL = new JPanel(new GridLayout(0,1));
FlabelL.add(firstLabel);
FlabelL.add(lastLabel);
// Layout the fields in a panel
JPanel FFieldL = new JPanel(new GridLayout(0,1));
FFieldL.add(firstField);
FFieldL.add(lastField);
//Lay out the button in a panel.
JPanel buttonPane = new JPanel(new GridLayout(1,0));
buttonPane.add(homeButton);
buttonPane.add(cancelButton);
// Layout all components in the main panel
JPanel mainPane = new JPanel(new GridLayout(4,2));
mainPane.add(StationPane);
mainPane.add(StationInput);
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.add(GetTime);
mainPane.add(FlabelL);
mainPane.add(FFieldL);
mainPane.add(Box.createRigidArea(new Dimension(0,1)));
mainPane.add(buttonPane);
mainPane.setBorder(new TitledBorder("View First and Last Train"));
JPanel leftPane = new JPanel(new GridLayout(1,0));
leftPane.add(Box.createRigidArea(new Dimension(0,1)));
leftPane.add(mainPane);
leftPane.add(Box.createRigidArea(new Dimension(0,1)));
JPanel hahaFrame = new JPanel(new GridLayout(0,1));
hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
hahaFrame.setBorder(BorderFactory.createEmptyBorder(30, 10, 80, 150));
hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
JPanel bigFrame = new JPanel();
bigFrame.add(hahaFrame, BorderLayout.NORTH);
bigFrame.add(leftPane, BorderLayout.CENTER);
add(bigFrame, BorderLayout.CENTER);
//Create the GUI and show it. For thread safety,
private void cancelButtonClicked()
stationField.setText("");
firstField.setText("");
lastField.setText("");
public void actionPerformed (ActionEvent e){
if (e.getSource() == cancelButton){
cancelButtonClicked();
} -
i m declaring a method with syntax .....
public void addWidgets() {
but the error comes .. illegal start of expression ..... ???
also i m using actionlistener interface in class definition ...
but the error comes .. no actionperformmed method defined ... although i have defined it ..???
''''' i wanna show 2 text fields and when user enters the no. n press swap button the swaped values r shoen in labels '''''''''''
----------------------------- here is the code -----------------
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Swap1 implements ActionListener {
private static String lbl = " becomes : " ;
JFrame frame;
JPanel panel;
JLabel aLabel, blabel;
JTextField aText, bText;
JButton button ;
// Constructor
public Swap1() {
// Create the frame and container
frame = new JFrame ("Swapping two values");
panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
addWidgets();
frame.getContentPane().add(panel,BorderLayout.CENTER);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
// show frame
frame.pack();
frame.setVisible(true);
// Create and add the widgets to the panel
private void addWidgets() {
aLabel = new JLabel(lbl, SwingConstants.CENTER);
bLabel = new JLabel(lbl, SwingConstants.CENTER);
aText = new JTextField(2);
bText = new JTextField(2);
button = new JButton("Swap...");
button.addActionListener(this);
//Adding the widgets to the panel
panel.add(aText);
panel.add(aLabel);
panel.add(bText);
panel.add(bLabel);
panel.add(button);
aLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Implementing the actionlistener
public void actionPerformed(ActionEvent event) {
int a = (int)(Double.parseDouble(aText.getText()));
int b = (int)(Double.parseDouble(bText.getText()));
int c = a;
a = b;
b = c;
aLabel.setText(lbl + a);
bLabel.setText(lbl + b);
// main method
public void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {}
Swap1 sp = new Swap1();DUPLICATE
-
Hi!
I'm having problems with adding ActionListener on JMenuItem. I do it like this:
JMenuItem saveMenuItem = new JMenuItem();
saveMenuItem.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.out.println("actionPerformed!");
saveActionPerformed(e);
});No even when I select that menu item from my GUI, the action is not launched! Compiler does not give any errors, so it should be ok. Can anyone tell me what's the problem?? I'm using JDK 1.3.1-b24, btw.
/jasurakkHi jasurakka,
just reading the source code, nothing seems to be
wrong. May be there's a problem using an adapter class
as listener. I suggest you try to write an own class
implementing the ActionListener interface and then add
this class as ActionListener to your menu items.
Appears to me, that this is anyway the better
solution, cause you create only one ActionListener
listening for all the menu items you're adding instead
of creating a new listener instance for each menu
item. In the latter case, you have to add and check a
unique action command for each item.Yeah, that's pretty much what I had before... But when I couldn't make it work, I tried to add own actionlistener for all menu items. Unfortunately it didn't help at all:=( Might you have any other ideas of what to do? -
Hi !!
I'm a student working on an assignment and I'm kind of stuck here, I hope you guys can help!
I'm trying to invoke one class from another through the use of ActionListener Interface.
I've been using a small example to try make it work but haven't been able to:
This is the class that implements the actionlistener for a button:
import javax.swing.*;
import java.awt.event.*;
public class TrialGui implements ActionListener
JButton button;
//private void run ()
// JTextField txt = new JTextField(10);
//frame.getContentPane().add(txt);
//SW nuevaSW = new SW("It works");
public static void main (String[] args)
TrialGui gui = new TrialGui();
gui.go();
public void go()
JFrame frame = new JFrame();
button = new JButton("Click me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
public void actionPerformed (ActionEvent ae)
//button.run();
button.setSize(200,300);
Now, I would like the button rather than to be resized to launch another class when pressed (this other class has been created in a different .java file) . As you can see I've tried creating the run method for launching the other class but it didn't work.
This is the other class I would like to be fired when pressing the button:
import javax.swing.*; // Contains the JFrame, JButton, etc.
import java.awt.*; //Contains the Border Layout
import java.awt.event.*;// package containing ActionListener and ActionEvent
//import java.util.Hashtable; Was being Used with GraphPaperLayout: Couldn't manage to make it work!
public class SW //implements ActionListener
JButton button1;
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
JButton button8;
// Declare main method
public static void main (String[] args)
/** What can I use to substitute the main. I think that in the programme
* one should not have more than one main method. But I'm not sure what
* to call this method or how it will influence the rest of the code.
// Creates an instance of SecondWindow
SW gui = new SW();
gui.go();
public void go()
// Generate frame and panels + look and feel
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Campaign Details");
JPanel panel1 = new JPanel(); // To occupy northern region of frame layout
JPanel panel2 = new JPanel(); // To occupy central region of frame layout
JPanel panel3 = new JPanel(); // To occupy southern region of frame layout
GridBagLayout gbl = new GridBagLayout();//Generates layout for panel2
// Generate the necessary buttons
button1 = new JButton("GO");
button2 = new JButton("Edit"); // times 3
/** Can I add the same button (button2) three times to the same panel and yet assign
* each different functions? they would all be edit buttons but
* they will be editing different parametersof the campaign
button3 = new JButton("Add Keywords");
button4 = new JButton("New Campaign");
button5 = new JButton("Log Out");
button6 = new JButton("Refresh");
button7 = new JButton("Edit");
button8 = new JButton("Edit");
// Generate the necessary txtAreas
JTextArea txtArea1 = new JTextArea(1,4);
JTextArea txtArea2 = new JTextArea(1,4);
JTextArea txtArea3 = new JTextArea(1,4);
JTextArea txtArea4 = new JTextArea(1,4);
JTextArea txtArea5 = new JTextArea(1,4);
JTextArea txtArea6 = new JTextArea(1,4);
JTextArea txtArea7 = new JTextArea(1,4);
JTextArea txtArea8 = new JTextArea(1,4);
JTextArea txtArea9 = new JTextArea(1,4);
/** Need to ask whether the data that will be
* downloaded from the google server can be displayed on a
* JTextField or do I need some other thing for displaying it?
* I found the JTextArea but I don't know how appropriate this is.
// Generate the necessary labels
JLabel label1 = new JLabel("Select Campaign:");
JLabel label2 = new JLabel("Impressions:");
JLabel label3 = new JLabel("Clicks:");
JLabel label4 = new JLabel("Budget:");
JLabel label5 = new JLabel("Monthly");
JLabel label6 = new JLabel("Daily");
JLabel label7 = new JLabel("Keywords:");
JLabel label8 = new JLabel("Popularity");
JLabel label9 = new JLabel("Avg.\nCPC");// how do I make it two lines?? /que?
JLabel label10 = new JLabel("Cost");
//Generate the necessary Drop Down Menus
String[] items = {"ApoyoVenezuela", "Other Campaign", "..."};
JComboBox editableCB1 = new JComboBox(items);
//editableCB1.setEditable(true);
String[] items2 = {"Venezuela", "hugo chavez", "ApoyoVenezuela", "..."};
JComboBox editableCB2 = new JComboBox(items2);
//editableCB2.setEditable(true);
// What class can I use to generate these menues???
// Defines format of fonts to be used
Font bigFont = new Font("Courrier New", Font.PLAIN, 12);
Font smallFont = new Font("Courrier New", Font.PLAIN, 9);
Font boldBigFont = new Font("Courrier New", Font.BOLD, 15);
Font boldSmallFont = new Font("Courrier New", Font.BOLD, 10);
// Assign fonts to differet components
button1.setFont(smallFont);
button2.setFont(smallFont);
button3.setFont(bigFont);
button4.setFont(bigFont);
button5.setFont(bigFont);
button6.setFont(bigFont);
button7.setFont(smallFont);
button8.setFont(smallFont);
label1.setFont(bigFont);
label2.setFont(boldBigFont);
label3.setFont(boldBigFont);
label4.setFont(boldBigFont);
label5.setFont(boldSmallFont);
label6.setFont(boldSmallFont);
label7.setFont(boldBigFont);
label8.setFont(boldSmallFont);
label9.setFont(boldSmallFont);
label10.setFont(boldSmallFont);
//Assign ActionListener Fuctionality to buttons
//button1.addActionListener(this);
//button2.addActionListener(this);
//button3.addActionListener(this);
//button4.addActionListener(this);
//button5.addActionListener(this);
//button6.addActionListener(this);
//button7.addActionListener(this);
//button8.addActionListener(this);
// Format frame and panels
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//atmtclly ends Prgmm on clsing the frame
frame.getContentPane().add(BorderLayout.NORTH, panel1);//fit panels inside the frame
frame.getContentPane().add(BorderLayout.CENTER, panel2);
frame.getContentPane().add(BorderLayout.SOUTH, panel3);
panel1.setBackground(Color.yellow); // set panels background colour
panel2.setBackground(Color.blue);
panel3.setBackground(Color.red);
panel2.setLayout(gbl); // Assign gbl layout created above
//Set constraints for gbc
GridBagConstraints gbc = new GridBagConstraints();
//Components spanning three columnsand aligned to the left (west)
gbc.gridwidth = 3;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 0;
gbc.gridy = 1;
gbl.setConstraints(label4, gbc);
panel2.add(label4);
gbc.gridx = 0;
gbc.gridy = 2;
gbl.setConstraints(label2, gbc);
panel2.add(label2);
gbc.gridx = 0;
gbc.gridy = 3;
gbl.setConstraints(label3, gbc);
panel2.add(label3);
gbc.gridx = 0;
gbc.gridy = 4;
gbl.setConstraints(label7, gbc);
panel2.add(label7);
gbc.gridx = 0;
gbc.gridy = 6;
gbl.setConstraints(button3, gbc);
panel2.add(button3);
gbc.gridx = 0;
gbc.gridy = 5;
gbl.setConstraints(editableCB2, gbc);
panel2.add(editableCB2);
//Sets back 2 column spanning and aligns back to the centre
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 1;
gbc.gridx = 3;
gbc.gridy = 0;
gbl.setConstraints(label5, gbc);
panel2.add(label5);
gbc.gridx = 4;
gbc.gridy = 0;
gbl.setConstraints(label6, gbc);
panel2.add(label6);
gbc.gridx = 3;
gbc.gridy = 4;
gbl.setConstraints(label8, gbc);
panel2.add(label8);
gbc.gridx = 4;
gbc.gridy = 4;
gbl.setConstraints(label9, gbc);
panel2.add(label9);
gbc.gridx = 5;
gbc.gridy = 4;
gbl.setConstraints(label10, gbc);
panel2.add(label10);
gbc.gridx = 5;
gbc.gridy = 1;
gbl.setConstraints(button2, gbc);
panel2.add(button2);
gbc.gridx = 4;
gbc.gridy = 6;
gbl.setConstraints(button7, gbc);
panel2.add(button7);
gbc.gridx = 5;
gbc.gridy = 6;
gbl.setConstraints(button8, gbc);
panel2.add(button8);
gbc.gridx = 3;
gbc.gridy = 1;
gbl.setConstraints(txtArea1, gbc);
panel2.add(txtArea1);
gbc.gridx = 3;
gbc.gridy = 2;
gbl.setConstraints(txtArea3, gbc);
panel2.add(txtArea3);
gbc.gridx = 3;
gbc.gridy = 3;
gbl.setConstraints(txtArea5, gbc);
panel2.add(txtArea5);
gbc.gridx = 3;
gbc.gridy = 5;
gbl.setConstraints(txtArea7, gbc);
panel2.add(txtArea7);
gbc.gridx = 4;
gbc.gridy = 1;
gbl.setConstraints(txtArea2, gbc);
panel2.add(txtArea2);
gbc.gridx = 4;
gbc.gridy = 2;
gbl.setConstraints(txtArea4, gbc);
panel2.add(txtArea4);
gbc.gridx = 4;
gbc.gridy = 3;
gbl.setConstraints(txtArea6, gbc);
panel2.add(txtArea6);
gbc.gridx = 4;
gbc.gridy = 5;
gbl.setConstraints(txtArea8, gbc);
panel2.add(txtArea8);
gbc.gridx = 5;
gbc.gridy = 5;
gbl.setConstraints(txtArea9, gbc);
panel2.add(txtArea9);
panel1.add(label1);
panel1.add(editableCB1);
panel1.add(button1);
panel3.add(button6);
panel3.add(button4);
panel3.add(button5);
// Set frame dimensions and make it visible
frame.setSize(320,300);
frame.setVisible(true);
//Set actions for the ActionListener enabled buttons
//public void actionPerformed (ActionEvent ae)
//button1.
Thank you very much for your help, I really appreciate it.
CheersThanx for yout pronpt reply!!
I've added
SW sw = new SW();
to the actionPerformed method and it seems to actually invoke the SW class. I've also added the following method to the SW class
public SW()
//build the GUI here, or call a method that builds it from here
SW sw2 = new SW();
but when I run it I get some error which I can't understand. I'm using the cmd to compile and execute and can't read the first lines of teh error. The only line of the error I can see is:
at SW.<init>(SW.java:22)
which keeps on repeating untill I stop the programme from running
To be sincere I'm confused with all this code and I'm no quite sure what method to use to make it work.
Please help!! :-)
Cheers -
I am working on a Java program for a PDA Touchscreen editor, but the actionListner is not working.
The program is running but none of the keys are working on the user interface.Also...
I'll offer pseudocode:
class MyClass implements ActionListener{
private Button butt;
public MyClass(...)
//yadda yadda
public void run()
//assume 'butt' has been init'd
butt.addActionListener(this);
public void actionPerformed(ActionEvent ae)
//this method must be implemented because we implemented the ActionListener interface
Object o = ae.getSource();
if (o == butt)
//do whatever
}Also..you've asked for help..post the code that you've tried here..asking for someone to email you offline means that when the next person who asks this question (if they were to bother to search the forum archives anyway) and searches for this problem, would have an answer without having to ask a question...
It's all about the community.
You DID check the forums to see if anyone else in the history of Java programming had asked how to add an ActionListener to a Button, right? -
Can I instantiate ActionListener like a class ?
Hi All :
If ActionListener is an interface, how come I can code something like this : ActionListener l = new ActionListener() {
}; which is performing fine.
As far my knowledge goes an interface can't be instantiated.
Thanks in advance
AtanuHi,
Your knowledge is correct, that the interfaces cannot be instantiated. and this code is also perfect. No errors. This is just a shortcut way of creating a subclass and instatiating it, known as Anonymous Inner Class.
ActionListener l = new ActionListener() {
}is just creating an object of the subclass or a class which implements the ActionListener interface and returns a reference to it. This could also be written as..
class MyActionListener implements ActionListener {
//somewhere in your program.....
MyActionListener l = new MyActionListener();With only one difference, in the former case, u cannot give the name u choose to the new class while in the latter u can give any name u want.
regards,
DeeJay -
When should one use interfaces?
Actually, I don't get interfaces at all. From what I understand, all an interface does is make sure that a class which implements the interface has certain methods. If someone could explain interfaces, it would be appreciated,
I am thinking of making a small game, and I was wondering if it would be good to use intefaces with my sprites, for example enemies and the player character sprites would implement Damageable, while a weapon, or some element which causes damage would not be Damageable. Is there a better way to set this up?
Thankswhenever I click the button, voila! the
actionPerformed method is called. How does that all
work?It works because code, working behind the scenes, is written to assume objects of the interface type.
The ActionListener interface specifies actionPerformed. You supply an object implementing the ActionListener interface which means it implements all methods the interface specifies. You then give that object to a JButton object. Later, when the button is pressed, the JButton object calls actionPerformed of the ActionListener object you gave to it. -
Hi everybody,
i�m a beginner programming JAVA. So i think the question will be so easy.
How can I add an action to a button created on a container???
i.e. i want that when pressing the button, a word document can be opened.
thank you very much in advance.hi,
you need to add a listener to the button such as an actionlistener:
JButton button1 = new JButton();
button1.addActionListener(new buttonListener());
// This should be an inner class
class buttonListener implements ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Event generated!");
}you an use an inner class to handle the event, pass the addActionlistener an object of the inner class, the inner class here should implement the actionlistener interface which has the actionPerformed method. You need a listener, best place to find one is the API. -
JLabel in Rules class won't display
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import Graphics.DrawFrame;
public class Caller { //driver class
public static void main(String[] args) { //main method
int width = 350; //sets width to 350 pixels
int height = 150; //sets height to 150 pixels
Toolkit toolkit = Toolkit.getDefaultToolkit(); //creates a Toolkit object
Dimension dim = toolkit.getScreenSize(); //creates a Dimension object and stores the screen size
do {
//DrawFrame.setDefaultLookAndFeelDecorated(true); //decorates the look and feel
DrawFrame frame = new DrawFrame((dim.width-width)/2, (dim.height-height)/2, width, height, "How to Play"); //creates an instance of DrawFrame and sets it in the center of the screen with a height of 300 and a width of 300
JButton rules = new JButton("Play"); //creates a newJButton with the text "play"
JLabel label = new JLabel("<html>Press ENTER to call a new number.<br>Press R to reset game.<br> The game resets if all 75 numbers have been called.<br> Press H to see this screen again.<br> Click the button or press ENTER to start.", SwingConstants.CENTER); //creates a JLabel that explains the game and centers it in the frame
frame.panel.add(label); //adds the label to the frame
label.setOpaque(true); //sets the label as opaque
label.setVisible(true); //makes the label visible
frame.panel.add(rules); //adds the button to the frame
rules.setOpaque(true); //sets the button to opaque
rules.setVisible(true); //makes the button visible
ButtonListener button = new ButtonListener(); //creates instance of ButtonListener class
rules.addActionListener(button); //adds an Action Listener to the button
frame.getRootPane().setDefaultButton(rules); //sets button as default button (clicks button when user hits ENTER
frame.setVisible(true);
while (button.source != rules) {//loops if the source of the ActionEvent wasn't the button
label.repaint(); //repaints the label
rules.repaint(); //repaints the button
frame.dispose(); //deletes the frame when the button is clicked
Bingo.bingoCaller(); //calls the method in the bingo class
} while(true); //loops indefinitely
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonListener implements ActionListener { //class implements ActionListener interface
public Object source; //creates an object of type Object
public void actionPerformed(ActionEvent e) { //actionPerformed method that has an ActionEvent ofject as an argument
source = e.getSource(); //sets the source of the ActionEvent to source
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import Graphics.*;
public class Bingo {
static Ball balls[][] = new Ball[5][15]; //creates a 2D 5 by 15 array
public static void bingoCaller() {
//DrawFrame.setDefaultLookAndFeelDecorated(true); //decorates the look and feel
int width = 1250; //sets width to 1250 pixels
int height = 500; //sets height to 500 pixels
Toolkit toolkit = Toolkit.getDefaultToolkit(); //creates a Toolkit object
Dimension dim = toolkit.getScreenSize(); //creates a Dimension object and sets the it as the screen size
DrawFrame frame = new DrawFrame((dim.width-width)/2, (dim.height-height)/2, width, height, "Automated BINGO Caller"); //creates instance of DrawFrame that is 1250 pixel wide and 500 pixels high at the center of the screen
Graphics g = frame.getGraphicsEnvironment(); //calls the getGraphicsEnvironment method in the DrawFrame class
Keys key = new Keys(); //creates instance of the Keys class
frame.addKeyListener(key); //adds a KeyListener called Key
for (int x = 0; x < 5; x++) { //fills rows
for (int y = 0; y < 15; y++) { //fills columns
balls[x][y] = new Ball(x, y+1); //fills array
frame.pack(); //adjusts the size of the frame so everything fits
g.setColor(Color.black); //sets the font color of the letters to black
g.setFont(new Font("MonoSpace", Font.BOLD, 50)); //creates new font
for(int y=0;y<balls.length;y++){ //draws all possible balls
g.drawString(balls[y][0].s, 0, y*100+50); //draws numbers
for(int x=0;x<balls[y].length;x++){ //draws all possible balls
g.drawString(Integer.toString(balls[y][x].i), (x+1)*75, y*100+50); //draws letters
frame.repaint(); //repaints numbers
do {
int x, y; //sets variables x and y as integers
int count = 0; //sets a count for the number of balls called
boolean exit; //sets a boolean to the exit variable
do {
exit = false; //exit is set to false
x = (int)(Math.random() * 5); //picks a random number between 0 and 4 and stores it as x
y = (int)(Math.random() * 15); //picks a random number between 0 and 14 stores it as y
if (!balls[x][y].called) { //checks to see if a value is called
exit = true; //changes exit to true if it wasn't called
balls[x][y].called = true; //sets called in the Ball class to true if it wasn't called
} while (!exit&&count<5*15); //if exit is false, and count is less than 75returns to top of loop
for(int z=0;z<balls.length;z++){ //looks at balls
g.setColor(Color.black); //displays in black
g.drawString(balls[z][0].s, 0, z*100+50); //draws balls as a string
for(int a=0;a<balls[z].length;a++){ //looks at all balls
if (balls[z][a].called){ //if a ball is called
g.setColor(Color.red); //change color to red
count++; //increments count
} else {
g.setColor(Color.white); //if it isn't called stay white
g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //draws balls as string
boolean next=false; //initiates boolean value next and sets it to false
frame.repaint(); //repaints the balls when one is called
while(!next) {
try {
Thread.sleep(100); //pauses the thread for 0.1 seconds so it can register the key pressed
} catch (InterruptedException e) {
e.printStackTrace(); //if it is interrupted it throws an exception and it is caught and the stack trace is printed
if(key.keyPressed==KeyEvent.VK_ENTER){ //if Enter is pressed
next=true; //next is set to true
key.keyPressed=0; //keypressed value is reset to 0
}else if (key.keyPressed == KeyEvent.VK_H) {
new Rules();
key.keyPressed = 0;
} else if (key.keyPressed == KeyEvent.VK_R) { //if R is pressed
key.keyPressed=0; //keypressed is reset to 0
next=true; //next is set to true
count=5*15; //changes count to 5*15
for(int z=0;z<balls.length;z++){ //recreates rows
g.setColor(Color.white); //sets color to white
g.drawString(balls[z][0].s, 0, z*100+50); //redraws rows
for(int a=0;a<balls[z].length;a++){ //recreates columns
balls[z][a] = new Ball(z, a+1); //fills array
g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //redraws columns
if (count==5*15) { //if count = 5*15
for(int z=0;z<balls.length;z++){ //recreates rows
g.setColor(Color.white); //sets color to white
g.drawString(balls[z][0].s, 0, z*100+50); //redraws rows
for(int a=0;a<balls[z].length;a++){ //recreates columns
balls[z][a] = new Ball(z, a+1); //fills array
g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //redraws columns
} while (true); //infinite loop only terminates program when the close button is clicked
package Graphics;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawFrame extends JFrame{
public Panel panel; //creates a variable called panel of type Panel
public DrawFrame(int width, int height, String s) { //constructor for size and title
super(s); //gets s from class that calls it
this.setBounds(0, 0, width, height); //sets size of component
initial(); //calls method initial
public DrawFrame(int x, int y, int width, int height, String s) { //second constructor for size, title, and where on the screen it appears
super(s); //gets title from the class that calls it
this.setBounds(x, y, width, height); //sets size of component
initial(); //calls method initial
void initial() {
this.setResizable(false); //disables resizing of window
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminates program if close button is pressed
this.setPreferredSize(getSize()); //gets the size and set the preferred size
panel = this.getPanel(); //gets the an instance of the Panel class and store the reference in panel
this.getContentPane().add(panel); //adds panel to the frame
this.setVisible(true); //makes the frame visible
panel.init(); //calls the init method form the Panel class
public Graphics getGraphicsEnvironment(){ //return type of Panel for method getGraphicsEnvironment
return panel.getGraphicsEnvironment(); //returns the GraphicsEnvironment from class Panel
Panel getPanel(){ //method getPanel with return type of Panel
return new Panel(); //returns a new instance of the Panel class
package Graphics;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawFrame2 extends JFrame{
public Panel panel; //creates a variable called panel of type Panel
public DrawFrame2(int width, int height, String s) { //constructor for size and title
super(s); //gets s from class that calls it
this.setBounds(0, 0, width, height); //sets size of component
initial(); //calls method initial
public DrawFrame2(int x, int y, int width, int height, String s) { //second constructor for size, title, and where on the screen it appears
super(s); //gets title from the class that calls it
this.setBounds(x, y, width, height); //sets size of component
initial(); //calls method initial
void initial() {
this.setResizable(false); //disables resizing of window
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //terminates program if close button is pressed
this.setPreferredSize(getSize()); //gets the size and set the preferred size
panel = this.getPanel(); //gets the an instance of the Panel class and store the reference in panel
this.getContentPane().add(panel); //adds panel to the frame
this.setVisible(true); //makes the frame visible
panel.init(); //calls the init method form the Panel class
public Graphics getGraphicsEnvironment(){ //return type of Panel for method getGraphicsEnvironment
return panel.getGraphicsEnvironment(); //returns the GraphicsEnvironment from class Panel
Panel getPanel(){ //method getPanel with return type of Panel
return new Panel(); //returns a new instance of the Panel class
package Graphics;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
public class Panel extends JPanel{
Graphics g; //initiates variable g as type Graphics
Image image; //initiates variable image as type Image
public void init() {
image = this.createImage(this.getWidth(), this.getHeight()); //creates the image with the specified height and stores it as image
g = image.getGraphics(); //uses the getGraphics method from the Image class and stores it as g
g.setColor(Color.white); //sets the color of g to white
g.fillRect(0, 0, this.getWidth(), this.getHeight()); //fills the rectangle
Graphics getGraphicsEnvironment() { //method getGraphicsEnvironment with return type Graphics
return g; //returns g
public void paint(Graphics graph) { //overrides the paint method and passes the argument graph of type Graphics
if (graph == null) //if there is nothing in graph
return; //return
if (image == null) { //if there is nothing in image
return; //return
graph.drawImage(image, 0, 0, this); //draws the image
package Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Keys extends KeyAdapter{
public int keyPressed; //creates a variable keyPressed that stores an integer
public void keyPressed(KeyEvent e) { //creates a KeyEvent from a KeyListner
keyPressed = e.getKeyCode(); //gets the key from the keyboard
public class Ball {
String s; //initiates s that can store data type String
int i; //initiates i that can store data as type integer
boolean called = false; //initiates called as a boolean value and sets it to false
public Ball(int x, int y) {
i = (x * 15) + y; //stores number as i to be passed to be printed
switch (x) { //based on x value chooses letter
case 0: //if x is 0
s = "B"; //sets s to B
break; //breaks out of switch case
case 1: //if x is 1
s = "I"; //sets s to I
break; //breaks out of switch case
case 2: //if x is 2
s = "N"; //sets s to N
break; //breaks out of switch case
case 3: //if x is 3
s = "G"; //sets s to G
break; //breaks out of switch case
case 4: //if x is 4
s = "O"; //sets s to O
public String toString() { //overrides toString method, converts answer to String
return s + " " + i; //returns to class bingo s and i
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import Graphics.DrawFrame2;
public class Rules {
public Rules() {
int width = 350;
int height = 150;
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dim = toolkit.getScreenSize();
DrawFrame2 frame = new DrawFrame2((dim.width-width)/2, (dim.height-height)/2, width, height, "How to Play");
JLabel label = new JLabel("<html>Press ENTER to call a new number.<br> Press R to reset game.<br> The game resets if all 75 numbers have been called.<br> Press H to see this scrern again.", SwingConstants.CENTER);
frame.panel.add(label);
label.setOpaque(true);
label.setVisible(true);
frame.setVisible(true);
I created this program to call bingo numbers. When you start the program a small frame appears that tells you how to use the program. When you click the button that frame is disposed and a new one appears that call the numbers. Both of these frames have code in them that will find the dimensions of your screen and put the frames in the center. When you press enter a new number is called by changing the number from white (same color as background) to red. Once all 75 numbers have been called it resets the game. If you press R at anytime during the game the game resets. I had wanted to create a new frame that would display how to play in the middle of the game. It had to be different than the one at the beginning where it doesn't have the button and it isn't in the driver class (class Caller). If you press H at anytime after it starts calling numbers the new frame will be displayed. I have a class (DrawFrame) that extends JFrame but that had the default close operation set to EXIT_ON_CLOSE and I didn't want the program to terminate when the user clicked the x in the how to play frame. I created DrawFrame2 to solve this problem where the only line of code that is different is that the default close operation is DISPOSE_ON_CLOSE. The name of the class I used for the new how to play frame is Rules. The code in this class should work but for some reason the JLabel isn't displaying. Can someone please help me out?I just copied the code from class Caller into Rules and reworked it a bit and it worked.
-
Why do the menus diseappear? please help.....
I am quite new to Java and I use project builder on my mac running OSX. Anyway I found some sample code and I was wondering if anybody could help me out. Basically when the app is compiled it draws "Hello World" in the window and there are two menus in the menubar -> 'File' and 'Edit', but when you go to the about box the menus disappear until you either close the aboutbox or bring the focus back to the main window.
How can I always keep the menus showing when there are multiple windows in the app. Remember that mac menus are fixed to the top of the screen...
anyway heres the code:
import java.awt.*;
import java.awt.event.*;
import com.apple.mrj.*;
import javax.swing.*;
public class test extends JFrame
implements ActionListener,
MRJAboutHandler,
MRJQuitHandler
static final String message = "Hello World!";
private Font font = new Font("serif", Font.ITALIC+Font.BOLD, 36);
protected AboutBox aboutBox;
// Declarations for menus
static final JMenuBar mainMenuBar = new JMenuBar();
static final JMenu fileMenu = new JMenu("File");
protected JMenuItem miNew;
protected JMenuItem miOpen;
protected JMenuItem miClose;
protected JMenuItem miSave;
protected JMenuItem miSaveAs;
static final JMenu editMenu = new JMenu("Edit");
protected JMenuItem miUndo;
protected JMenuItem miCut;
protected JMenuItem miCopy;
protected JMenuItem miPaste;
protected JMenuItem miClear;
protected JMenuItem miSelectAll;
public void addFileMenuItems() {
miNew = new JMenuItem ("New");
miNew.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.Event.META_MASK));
fileMenu.add(miNew).setEnabled(true);
miNew.addActionListener(this);
miOpen = new JMenuItem ("Open...");
miOpen.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Event.META_MASK));
fileMenu.add(miOpen).setEnabled(true);
miOpen.addActionListener(this);
miClose = new JMenuItem ("Close");
miClose.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.Event.META_MASK));
fileMenu.add(miClose).setEnabled(true);
miClose.addActionListener(this);
miSave = new JMenuItem ("Save");
miSave.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.META_MASK));
fileMenu.add(miSave).setEnabled(true);
miSave.addActionListener(this);
miSaveAs = new JMenuItem ("Save As...");
fileMenu.add(miSaveAs).setEnabled(true);
miSaveAs.addActionListener(this);
mainMenuBar.add(fileMenu);
public void addEditMenuItems() {
miUndo = new JMenuItem("Undo");
miUndo.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.Event.META_MASK));
editMenu.add(miUndo).setEnabled(true);
miUndo.addActionListener(this);
editMenu.addSeparator();
miCut = new JMenuItem("Cut");
miCut.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.Event.META_MASK));
editMenu.add(miCut).setEnabled(true);
miCut.addActionListener(this);
miCopy = new JMenuItem("Copy");
miCopy.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.Event.META_MASK));
editMenu.add(miCopy).setEnabled(true);
miCopy.addActionListener(this);
miPaste = new JMenuItem("Paste");
miPaste.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.Event.META_MASK));
editMenu.add(miPaste).setEnabled(true);
miPaste.addActionListener(this);
miClear = new JMenuItem("Clear");
editMenu.add(miClear).setEnabled(true);
miClear.addActionListener(this);
editMenu.addSeparator();
miSelectAll = new JMenuItem("Select All");
miSelectAll.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.Event.META_MASK));
editMenu.add(miSelectAll).setEnabled(true);
miSelectAll.addActionListener(this);
mainMenuBar.add(editMenu);
public void addMenus() {
addFileMenuItems();
addEditMenuItems();
setJMenuBar (mainMenuBar);
public test() {
super("test");
this.getContentPane().setLayout(null);
addMenus();
aboutBox = new AboutBox();
Toolkit.getDefaultToolkit();
MRJApplicationUtils.registerAboutHandler(this);
MRJApplicationUtils.registerQuitHandler(this);
setVisible(true);
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.blue);
g.setFont (font);
g.drawString(message, 40, 80);
public void handleAbout() {
aboutBox.setResizable(false);
aboutBox.setVisible(true);
aboutBox.show();
public void handleQuit() {
System.exit(0);
// ActionListener interface (for menus)
public void actionPerformed(ActionEvent newEvent) {
if (newEvent.getActionCommand().equals(miNew.getActionCommand())) doNew();
else if (newEvent.getActionCommand().equals(miOpen.getActionCommand())) doOpen();
else if (newEvent.getActionCommand().equals(miClose.getActionCommand())) doClose();
else if (newEvent.getActionCommand().equals(miSave.getActionCommand())) doSave();
else if (newEvent.getActionCommand().equals(miSaveAs.getActionCommand())) doSaveAs();
else if (newEvent.getActionCommand().equals(miUndo.getActionCommand())) doUndo();
else if (newEvent.getActionCommand().equals(miCut.getActionCommand())) doCut();
else if (newEvent.getActionCommand().equals(miCopy.getActionCommand())) doCopy();
else if (newEvent.getActionCommand().equals(miPaste.getActionCommand())) doPaste();
else if (newEvent.getActionCommand().equals(miClear.getActionCommand())) doClear();
else if (newEvent.getActionCommand().equals(miSelectAll.getActionCommand())) doSelectAll();
public void doNew() {}
public void doOpen() {}
public void doClose() {}
public void doSave() {}
public void doSaveAs() {}
public void doUndo() {}
public void doCut() {}
public void doCopy() {}
public void doPaste() {}
public void doClear() {}
public void doSelectAll() {}
public static void main(String args[]) {
new test();
}������������������������������������������
and the coe of the aboutbox
������������������������������������������
// File: AboutBox.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AboutBox extends JFrame
implements ActionListener
protected JButton okButton;
protected JLabel aboutText;
public AboutBox() {
super();
this.getContentPane().setLayout(new BorderLayout(15, 15));
this.setFont(new Font ("SansSerif", Font.BOLD, 14));
aboutText = new JLabel ("About test");
JPanel textPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
textPanel.add(aboutText);
this.getContentPane().add (textPanel, BorderLayout.NORTH);
okButton = new JButton("OK");
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
buttonPanel.add (okButton);
okButton.addActionListener(this);
this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
this.pack();
public void actionPerformed(ActionEvent newEvent) {
setVisible(false);
}thanksWhy not make the about box a dialog in the frame which initially has setVisible(false) and only appears when required by chaning this to true, then back to false on closing.
That way it shouldn't interfere with the menus, as it is always there, just not always visible... -
Why do the menus disappear?
I am quite new to Java and I use project builder on my mac running OSX. Anyway I found some sample code and I was wondering if anybody could help me out. Basically when the app is compiled it draws "Hello World" in the window and there are two menus in the menubar -> 'File' and 'Edit', but when you go to the about box the menus disappear until you either close the aboutbox or bring the focus back to the main window.
How can I always keep the menus showing when there are multiple windows in the app. Remember that mac menus are fixed to the top of the screen...
anyway heres the code:
import java.awt.*;
import java.awt.event.*;
import com.apple.mrj.*;
import javax.swing.*;
public class test extends JFrame
implements ActionListener,
MRJAboutHandler,
MRJQuitHandler
static final String message = "Hello World!";
private Font font = new Font("serif", Font.ITALIC+Font.BOLD, 36);
protected AboutBox aboutBox;
// Declarations for menus
static final JMenuBar mainMenuBar = new JMenuBar();
static final JMenu fileMenu = new JMenu("File");
protected JMenuItem miNew;
protected JMenuItem miOpen;
protected JMenuItem miClose;
protected JMenuItem miSave;
protected JMenuItem miSaveAs;
static final JMenu editMenu = new JMenu("Edit");
protected JMenuItem miUndo;
protected JMenuItem miCut;
protected JMenuItem miCopy;
protected JMenuItem miPaste;
protected JMenuItem miClear;
protected JMenuItem miSelectAll;
public void addFileMenuItems() {
miNew = new JMenuItem ("New");
miNew.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.Event.META_MASK));
fileMenu.add(miNew).setEnabled(true);
miNew.addActionListener(this);
miOpen = new JMenuItem ("Open...");
miOpen.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Event.META_MASK));
fileMenu.add(miOpen).setEnabled(true);
miOpen.addActionListener(this);
miClose = new JMenuItem ("Close");
miClose.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.Event.META_MASK));
fileMenu.add(miClose).setEnabled(true);
miClose.addActionListener(this);
miSave = new JMenuItem ("Save");
miSave.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.META_MASK));
fileMenu.add(miSave).setEnabled(true);
miSave.addActionListener(this);
miSaveAs = new JMenuItem ("Save As...");
fileMenu.add(miSaveAs).setEnabled(true);
miSaveAs.addActionListener(this);
mainMenuBar.add(fileMenu);
public void addEditMenuItems() {
miUndo = new JMenuItem("Undo");
miUndo.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.Event.META_MASK));
editMenu.add(miUndo).setEnabled(true);
miUndo.addActionListener(this);
editMenu.addSeparator();
miCut = new JMenuItem("Cut");
miCut.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.Event.META_MASK));
editMenu.add(miCut).setEnabled(true);
miCut.addActionListener(this);
miCopy = new JMenuItem("Copy");
miCopy.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.Event.META_MASK));
editMenu.add(miCopy).setEnabled(true);
miCopy.addActionListener(this);
miPaste = new JMenuItem("Paste");
miPaste.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.Event.META_MASK));
editMenu.add(miPaste).setEnabled(true);
miPaste.addActionListener(this);
miClear = new JMenuItem("Clear");
editMenu.add(miClear).setEnabled(true);
miClear.addActionListener(this);
editMenu.addSeparator();
miSelectAll = new JMenuItem("Select All");
miSelectAll.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.Event.META_MASK));
editMenu.add(miSelectAll).setEnabled(true);
miSelectAll.addActionListener(this);
mainMenuBar.add(editMenu);
public void addMenus() {
addFileMenuItems();
addEditMenuItems();
setJMenuBar (mainMenuBar);
public test() {
super("test");
this.getContentPane().setLayout(null);
addMenus();
aboutBox = new AboutBox();
Toolkit.getDefaultToolkit();
MRJApplicationUtils.registerAboutHandler(this);
MRJApplicationUtils.registerQuitHandler(this);
setVisible(true);
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.blue);
g.setFont (font);
g.drawString(message, 40, 80);
public void handleAbout() {
aboutBox.setResizable(false);
aboutBox.setVisible(true);
aboutBox.show();
public void handleQuit() {
System.exit(0);
// ActionListener interface (for menus)
public void actionPerformed(ActionEvent newEvent) {
if (newEvent.getActionCommand().equals(miNew.getActionCommand())) doNew();
else if (newEvent.getActionCommand().equals(miOpen.getActionCommand())) doOpen();
else if (newEvent.getActionCommand().equals(miClose.getActionCommand())) doClose();
else if (newEvent.getActionCommand().equals(miSave.getActionCommand())) doSave();
else if (newEvent.getActionCommand().equals(miSaveAs.getActionCommand())) doSaveAs();
else if (newEvent.getActionCommand().equals(miUndo.getActionCommand())) doUndo();
else if (newEvent.getActionCommand().equals(miCut.getActionCommand())) doCut();
else if (newEvent.getActionCommand().equals(miCopy.getActionCommand())) doCopy();
else if (newEvent.getActionCommand().equals(miPaste.getActionCommand())) doPaste();
else if (newEvent.getActionCommand().equals(miClear.getActionCommand())) doClear();
else if (newEvent.getActionCommand().equals(miSelectAll.getActionCommand())) doSelectAll();
public void doNew() {}
public void doOpen() {}
public void doClose() {}
public void doSave() {}
public void doSaveAs() {}
public void doUndo() {}
public void doCut() {}
public void doCopy() {}
public void doPaste() {}
public void doClear() {}
public void doSelectAll() {}
public static void main(String args[]) {
new test();
}������������������������������������������
and the coe of the aboutbox
������������������������������������������
// File: AboutBox.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AboutBox extends JFrame
implements ActionListener
protected JButton okButton;
protected JLabel aboutText;
public AboutBox() {
super();
this.getContentPane().setLayout(new BorderLayout(15, 15));
this.setFont(new Font ("SansSerif", Font.BOLD, 14));
aboutText = new JLabel ("About test");
JPanel textPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
textPanel.add(aboutText);
this.getContentPane().add (textPanel, BorderLayout.NORTH);
okButton = new JButton("OK");
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
buttonPanel.add (okButton);
okButton.addActionListener(this);
this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
this.pack();
public void actionPerformed(ActionEvent newEvent) {
setVisible(false);
}thanksplease anyone wanna help me?
-
Java Calendar Help Needed :)
Hi,
I am trying to develop a Java Event Calendar which is able to display the calendar weekly. So the JPanel will be setup with 7 JLists for the days of the week. Buttons will allow switching of the days of the week, months and year.
Each JList corresponding to the day of the week will have its data obtained from the database using JDBC and loaded upon 're-drawing' of the lists.
However i am having trouble with the GUI side in understanding how to implement this, i am confident with the JList and database side of things, i have just used a similar example using the Calendar API for monthly displays, however i am unsure how to convert this to a weekly calendar.
Ideally 7 JLists will always be available in the panel in order M,T,W,T,F,S,S but some will be set to inactive (for example in the first and last weeks of the month).
If anyone has any suggestions please could you help me out :)
Sorry if what im trying to do is a bit confusing.
I've included the code i've been using for the monthly calendar
THANKS!!
public class CalendarPanel extends JPanel implements ActionListener {
private Calendar panelDate;
private Label monthLabel;
private Label yearLabel;
private Panel daysPanel;
private Vector calendarListeners;
private static final String days[] = {"S","M","T","W","T","F","S"};
public CalendarPanel(){
super(new BorderLayout());
panelDate = Calendar.getInstance();
buildUI();
public CalendarPanel(Calendar date){
super(new BorderLayout());
panelDate = (date != null) ? (Calendar)date.clone() : Calendar.getInstance();
buildUI();
public CalendarPanel(Date date){
super(new BorderLayout());
panelDate = Calendar.getInstance();
if(date != null) panelDate.setTime(date);
buildUI();
public Calendar getCalendar(){ return panelDate;}
public void setCalendar(Calendar date){
if(date != null){
panelDate = (Calendar)date.clone();
redrawPanel();
public void setCalendar(Date date){
if(date != null){
panelDate.setTime(date);
redrawPanel();
public int getYear(){ return panelDate.get(Calendar.YEAR);}
public String getMonthName(){
switch(panelDate.get(Calendar.MONTH)){
case Calendar.JANUARY: return "January";
case Calendar.FEBRUARY: return "February";
case Calendar.MARCH: return "March";
case Calendar.APRIL: return "April";
case Calendar.MAY: return "May";
case Calendar.JUNE: return "June";
case Calendar.JULY: return "July";
case Calendar.AUGUST: return "August";
case Calendar.SEPTEMBER: return "September";
case Calendar.OCTOBER: return "October";
case Calendar.NOVEMBER: return "November";
case Calendar.DECEMBER: return "December";
case Calendar.UNDECIMBER: return "Undecimber";
default: return "Unknown";
private void buildUI(){
this.add(buildHeaderPanel(), BorderLayout.NORTH);
daysPanel = new Panel(new GridBagLayout());
redrawPanel();
this.add(daysPanel, BorderLayout.CENTER);
// build the part of the gui that contains the month and year
// labels with their incrementors / decrementors
private Panel buildHeaderPanel(){
monthLabel = new Label(getMonthName(), Label.CENTER);
yearLabel = new Label(Integer.toString(panelDate.get(Calendar.YEAR)),
Label.CENTER);
GridBagConstraints gbc = new GridBagConstraints();
Panel headerPanel = new Panel(new GridBagLayout());
// month label and buttons
Panel panel = new Panel(new GridBagLayout());
Button button = new Button("-");
button.setActionCommand("decrease month");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.EAST;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
panel.add(monthLabel, gbc);
button = new Button("+");
button.setActionCommand("increase month");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.WEST;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1;
headerPanel.add(panel, gbc);
// year label and buttons
panel = new Panel(new GridBagLayout());
button = new Button("-");
button.setActionCommand("decrease year");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 0;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
panel.add(yearLabel, gbc);
button = new Button("+");
button.setActionCommand("increase year");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.WEST;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1;
headerPanel.add(panel, gbc);
return headerPanel;
// redraws the entire panel, including relaying out of
// the days buttons
private void redrawPanel(){
monthLabel.setText(getMonthName());
yearLabel.setText(Integer.toString(getYear()));
// redraw days panel
GridBagConstraints gbc = new GridBagConstraints();
// clear current days panel
daysPanel.removeAll();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
// add days of week
for(int i = 0; i < days.length; i++, gbc.gridx++)
daysPanel.add(new Label(days, Label.CENTER), gbc);
gbc.gridx = 0;
gbc.gridy++;
// days of month
Button button; // day buttons
JTable day = new JTable();
Calendar today = Calendar.getInstance();
Calendar cellDay = (Calendar)today.clone();
int month = panelDate.get(Calendar.MONTH);
int year = panelDate.get(Calendar.YEAR);
// start with first of panels month
cellDay.set(year, month, 1);
gbc.gridx = cellDay.get(Calendar.DAY_OF_WEEK) - 1;
while( cellDay.get(Calendar.MONTH) == month ){
if(gbc.gridx > 6){
gbc.gridy++;
gbc.gridx = 0;
button = new Button(Integer.toString(cellDay.get(Calendar.DATE)));
button.addActionListener(this);
if( cellDay.equals(today)){
button.setForeground(Color.red);
daysPanel.add(button, gbc);
gbc.gridx++;
cellDay.add(Calendar.DAY_OF_MONTH, 1);
// re validate entire panel
validate();
// implementation of ActionListener interface
// currently no real need to create subclassed action
// events for calendar. All actions generated by this
// are action events (generated from the buttons).
// the action command will be one of the four below
// or a number (the label of the day button!).
public void actionPerformed(ActionEvent ae){
String command = ae.getActionCommand();
if(command.equals("increase month")){
panelDate.add(Calendar.MONTH, 1);
redrawPanel();
} else if(command.equals("decrease month")){
panelDate.add(Calendar.MONTH, -1);
redrawPanel();
} else if(command.equals("increase year")){
panelDate.add(Calendar.YEAR, 1);
redrawPanel();
} else if(command.equals("decrease year")){
panelDate.add(Calendar.YEAR, -1);
redrawPanel();
notifyCalendarListeners(ae);
// methods for keeping track of interested listeners
public void addCalendarActionListener(ActionListener al){
if(al != null){
if(calendarListeners == null) calendarListeners = new Vector();
calendarListeners.addElement(al);
public void removeCalendarActionListener(ActionListener al){
if((calendarListeners != null) && (al != null)){
calendarListeners.removeElement(al);
private void notifyCalendarListeners(ActionEvent ae){
if((calendarListeners != null) && (!calendarListeners.isEmpty())){
java.util.Enumeration e = calendarListeners.elements();
while(e.hasMoreElements())
((ActionListener)e.nextElement()).actionPerformed(ae);Hi,
Sorry for the change of screen name, i'm having trouble with my old account.
I have now got most of the system working. However I am having trouble working out how to stop the last days of the previous month appearing in the first week of the next month. For example on 'July 2008' , days 29 and 30 of June are present in the first week of July. How can i get rid of this? And also for the last week of the month, how to get rid of the first days of the next month?
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
* @category CalendarSystem
* @author Daniel Barrett
public class CalendarSystem extends JPanel implements ActionListener, MouseListener, KeyListener {
JPanel events = new JPanel();
JPanel action = new JPanel();
//Events Panel
DateComboBox eventDateChooser = new DateComboBox();
JTextField ref = new JTextField(10);
JTextArea eventDetails = new JTextArea();
JScrollPane scrollingArea = new JScrollPane(eventDetails);
JTextField dateF = new JTextField(15);
JTextField timeF = new JTextField(15);
String[] minutes = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
String[] hours = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
JComboBox minsComb = new JComboBox(minutes);
JComboBox hourComb = new JComboBox(hours);
//Actions Panel
JButton delete = new JButton("Delete");
JButton purge = new JButton("Purge");
JButton add = new JButton("Add");
JButton edit = new JButton("Edit");
JButton mview = new JButton("Month View");
protected JLabel monthLabel;
protected JLabel weekLabel;
protected JLabel lmonday = new JLabel("");
protected JLabel ltuesday = new JLabel("");
protected JLabel lwednesday = new JLabel("");
protected JLabel lthursday = new JLabel("");
protected JLabel lfriday = new JLabel("");
protected JLabel lsaturday = new JLabel("");
protected JLabel lsunday = new JLabel("");
protected Calendar calendar;
protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
protected SimpleDateFormat dayFormat = new SimpleDateFormat("MMM");
JPanel monthCont = new JPanel();
JPanel weekCont = new JPanel();
JPanel yearCont = new JPanel();
JPanel daysOfWeek = new JPanel();
JPanel monday = new JPanel();
JPanel tuesday = new JPanel();
JPanel wednesday = new JPanel();
JPanel thursday = new JPanel();
JPanel friday = new JPanel();
JPanel saturday = new JPanel();
JPanel sunday = new JPanel();
JList mondayEvents = new JList();
JScrollPane mondayEventsScroll = new JScrollPane(mondayEvents);
JList tuesdayEvents = new JList();
JScrollPane tuesdayEventsScroll = new JScrollPane(tuesdayEvents);
JList wednesdayEvents = new JList();
JScrollPane wednesdayEventsScroll = new JScrollPane(wednesdayEvents);
JList thursdayEvents = new JList();
JScrollPane thursdayEventsScroll = new JScrollPane(thursdayEvents);
JList fridayEvents = new JList();
JScrollPane fridayEventsScroll = new JScrollPane(fridayEvents);
JList saturdayEvents = new JList();
JScrollPane saturdayEventsScroll = new JScrollPane(saturdayEvents);
JList sundayEvents = new JList();
JScrollPane sundayEventsScroll = new JScrollPane(sundayEvents);
protected Color selectedBackground;
protected Color selectedForeground;
protected Color background;
protected Color foreground;
public CalendarSystem(){
setupDays();
setupHeaders();
setupEvents();
setupActions();
this.calendar = Calendar.getInstance();
this.calendar.setFirstDayOfWeek(Calendar.SUNDAY);
this.add(this.monthCont);
this.add(this.daysOfWeek);
this.add(this.weekCont);
this.add(this.events);
this.add(this.action);
this.setLayout(new BoxLayout(this,1));
this.setMaximumSize(new Dimension(400,30));
this.updateCalendar();
private void setupActions() {
this.action.setBorder(BorderFactory.createTitledBorder("Actions"));
this.action.add(this.add);
this.action.add(this.edit);
this.action.add(this.delete);
this.action.add(this.purge);
this.action.add(this.mview);
private void setupEvents() {
this.events.setBorder(BorderFactory.createTitledBorder("Event Details"));
this.events.setLayout(new BoxLayout(this.events,1));
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
JLabel la = new JLabel("Reference");
JLabel da = new JLabel("Date");
JLabel time = new JLabel("Time");
JLabel det = new JLabel("Details");
this.ref.setEditable(false);
this.dateF.setEditable(false);
this.timeF.setEditable(false);
this.eventDetails.setEditable(false);
row1.add(la);
row1.add(this.ref);
row1.add(da);
row1.add(this.dateF);
row1.add(time);
row1.add(this.timeF);
row2.add(det);
scrollingArea.setPreferredSize(new Dimension(600,50));
row3.add(this.scrollingArea);
this.events.add(row1);
this.events.add(row2);
this.events.add(row3);
protected JLabel createUpdateButton(final int field, final int amount, final boolean month) {
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);
if(month){
updateMCalendar();}
else{
updateCalendar();
public void mouseEntered(MouseEvent e) {
label.setBorder(selectedBorder);
public void mouseExited(MouseEvent e) {
label.setBorder(unselectedBorder);
return label;
private void updateMCalendar() {
this.calendar.set(Calendar.DAY_OF_MONTH, 1);
updateCalendar();
private void setupHeaders() {
//MONTH CONTROLS
monthCont.setLayout(new BoxLayout(monthCont, BoxLayout.X_AXIS));
monthCont.setBackground(background);
monthCont.setOpaque(true);
JLabel label;
label = createUpdateButton(Calendar.YEAR, -1,false);
label.setText("<<");
label.setToolTipText("Previous Year");
monthCont.add(Box.createHorizontalStrut(12));
monthCont.add(label);
monthCont.add(Box.createHorizontalStrut(12));
label = createUpdateButton(Calendar.MONTH, -1,true);
label.setText("< ");
label.setToolTipText("Previous Month");
monthCont.add(label);
monthLabel =new JLabel("", JLabel.CENTER);
monthLabel.setForeground(foreground);
//monthCont.add(Box.createHorizontalGlue());
monthCont.add(Box.createHorizontalStrut(12));
monthCont.add(monthLabel);
monthCont.add(Box.createHorizontalStrut(12));
//monthCont.add(Box.createHorizontalGlue());
label =createUpdateButton(Calendar.MONTH, 1,true);
label.setText(" >");
label.setToolTipText("Next Month");
monthCont.add(label);
label = createUpdateButton(Calendar.YEAR, 1,false);
label.setText(">>");
label.setToolTipText("Next Year");
monthCont.add(Box.createHorizontalStrut(12));
monthCont.add(label);
monthCont.add(Box.createHorizontalStrut(12));
//WEEK CONTROLS
weekCont.setLayout(new BoxLayout(weekCont, BoxLayout.X_AXIS));
weekCont.setBackground(background);
weekCont.setOpaque(true);
JLabel label1;
label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, -1,false);
label1.setText("<<");
label1.setToolTipText("Previous Week");
weekCont.add(label1);
weekLabel =new JLabel("", JLabel.CENTER);
weekLabel.setForeground(foreground);
JLabel lweek =new JLabel("Week: ", JLabel.CENTER);
lweek.setForeground(foreground);
//monthCont.add(Box.createHorizontalGlue());
weekCont.add(Box.createHorizontalStrut(12));
weekCont.add(lweek);
weekCont.add(weekLabel);
weekCont.add(Box.createHorizontalStrut(12));
//monthCont.add(Box.createHorizontalGlue());
label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, 1,false);
label1.setText(">>");
label1.setToolTipText("Next Week");
weekCont.add(label1);
public void setupDays(){
monday.setLayout(new BoxLayout(monday,1));
tuesday.setLayout(new BoxLayout(tuesday,1));
wednesday.setLayout(new BoxLayout(wednesday,1));
thursday.setLayout(new BoxLayout(thursday,1));
friday.setLayout(new BoxLayout(friday,1));
saturday.setLayout(new BoxLayout(saturday,1));
sunday.setLayout(new BoxLayout(sunday,1));
monday.add(this.lmonday);
monday.add(this.mondayEventsScroll);
monday.setBorder(BorderFactory.createTitledBorder("Monday"));
tuesday.add(this.ltuesday);
tuesday.add(this.tuesdayEventsScroll);
tuesday.setBorder(BorderFactory.createTitledBorder("Tuesday"));
wednesday.add(this.lwednesday);
wednesday.add(this.wednesdayEventsScroll);
wednesday.setBorder(BorderFactory.createTitledBorder("Wednesday"));
thursday.add(this.lthursday);
thursday.add(this.thursdayEventsScroll);
thursday.setBorder(BorderFactory.createTitledBorder("Thursday"));
friday.add(this.lfriday);
friday.add(this.fridayEventsScroll);
friday.setBorder(BorderFactory.createTitledBorder("Friday"));
saturday.add(this.lsaturday);
saturday.add(this.saturdayEventsScroll);
saturday.setBorder(BorderFactory.createTitledBorder("Saturday"));
sunday.add(this.lsunday);
sunday.add(this.sundayEventsScroll);
sunday.setBorder(BorderFactory.createTitledBorder("Sunday"));
this.mondayEventsScroll.setPreferredSize(new Dimension(90,200));
this.monday.setPreferredSize(new Dimension(145,300));
this.tuesdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.tuesday.setPreferredSize(new Dimension(145,300));
this.wednesdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.wednesday.setPreferredSize(new Dimension(145,300));
this.thursdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.thursday.setPreferredSize(new Dimension(145,300));
this.fridayEventsScroll.setPreferredSize(new Dimension(90,200));
this.friday.setPreferredSize(new Dimension(145,300));
this.saturdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.saturday.setPreferredSize(new Dimension(145,300));
this.sundayEventsScroll.setPreferredSize(new Dimension(90,200));
this.sunday.setPreferredSize(new Dimension(145,300));
daysOfWeek.add(this.sunday);
daysOfWeek.add(this.monday);
daysOfWeek.add(this.tuesday);
daysOfWeek.add(this.wednesday);
daysOfWeek.add(this.thursday);
daysOfWeek.add(this.friday);
daysOfWeek.add(this.saturday);
private void updateCalendar() {
monthLabel.setText(monthFormat.format(calendar.getTime()) );
weekLabel.setText(String.valueOf(this.calendar.get(calendar.WEEK_OF_MONTH)));
//Blank out / empty strings for first elements that do not start on sunday
Calendar setupCalendar = (Calendar) calendar.clone();
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
// while(setupCalendar.get(Calendar.DAY_OF_WEEK) < calendar.getActualMaximum(Calendar.DAY_OF_WEEK)) {
//System.out.println("day of month: " + setupCalendar.get(Calendar.DAY_OF_MONTH));
//System.out.println("day of week: " + (setupCalendar.get(Calendar.DAY_OF_WEEK)));
//System.out.println("week of month: " + calendar.get(Calendar.WEEK_OF_MONTH) + "\n");
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
public void setDayLabels(int day, int dayOfWeek){
if(dayOfWeek == 1){
this.lsunday.setText(String.valueOf(day));
if(dayOfWeek == 2){
this.lmonday.setText(String.valueOf(day));
if(dayOfWeek == 3){
this.ltuesday.setText(String.valueOf(day));
if(dayOfWeek == 4){
this.lwednesday.setText(String.valueOf(day));
if(dayOfWeek == 5){
this.lthursday.setText(String.valueOf(day));
if(dayOfWeek == 6){
this.lfriday.setText(String.valueOf(day));
if(dayOfWeek == 7){
this.lsaturday.setText(String.valueOf(day));
@Override
public void actionPerformed(ActionEvent arg0) {
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(1100, 670);
frame.add(new CalendarSystem());
frame.setVisible(true);
}Thanks
Dan
Maybe you are looking for
-
I am trying to setup VPN with QuickVPN
Hi I am trying to setup VPN with WRVS4400N and Quick VPN on client side. I am fairly new to VPN and did some research and looked through the manual but can't seem to get it to work so far and from what I noticed many people are having this problem. S
-
Some logins don't work in Firefox but do work in other browsers
I have a couple of sites that the logins don't work when I use Firefox but work perfectly if I use another browser such as Chrome or IE. I have tried uninstalling and reinstalling firefox including reinstalling back levels but nothing works. Any sugg
-
i have an ipod touch and it is locked and i can't seem to get into it. what can i do to unlock it?
-
Trying to factory reset an Iphone 6..
This phone was dropped in the water...and instead of waiting for it to "dry-out", I purchased another for my daughter. Well, now that it's working...I would like to use it for myself. The problem: well, she forgot the e-mail associated with the I-tu
-
Best way to handle sounds in AS3
I'm currently doing some game development, targeting iOS and Android devices using Flash Pro and AS3. I'm doing my best to keep the code highly optomized and doing as much object pooling as possible. So far, I'm very pleased with how smooth everythi