-1

I am writing a program where I need to do different actions for a separate class depending on which button is clicked.

public class NewJFrame{
    public static JButton b1;
    public static JButton b2;
    public static JButton b3;
}

public class Slot{

    int value;
    JButton button;

    Slot(int value, JButton button)
    {
        this.value=value;
        this.button=button;
    }
}

public class Game{
    Slot[] slots=new Slot[3];
    Game(){
        slots[0]=new Slot(1,NewJFrame.b1);
        slots[1]=new Slot(2,NewJFrame.b2);
        slots[2]=new Slot(3,NewJFrame.b3);
    }
    public void actionPerformed(ActionEvent e) {
        for(int i=0;i<3;i++){
            if(e.getSource()==slots[i].button)
                slots[i].button.setText(String.valueOf(value));
        }
    }
}

Something like this. Note that, I'm completely novice at GUI designing.

Shawon0418
  • 181
  • 1
  • 3
  • 12
  • 1
    Please ask a more specific question. So far all you've done is to post some vague overly broad requirements. The more specific your question, usually the better and more specific the answer. Please have a look at [help] as well as the [how to ask good questions](http://stackoverflow.com/help/how-to-ask) sections for more information on how to improve your question and increase your chances of getting decent help. – Hovercraft Full Of Eels May 06 '16 at 01:35
  • 1
    Unrelated recs: None of the fields above should be static, especially JButtons. Class names should begin with upper case letters to conform with Java naming conventions, since if you do it this way, others will better understand your code and your problem. – Hovercraft Full Of Eels May 06 '16 at 01:36
  • 1
    Thanks for the renaming, but the more important correction is to improve your question so that it is more easily understood and answered. – Hovercraft Full Of Eels May 06 '16 at 01:39
  • Thanks, yeah I get it that I should be more specific, but the actual program I have contains hundreds of lines of auto-generated code, I just want to save the trouble of copy-pasting it here and give potential helpers a headache. So I just gave the basic idea of what I want to do here. About the buttons being static, I was trying to call them normally, but got an error saying "non static variable b1 cannon be referenced from static context", the problem is solved after I made the button static. – Shawon0418 May 06 '16 at 01:45
  • 1
    For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson May 06 '16 at 01:45
  • 1
    Your way of "solving" this problem is the exact opposite of what you should be doing. The proper solution is to not access those buttons in a static way. You've still not clarified your main question at all though. – Hovercraft Full Of Eels May 06 '16 at 01:47
  • 1
    @Shawon0418: Don't let the GUI editor dictate your design, for [example](http://stackoverflow.com/a/12505305/230513). – trashgod May 06 '16 at 02:13

1 Answers1

5

Use Action to encapsulate functionality for use elsewhere in your program, e.g. buttons, menus and toolbars. The BeaconPanel shown below exports several actions that make it easy to use them in a control panel. To limit the proliferation of instances, the actions themselves can be class members. As an exercise, change controls to a JToolBar or add the same actions to a menu.

JPanel controls = new JPanel();
controls.add(new JButton(beaconPanel.getFlashAction()));
controls.add(new JButton(beaconPanel.getOnAction()));
controls.add(new JButton(beaconPanel.getOffAction()));

image

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Timer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/a/37063037/230513 */
public class Beacon {

    private static class BeaconPanel extends JPanel {

        private static final int N = 16;
        private final Ellipse2D.Double ball = new Ellipse2D.Double();
        private final Timer timer;
        private final Color on;
        private final Color off;
        private final AbstractAction flashAction = new AbstractAction("Flash") {
            @Override
            public void actionPerformed(ActionEvent e) {
                timer.restart();
            }
        };
        private final AbstractAction onAction = new AbstractAction("On") {
            @Override
            public void actionPerformed(ActionEvent e) {
                stop(on);
            }
        };
        private final AbstractAction offAction = new AbstractAction("Off") {
            @Override
            public void actionPerformed(ActionEvent e) {
                stop(off);
            }
        };
        private Color currentColor;

        public BeaconPanel(Color on, Color off) {
            this.on = on;
            this.off = off;
            this.currentColor = on;
            timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    changeColors();
                }
            });
        }

        public void start() {
            timer.start();
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            int x = getX() + N;
            int y = getY() + N;
            int w = getWidth() - 2 * N;
            int h = getHeight() - 2 * N;
            ball.setFrame(x, y, w, h);
            g2.setColor(currentColor);
            g2.fill(ball);
            g2.setColor(Color.black);
            g2.draw(ball);
        }

        private void changeColors() {
            currentColor = currentColor == on ? off : on;
            repaint();
        }

        private void stop(Color color) {
            timer.stop();
            currentColor = color;
            repaint();
        }

        public Action getFlashAction() {
            return flashAction;
        }

        public Action getOnAction() {
            return onAction;
        }

        public Action getOffAction() {
            return offAction;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(N * N, N * N);
        }
    }

    public static void display() {
        JFrame f = new JFrame("Beacon");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final BeaconPanel beaconPanel = new BeaconPanel(Color.orange, Color.orange.darker());
        f.add(beaconPanel);
        JPanel controls = new JPanel();
        controls.add(new JButton(beaconPanel.getFlashAction()));
        controls.add(new JButton(beaconPanel.getOnAction()));
        controls.add(new JButton(beaconPanel.getOffAction()));
        f.add(controls, BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        beaconPanel.start();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Beacon.display();
            }
        });
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045