Full caveat: I'm a CS student, and this question is related to the recently assigned Java program for object oriented programming. Although we did some things in the console, this is the first time we have worked with a GUI and Swing or Awt. We were given some code that created a window with some text and a button that rotated in different colors for the text. Then we were asked to change the program to create color switchers instead - this was also meant to give us the opportunity to explore the API. I have already transferred my assignment and received permission from my instructor to post my code here.
What is the best way to implement button actions in Java? After some attempts, I created these buttons:
class HelloComponent3 extends JComponent implements MouseMotionListener, ActionListener { int messageX = 75, messageY= 175; String theMessage; String redString = "red", blueString = "blue", greenString = "green"; String magentaString = "magenta", blackString = "black", resetString = "reset"; JButton resetButton; JRadioButton redButton, blueButton, greenButton, magentaButton, blackButton; ButtonGroup colorButtons; public HelloComponent3(String message) { theMessage = message;
And added action listeners ...
redButton.addActionListener(this); blueButton.addActionListener(this); ...
A stub was created for the actionPerformed method to give us an idea of how to use it, but since there was only one button in the template, it was not clear how to implement several buttons. I tried to include String, but quickly realized that since String is not a primitive type, I could not use it for the switch statement. I could improvise with an if-else chain, but instead I came to this. It seems far from elegance, and there must be a better way. If there is, what is it? Is there a way to include a string? Or choose an action in a more scalable way?
public void actionPerformed(ActionEvent e){ if (e.getActionCommand().equals(resetString)) { messageX = 75; messageY = 175; setForeground(Color.black); blackButton.setSelected(true); repaint(); return; } if ( e.getActionCommand().equals(redString) ) { setForeground(Color.red); repaint(); return; } if ( e.getActionCommand().equals(blueString) ) { setForeground(Color.blue); repaint(); return; } if ( e.getActionCommand().equals(greenString) ) { setForeground(Color.green); repaint(); return; } if ( e.getActionCommand().equals(magentaString) ) { setForeground(Color.magenta); repaint(); return; } if ( e.getActionCommand().equals(blackString) ) { setForeground(Color.black); repaint(); return; } }
java swing awt
Kevin griffin
source share