I'm programming in Java, trying to use a cardholder in order to switch between 2 JPanels which are each an extension of their own class. I think I understand the basic concepts but I am having errors in my current revision, when calling the classes. I'm getting a null pointer exception and I think it's a structural problem but I'm not sure how or why.
The main method points to this class
public class Skeleton implements ActionListener{
JPanel cardHolder;
CardLayout cards;
String cardA = "A";
String cardB = "B";
JPanel Jboard;
JPanel Jmenu;
JFrame frame2;
Board board;
Menu menu;
boolean menuSet;
boolean boardSet;
Timer timer;
public class Switcher implements ActionListener{
String card;
Switcher(String card){
this.card = card;
}
#Override
public void actionPerformed(ActionEvent e) {
cards.show(cardHolder, card);
}
}
public Skeleton(JFrame frame){
JPanel menu = new Menu();
JPanel board = new Board();
JFrame frame2 = frame;
timer = new Timer(5, this);
timer.start();
cardHolder = new JPanel();
cards = new CardLayout();
cardHolder.setLayout(cards);
cardHolder.add(menu, cardA);
cardHolder.add(board, cardB);
frame2.add(cardHolder);
frame2.revalidate();
frame2.setVisible(true);
}
public JFrame getSkeleton(){
return frame2;
}
public JPanel getCardHolder(){
return cardHolder;
}
public void checkStatus(){
if (menuSet == true){
new Switcher(cardB);
boardSet = false;
}
if (boardSet == true){
new Switcher(cardA);
menuSet = false;
}
}
#Override
public void actionPerformed(ActionEvent e) {
menuSet = menu.getMenuset();
boardSet = board.getBoardset();
checkStatus();
}
}
This is the board class, one of the JPanels I'm trying to switch between
public class Board extends JPanel{
boolean boardset;
Menu menu = new Menu();
public Board(){
setBackground(Color.WHITE);
}
public JPanel getPanel(){
return this;
}
public void setBoardset(boolean x){
boardset = x;
}
public boolean getBoardset(){
return boardset;
}
}
Here is the other JPanel class, which contains a button used to switch to the other JPanel class. This is also the original starting JPanel used.
public class Menu extends JPanel implements ActionListener{
boolean menuset;
public Menu(){
setBackground(Color.BLACK);
JButton button = new JButton("hello");
button.addActionListener(this);
this.add(button);
}
public JPanel getPanel(){
return this;
}
#Override
public void actionPerformed(ActionEvent e) {
menuset = true;
}
public void setMenuset(boolean x){
menuset = x;
}
public boolean getMenuset(){
return menuset;
}
}
Like I said, I'm getting a null pointer exception. It is occuring on this line of the Skeleton() class
menuSet = menu.getMenuset();
The line above is right after the actionPerformed event above (from the timer), and I have tested the timer a little, it works doing basic print statements but whenever I try to use the 'menu' or 'board' instance inside the actionPerformed, I get this null pointer exception.
I would appreciate any advice. I get the idea that the way I'm doing this may be a little convoluted. If anyone has any suggestions on a better way to do this it would also be helpful. My main goal is to be able to call 2 separate classes from one main class containing a cardholder. That way I can separate the code in order to keep everything isolated and in order.
Your Skeleton class has a "menu" member but it isn't set anywhere that I can see. The constructor declares its own "menu" local variable, which is local to the constructor and hides the member. Setting "menu" inside the constructor won't set the member. I don't see anywhere else where the "menu" member is set, unless I've missed something or unless another class in the same package is setting it.
Related
I have been trying to create a 'catch me if you can' game: when I start it, it randomly chooses where to allocate a 'click me' button. I am not supposed to be able to click the button, the text should be re-assigned to another button before I am able to do that.
It works for a while but then it throws the following error: "java.awt.AWTEventMulticaster.mouseMoved".
I have been trying to fix the problem with removeListener() method but I don't seem to be able to find a solution. Any comments?
Here's my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.*;
public class Game extends JFrame {
//Panels
private JPanel mainPanel = new JPanel();
// Buttons
private JButton[] buttons = new JButton[9];
private JButton theChosenButton = new JButton();
// other
private int random = 0;
public Game() {
this.setTitle("Catch me if you can");
mainPanel.setLayout(new GridLayout(3, 3));
// creates buttons
for(int i = 0; i < 9 ; i++) {
buttons[i] = new JButton();
mainPanel.add(buttons[i]);
}
// Add everything to frame
this.getContentPane().add(mainPanel);
this.setSize(400, 400);
this.setVisible(true);
}
// generates random number between 1 and 9 to be used
public int clickMeGenerator(){
random = (int) Math.floor(Math.random() * 9);
return random;
}
// randomly assigns clickMeGenerator to a button
// add mouseMoved listener to the chosen button
public void assign(){
int randomButton = this.clickMeGenerator();
theChosenButton = buttons[randomButton];
theChosenButton.addMouseMotionListener(new MouseHover());
theChosenButton.setText("Click me");
}
public void removeListener() {
theChosenButton.removeMouseMotionListener(new MouseHover());
//}
}
// inner class
class MouseHover implements MouseMotionListener {
public void mouseMoved(MouseEvent e) {
theChosenButton.setText("");
Game.this.assign();
}
public void mouseDragged(MouseEvent e) {
}
}
} // end of class
Test class:
public class GameTest {
public static void main (String args[]) {
Game myGame = new Game();
myGame.assign();
}
}
Thank you so much for your help!
Just for clarity, the "actual" error is ...
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.desktop/java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:337)
at java.desktop/java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:337)
So looking through the code...
public void assign() {
int randomButton = this.clickMeGenerator();
theChosenButton = buttons[randomButton];
theChosenButton.addMouseMotionListener(new MouseHover());
theChosenButton.setText("Click me");
}
You are repeatedly add a new MouseMotionListener to you buttons, over and over again, and...
public void removeListener() {
theChosenButton.removeMouseMotionListener(new MouseHover());
//}
}
is pointless, as you're trying to remove a new instance of MouseHover from the button, but it will never have been applied in the first place.
The first thing I would do is create an instance of MouseHover as an instance field in Game
private MouseHover mouseHover = new MouseHover();
and use it when calling addMouseMotionListener and removeMouseMotionListener.
I would then, remove the listener from the "currently" active button before adding it to the next one.
Personally, I would do this in the assign method
public void assign() {
int randomButton = this.clickMeGenerator();
if (theChosenButton != null) {
theChosenButton.removeMouseMotionListener(mouseHover);
}
theChosenButton = buttons[randomButton];
theChosenButton.addMouseMotionListener(mouseHover);
theChosenButton.setText("Click me");
}
I would also ensure that assign is called from within the Event Dispatching Thread when the class is first created, as the UI has been realised by the end of the constructor of Game, meaning the first call to assign is outside of the context of the EDT, which is not recommended.
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Game myGame = new Game();
myGame.assign();
}
});
}
I am trying to develop a very basic "Simon says" simulator using Java GUI. I have a method that generates and returns an int[] array; for each element in the array, the Timer computer should start, call the doClick() method for the specified JButton, and wait for 1/2 a second. Each JButton is connected to an ActionListener() that changes the color of the specific button to white, activates another Timer timer, and changes the button back to its original color.
Every time I call computer.start(); within the for-loop it runs the code within ComputerListener(), but it repeats endlessly. I have added print statements so that I can see what is going on via the output on Netbeans. I have looked at similar issues on the forum, but nothing has provided a viable solution.
My question: why is my ComputerListener class repeating when computer.start(); is called within the for-loop?
package simon;
// #jagged_prospect
import java.util.Random;
import java.util.Arrays;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.basic.BasicButtonUI;
public class SIMONPanel extends JPanel{
private static final int PANEL_W=300,PANEL_H=300;
private static final int PREF_W=500,PREF_H=500;
private static final String[] CARD_LABELS={"main","info","game"};
private final JPanel gameCard,infoCard,splashCard;
private final JButton rButton,yButton,gButton,bButton;
private final int lives=3;
private CardLayout cardlayout=new CardLayout();
private JPanel cards=new JPanel(cardlayout);
private Action[] actions={new ShowMainAction(),new ShowInfoAction(),
new ShowGameAction()};
private Object source;
private Timer timer,computer;
public SIMONPanel(){
setBackground(Color.BLACK);
setLayout(new BorderLayout());
gameCard=new JPanel();
infoCard=new JPanel();
splashCard=new JPanel();
// game card panel
gameCard.setLayout(new BorderLayout());
gameCard.setPreferredSize(new Dimension(PANEL_W,PANEL_H));
JPanel gameButtonPanel=new JPanel();
gameButtonPanel.setLayout(new GridLayout(2,2));
JButton startButton=new JButton("Start");
startButton.addActionListener(new StartListener());
rButton=new JButton("red");
rButton.addActionListener(new ColorButtonListener());
rButton.setSize(50,50);
rButton.setUI((ButtonUI)BasicButtonUI.createUI(rButton));
rButton.setBackground(Color.RED);
rButton.setForeground(Color.WHITE);
yButton=new JButton("yellow");
yButton.addActionListener(new ColorButtonListener());
yButton.setSize(50,50);
yButton.setUI((ButtonUI)BasicButtonUI.createUI(yButton));
yButton.setBackground(Color.YELLOW);
gButton=new JButton("green");
gButton.addActionListener(new ColorButtonListener());
gButton.setSize(50,50);
gButton.setUI((ButtonUI)BasicButtonUI.createUI(gButton));
gButton.setBackground(Color.GREEN);
bButton=new JButton("blue");
bButton.addActionListener(new ColorButtonListener());
bButton.setSize(50,50);
bButton.setUI((ButtonUI)BasicButtonUI.createUI(bButton));
bButton.setBackground(Color.BLUE);
bButton.setForeground(Color.WHITE);
gameButtonPanel.add(gButton);
gameButtonPanel.add(rButton);
gameButtonPanel.add(yButton);
gameButtonPanel.add(bButton);
gameCard.add(gameButtonPanel,BorderLayout.CENTER);
gameCard.add(startButton,BorderLayout.SOUTH);
// splash card panel
splashCard.setLayout(new BorderLayout());
splashCard.setPreferredSize(new Dimension(PANEL_W,PANEL_H));
splashCard.setBackground(Color.BLACK);
JLabel titleLabel=new JLabel("S I M O N",SwingConstants.CENTER);
titleLabel.setFont(new Font("Niagara Solid",Font.BOLD,84));
titleLabel.setForeground(Color.WHITE);
splashCard.add(titleLabel,BorderLayout.CENTER);
// info card panel
// nothing here yet
JPanel buttonPanel=new JPanel(new GridLayout(1,0,5,0));
for(Action action : actions){
buttonPanel.add(new JButton(action));
buttonPanel.setBackground(Color.BLACK);
}
cards.add(splashCard,CARD_LABELS[0]);
cards.add(infoCard,CARD_LABELS[1]);
cards.add(gameCard,CARD_LABELS[2]);
add(cards,BorderLayout.CENTER);
add(buttonPanel,BorderLayout.SOUTH);
}
// sets uniform panel size
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
// shows the Main Menu card
private class ShowMainAction extends AbstractAction {
public ShowMainAction() {
super("Main");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[0]);
}
}
// shows the Info card
private class ShowInfoAction extends AbstractAction {
public ShowInfoAction() {
super("Info");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[1]);
}
}
// show the Game card
private class ShowGameAction extends AbstractAction {
public ShowGameAction() {
super("Game");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[2]);
}
}
private class TimerListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(source==gButton){
gButton.setBackground(Color.GREEN);
}
else if(source==rButton){
rButton.setBackground(Color.RED);
rButton.setForeground(Color.WHITE);
}
else if(source==yButton){
yButton.setBackground(Color.YELLOW);
}
else if(source==bButton){
bButton.setBackground(Color.BLUE);
bButton.setForeground(Color.WHITE);
}
}
}
private class ColorButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
source=event.getSource();
int delay=300;
timer=new Timer(delay,new TimerListener());
if(source==gButton){
gButton.setBackground(Color.WHITE);
timer.setRepeats(false);
timer.start();
}
else if(source==rButton){
rButton.setBackground(Color.WHITE);
rButton.setForeground(Color.BLACK);
timer.setRepeats(false);
timer.start();
}
else if(source==yButton){
yButton.setBackground(Color.WHITE);
timer.setRepeats(false);
timer.start();
}
else if(source==bButton){
bButton.setBackground(Color.WHITE);
bButton.setForeground(Color.BLACK);
timer.setRepeats(false);
timer.start();
}
}
}
private class StartListener implements ActionListener{
public void actionPerformed(ActionEvent event){
// calls generateSequence() to make pattern for player to replicate
// for debugging in output
System.out.println(Arrays.toString(generateSequence()));
}
}
public int[] generateSequence(){
Random ran=new Random();
ComputerListener cpu=new ComputerListener();
computer=new javax.swing.Timer(500,cpu);
int seqLen=4;
int[] gameSequence=new int[seqLen];
for(int x=0;x<seqLen;x++){
int assign=ran.nextInt(4)+1;
gameSequence[x]=assign;
}
for(int y=0;y<seqLen;y++){ // print and wait 1/2 second, repeat 3 times
computer.start();
}
//computer.stop(); // should stop ComputerListener()???
return gameSequence;
}
private class ComputerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
// for debugging in output
System.out.println("it worked");
}
}
}
You're calling the computer Swing Timer's start button multiple times in a for loop, and that is not what you want to do, and in fact, the whole purpose of the timer is to help you get rid of the for loop. Instead the Timer repeats an action, and changes a state, and keeps going until its done. Consider using an int array or better an ArrayList to hold the colors that the timer should iterate through, and within that ActionListener, do the action and advance a pointer to the next position in the array or List, using that pointer to decide what action to do next. Then when the pointer is completely through the collection, stop the Timer.
For an example of exactly what I'm describing, please check out my Timer's ActionListener for an incomplete Simon game here: Method keeps window from closing
The Timer's ActionListener, annotated, is below:
private class TimerListener implements ActionListener {
private SimonPanel simonPanel; // the Simon JPanel
private int colorListIndex = 0; // index into the ArrayList of MyColor objects
private int sliceCount = 0;
private List<MyColor> myColorList; // the MyColor ArrayList -- the random colors to press
private int maxCount;
public TimerListener(SimonPanel simonPanel, List<MyColor> myColorList) {
// pass in the key fields into the program via constructor parameter
this.simonPanel = simonPanel;
this.myColorList = myColorList; // again the ArrayList that holds random MyColor objects
maxCount = myColorList.size(); // size of my list
}
#Override
public void actionPerformed(ActionEvent evt) {
// if index at the end of the list -- get out and clean up
if (colorListIndex == maxCount) {
// clear the display of "pressed" colors
for (MyColor myColor : MyColor.values()) {
simonPanel.setMyColorPressed(myColor, false);
}
// stop this timer
((Timer) evt.getSource()).stop();
return;
}
// the listener is a little complex since it must turn on colors and turn them off
// which is why I use a sliceCount int counter variable here
if (sliceCount == 0) {
// turn on the next color in the list (using the index)
MyColor myColor = myColorList.get(colorListIndex);
simonPanel.setMyColorPressed(myColor, true);
sliceCount++;
} else if (sliceCount < TIME_SLICES - 1) {
sliceCount++;
return;
} else if (sliceCount == TIME_SLICES - 1) {
sliceCount = 0;
MyColor myColor = myColorList.get(colorListIndex);
simonPanel.setMyColorPressed(myColor, false); // turn off the color
colorListIndex++; // and increment the index
return;
}
}
}
I can add/remove elements to/from a panel and repaint it when the method used to fill the panel is called by one of its parent JFrame events, but I can not repaint it by events from other classes even if their sources have been added to it, or that is how I understand the problem for now.
I want to understand what is going on here, Thank you.
Main Class
public class Principal extends JFrame implements ActionListener{
private static Principal instPrincipal = null;
private SubClass subClassInst =new SubClass();
public JPanel panelPrincipal;
public static Principal getInstance() {
if (instPrincipal != null)
return instPrincipal ;
else {
instPrincipal = new Principal ();
return instPrincipal ;
}
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
try {
if(source == btnSub)
{
subClassInst.fillPanelPrincipal();
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Sub Classes Example
public class SubClass implements ActionListener {
private JPanel tempPanel;
private JButton btnSave;
private Principal instPrincipal;
public void fillPanelPrincipal() {
instPrincipal = Principal.getInstance();
instPrincipal.panelPrincipal.removeAll();
//Start adding elements..
tempPanel = new JPanel();
instPrincipal.panelPrincipal.add(tempPanel);
btnSave = new JButton("Save");
btnSave.addActionListener(this);
tempPanel.add(btnSave);
//End.
instPrincipal.panelPrincipal.repaint();
}
public void actionPerformed(ActionEvent event) {
instPrincipal = Principal.getInstance();
Object source = event.getSource();
if (source == btnSave) {
// modify local data, Database .. ; //work but need to be repainted on panelPrincipal
instPrincipal.panelPrincipal.repaint();//does not work
}
}
}
Update
To clarify the problem more, I have one single JPanel on a JFrame and there are different classes to fill it for multiple functionalities, I call their methods using JMenuItems on the main frame, these Classes implement ActionListener, passing the panel didn't work, and also the method I am trying here.
I thought about changing the design to use CardLayout, but it was very difficult.
You are calling Principal as a static reference, so how is it supposed to know what frame to repaint? You should pass the instance of the JFrame through the constructor of the subclass. Like so:
private SubClass subClassInst = new SubClass(this);
And create the constructor like this
private JFrame parent;
public SubClass(JFrame parent) { this.parent = parent; }
You can then use it like so
this.parent.repaint();
Looking at other answers, i have followed exactly what they say, but i just keep getting the nullPointerException error. I have 4 classes, the 2 below, a GUI class and main menu class. Main manages the card layout and i would like a button in the Insert class to change the "Active" card to main menu class.
Main:
public class Main extends JPanel implements ChooserListener{
MainMenu mm;
Insert InsertCustomer;
public JPanel mPanel;
CardLayout cl;
private String c;
public Main(){
super();
//add mPanel, set to CardLayout and add the Main
mPanel = new JPanel();
this.add(mPanel);
cl = new CardLayout();
mPanel.setLayout(cl);
//add classes
mm = new MainMenu(this);
InsertCustomer = new Insert();
//add classes to mPanel
mPanel.add(mm, "mm");
mPanel.add(InsertCustomer, "InsertCustomer");
}
public void tell(Object o) {
c = o.toString();
cl.show(mPanel, c);
}
public void swapView(String key) {
CardLayout cl = (CardLayout)(mPanel.getLayout());
cl.show(mPanel, key);
}
}
Insert:
public class Insert extends JPanel{
private JButton logoutbutton;
private LogoutListener lListener;
public Insert() {
super();
//BUTTONS
//logout button
JButton logoutbutton = new JButton("Main Menu");
this.add(logoutbutton);
lListener = new LogoutListener(null);
logoutbutton.addActionListener(lListener);
}
private class LogoutListener implements ActionListener{
private Main main;
public LogoutListener(Main main){
this.main = main;
}
public void actionPerformed(ActionEvent e) {
main.swapView("mm");
}
}
}
lListener = new LogoutListener(null);
Your LogoutListener takes your Main-class, but you give him null. Of course you will get a NullPointerException (at least on your logoutButton-click).
Your problem in next lines :
lListener = new LogoutListener(null);
main.swapView("mm");
You need to put reference to your Main class, not null as you done. Because of your main in LogoutListener is null and you catch NPE.
Simple solution is to transfer reference of your Main to Insert with help of constructor and then transfer that to LogoutListener.
Hi well my code so far does something like this: Click a button, opens a combobox. I want to select an option on the ComboBox and depending on which option is picked i want to open another combobox using getSelectIndex().
Here are parts of my code which are relevant. I know I have to make the other comboboxes not visible or removed but at the moment I'm just trying to make a combobox appear. As you can see i have inserted the actionlistener for the button which works and opens the combobox.however when selecting a string in the combobox no event occurs. However when I run it, no comboboxes appear.
public class Work extends JFrame {
// variables for JPanel
private JPanel buttonPanel;
private JButton timeButton;
public Work()
{
setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.setPreferredSize(new Dimension(400, 500));
add(buttonPanel,BorderLayout.WEST);
timeButton = new JButton("Time");
buttonPanel.add(timeButton);
buttontime clickTime = new buttontime(); // event created when time button is clicked
timeButton.addActionListener(clickTime);
Time timeObject = new Time();
timeObject.SelectTime();
buttontime2 selectDest = new buttontime2();
timeObject.getAirportBox().addActionListener(selectDest);
}
public class buttontime implements ActionListener { //creating actionlistener for clicking on timebutton to bring up a combobox
public void actionPerformed(ActionEvent clickTime) {
Time timeObject = new Time();
timeObject.SelectTime();
add(timeObject.getTimePanel(),BorderLayout.EAST);
timeObject.getTimePanel().setVisible(true);
timeObject.getTimePanel().revalidate() ;
timeObject.getAirportBox().setVisible(true);
}
}
public class buttontime2 implements ActionListener{
public void actionPerformed(ActionEvent selectDest) {
Time timeObject = new Time();
timeObject.SelectTime();
if(timeObject.getAirportBox().getSelectedIndex() == 1) {
timeObject.getEastMidBox().setVisible(true);
}
else if(timeObject.getAirportBox().getSelectedIndex() == 2) {
timeObject.getBirmBox().setVisible(true);
}
else if(timeObject.getAirportBox().getSelectedIndex() == 3) {
timeObject.getMancbox().setVisible(true);
}
else if(timeObject.getAirportBox().getSelectedIndex() == 4) {
timeObject.getHeathBox().setVisible(true);
}
}
}
public static void main (String args[]) {
events mainmenu = new events(); //object is created
mainmenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainmenu.setSize(800,500);
mainmenu.setVisible(true);
mainmenu.setLayout(new BorderLayout());
mainmenu.setTitle("Learning how to use GUI");
mainmenu.setBackground(Color.BLUE);
mainmenu.setResizable(false);
}
}
my other class TIME
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Time
{
private JComboBox timeAirportbox;//comboboxes declared
private JComboBox eastMidbox;
private JComboBox mancBox;
private JComboBox heathBox;
private JComboBox birmBox;
private String[] airport = {"","EM", "Bham", "Manc", "Heath"};//array of airports declared
private String[] destination = {"","NY", "Cali", "FlO", "MIAMI", "Tokyo"};//array of destinations declared
private JPanel timePanel;
public void SelectTime() {
//combobox objects created
timePanel = new JPanel();
timePanel.setBackground(Color.BLUE);
timePanel.setPreferredSize(new Dimension(400, 400));
timeAirportbox = new JComboBox(airport);//array is inserted into the JComboBox
timePanel.add(timeAirportbox);
timeAirportbox.setVisible(false);
eastMidbox = new JComboBox(destination);
timePanel.add(eastMidbox);
eastMidbox.setVisible(false);
mancBox = new JComboBox(destination);
timePanel.add(mancBox);
mancBox.setVisible(false);
heathBox = new JComboBox(destination);
timePanel.add(heathBox);
heathBox.setVisible(false);
birmBox = new JComboBox(destination);
timePanel.add(birmBox);
birmBox.setVisible(false);
}
public JPanel getTimePanel() {
return timePanel;
}
public JComboBox getAirportBox() {
return timeAirportbox;
}
public JComboBox getEastMidBox() {
return eastMidbox;
}
public JComboBox getMancbox() {
return mancBox;
}
public JComboBox getHeathBox() {
return heathBox;
}
public JComboBox getBirmBox() {
return birmBox;
}
}
The Time object that is built in Work constructor is not used:
Time timeObject = new Time();
timeObject.SelectTime();
buttontime2 selectDest = new buttontime2();
timeObject.getAirportBox().addActionListener(selectDest);
As you are only applying the action listener selectedDest to the combobox of that timeObject, which is not used, then the listener will never be called.
You can do two things to make it work:
Move the code that creates the listener and assign it to the combox in the first listener buttontime
Create the Time object only once and store it as a member of your Work instance. As your listener is a non-static inner classes of the Work class, it will be able to use it instead of creating a new Time object.
Edit: I didn't see that in your second listener, you were AGAIN building a new Time object. This object is really a different one than the one you have created earlier, so modifying one will not affect the other. You really should create the Time object once and store it as a member variable of your Work class, and then use this object in your listeners instead of recreating it.
To be clear, do it like this:
public class Work extends JFrame {
// ...
private Time timeObject;
public Work() {
// ...
timeObject = new Time();
timeObject.SelectTime();
buttontime2 selectDest = new buttontime2();
timeObject.getAirportBox().addActionListener(selectDest);
}
public class buttontime implements ActionListener {
public void actionPerformed(ActionEvent clickTime) {
// use timeObject, don't create it and don't call SelectTime()
// example:
add(timeObject.getTimePanel(),BorderLayout.EAST);
// ....
}
}
public class buttontime2 implements ActionListener {
public void actionPerformed(ActionEvent clickTime) {
// use timeObject, don't create it and don't call SelectTime()
}
}
}
Also to note:
You should not extends JFrame, there is no reason to do so. Refactor your code so that your frame is just a member variable of your Work class.
Follow Java standard code conventions, especially use case properly with class names: buttonlistener should be ButtonListener, and method should start with lowercase: SelectTime should be selectTime.