I have the following code below. My objective is to allow each button to add to the text field so that the user can input a phone number. The only thing I can't seem to get working is the field to allow multiple text input. Once you click on another button, it replaces it in the text field so only one digit at a time is present. How can I fix this so each button adds its number in without just completely replacing it? Also, why is my border manager not applying to the code? Thank you!!
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Keys
{
private JPanel phone;
public static void main (String[] args)
{
JFrame frame = new JFrame ("Keys");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel phone = new JPanel();
phone.setBorder (BorderFactory.createRaisedBevelBorder());
JTabbedPane tp = new JTabbedPane();
tp.addTab ("KeyPad", new KeyPad());
frame.getContentPane().add(phone);
frame.getContentPane().add(tp);
frame.pack();
frame.pack();frame.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyPad extends JPanel
{
private JLabel resultLabel;
private JButton button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonclear;
public KeyPad()
{
setLayout (new GridLayout (5, 3));
resultLabel = new JLabel ("---");
button0 = new JButton ("0");
button1 = new JButton ("1");
button2 = new JButton ("2");
button3 = new JButton ("3");
button4 = new JButton ("4");
button5 = new JButton ("5");
button6 = new JButton ("6");
button7 = new JButton ("7");
button8 = new JButton ("8");
button9 = new JButton ("9");
buttonclear = new JButton ("Clear");
button0.addActionListener (new ButtonListener0());
button1.addActionListener (new ButtonListener1());
button2.addActionListener (new ButtonListener2());
button3.addActionListener (new ButtonListener3());
button4.addActionListener (new ButtonListener4());
button5.addActionListener (new ButtonListener5());
button6.addActionListener (new ButtonListener6());
button7.addActionListener (new ButtonListener7());
button8.addActionListener (new ButtonListener8());
button9.addActionListener (new ButtonListener9());
buttonclear.addActionListener(new ButtonListenerC());
add (resultLabel);
add (button0);
add (button1);
add (button2);
add (button3);
add (button4);
add (button5);
add (button6);
add (button7);
add (button8);
add (button9);
add (buttonclear);
setPreferredSize (new Dimension(250,250));
setBackground (Color.green);
}
private class ButtonListener0 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("0");
}
}
private class ButtonListener1 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("1");
}
}
private class ButtonListener2 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("2");
}
}
private class ButtonListener3 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("3");
}
}
private class ButtonListener4 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("4");
}
}
private class ButtonListener5 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("5");
}
}
private class ButtonListener6 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("6");
}
}
private class ButtonListener7 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("7");
}
}
private class ButtonListener8 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("8");
}
}
private class ButtonListener9 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("9");
}
}
private class ButtonListenerC implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText (" ");
}
}
}
In each of your actionPerformed method if should be :
resultLabel.setText (resultLabel.getText()+"theNumber");
There seems to be a lot of copy/paste in your code. Try to see if you can make it more simpler.
You can concatenate the new text on to the old text by doing something like this:
resultLabel.setText(resultLabel.getText() + "3");
This gets the current text, then appends "3" to the end of it.
First of all you should only have one ButtonListener, since every ButtonListener does the the same (except the number it should add. The following code should work:
private class ButtonListener implements ActionListener
{
private String value = "";
public ButtonListner(String value) {
this.value = value;
}
public void actionPerformed (ActionEvent event)
{
resultLabel.setText(resultLabel.getText() + value);
}
}
You can init your ButtonListeners this way:
button0.addActionListener(new ButtonListener("0"));
Related
I have two frames in separate classes (FrameOne and FrameTwo) FrameOne has two buttons. One to open FrameTwo and One shall close FrameTwo. How to open FrameTwo I know. But not how to close from Frame One. How do I code it to make it working? Thanks. (I know that there are similar questions. I red them all. But it didn't gave me the answer. Also GUI guides didn't helped.)
public class Main {
public static void main(String[] args) {
FrameOne frame = new FrameOne();
}
}
FrameOne class:
public class FrameOne extends JFrame implements ActionListener{
private JButton btn1, btn2;
FrameOne () {
setVisible(true);
setSize(400,400);
setLayout(new FlowLayout());
setTitle("Main");
setDefaultCloseOperation(EXIT_ON_CLOSE);
btn1 = new JButton("opens FrameTwo");
btn2 = new JButton("close FrameTwo");
btn1.addActionListener(this);
btn2.addActionListener(this);
add(btn1);
add(btn2);
}
#Override
public void actionPerformed (ActionEvent e) {
if(e.getSource()== btn1) {
FrameTow frameTwo = new FrameTwo();
}
else if(e.getSource()== btn2) ;
// {???.dispose(); }
}
}
`
Frame2 class:
public class FrameTow extends JFrame {
FrameTwo () {
setVisible(true);
setSize(400,400);
setTitle("FrameTwo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocation(400, 400);
}
}
Any of the below solutions will work
frameTwo.dispatchEvent(new WindowEvent(frameTwo, WindowEvent.WINDOW_CLOSING));
OR
frameTwo.setVisible(false);
The short answer is modify FrameOne :
private JFrame frameTwo; //introduce a field
#Override
public void actionPerformed (ActionEvent e) {
if(e.getSource()== btn1) {
frameTwo = new FrameTwo(); //use field in action listener
}
else if(e.getSource()== btn2){
frameTwo.dispose(); //use field in action listener
}
}
The longer answer: using a JDialog for the 2nd frame is a better practice:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
new FrameOne();
}
}
class FrameOne extends JFrame implements ActionListener{
private final JButton btn1, btn2;
private JDialog frameTwo; //introduce a field
FrameOne () {
setSize(400,400);
setLayout(new FlowLayout());
setTitle("Main");
setDefaultCloseOperation(EXIT_ON_CLOSE);
btn1 = new JButton("opens FrameTwo");
btn2 = new JButton("close FrameTwo");
btn1.addActionListener(this);
btn2.addActionListener(this);
add(btn1);
add(btn2);
setVisible(true); //make it visible after construction is completed
}
#Override
public void actionPerformed (ActionEvent e) {
if(e.getSource()== btn1) {
frameTwo = new FrameTwo(); //use field in action listener
}
else if(e.getSource()== btn2){
frameTwo.dispose(); //use field in action listener
}
}
}
class FrameTwo extends JDialog {
FrameTwo() {
setSize(400,400);
setTitle("FrameTwo");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLocation(400, 400);
setVisible(true); //make it visible after construction is completed
}
}
In the example you show, one can open several instances of FrameTwo. Which one should the second button close?
Assuming you want there to be only one, you could introduce a field in in FrameOne, initially set to null. btn1 would then only open a frame if the field is null, and assign it to the field. Then btn2 can call dispose() on the field (and reset it to null).
Example, based on your attempt:
public class FrameOne extends JFrame implements ActionListener {
private JButton btn1, btn2;
private FrameTwo frameTwo = null;
FrameOne () {
setVisible(true);
setSize(400,400);
setLayout(new FlowLayout());
setTitle("Main");
setDefaultCloseOperation(EXIT_ON_CLOSE);
btn1 = new JButton("opens FrameTwo");
btn2 = new JButton("close FrameTwo");
btn1.addActionListener(this);
btn2.addActionListener(this);
add(btn1);
add(btn2);
}
#Override
public void actionPerformed (ActionEvent e)
{if(e.getSource()== btn1)
{
if (frameTwo == null) {
frameTwo = new FrameTwo();
}
}
else if(e.getSource()== btn2) {
frameTwo.dispatchEvent(new WindowEvent(frameTwo, WindowEvent.WINDOW_CLOSING));
frameTwo = null;
}}}
I started to make a graphic for program I built in which to insert a name and length of a song, how do I do it in graphics? I found out how to pick up a button but I do not understand how to absorb something inserted into a text box
import java.awt.*;
import java.awt.event.*;
public class Active extends Frame {
public void init() {
ActionListener al = new MyActionListener();
TextField tf = new TextField(20);
Button b;
setLayout(new FlowLayout());
setSize(1000, 1000);
b = new Button ("first");
b.setActionCommand("First");
b.addActionListener(al);
add(b);
b = new Button ("Second");
b.setActionCommand("Second");
b.addActionListener(al);
add(b);
setVisible(true);
add(tf);
}
public Active(String caption) {
super(caption);
init();
}
public static void main(String[] args) {
Active m = new Active("Active buttons");
}
}
the main:
import java.awt.*;
import java.awt.event.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s.equals("First")) {
System.out.println("The first button was switched");
}
if(s.equals("Second")) {
System.out.println("The second button was switched");
}
}
}
I would write it with the Swing GUI Toolkit. Here is a short example of that:
public class MyPanel extends JPanel
{
private JTextField songNameField;
private JTextField songLengthField;
private JButton assignBtn;
public MyPanel()
{
this.songNameField = new JTextField();
this.songLengthField = new JTextField();
this.assignBtn = new JButton("Assign");
this.assignBtn.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent event)
{
String name = songNameField.getText();
int length = Integer.parseInt(parsesongLengthField.getText());
...
}
});
this.add(songNameField);
this.add(songLengthField);
this.add(assignBtn);
}
}
I am learning Java with GUI using JFrame, I would like to seek help regarding on how to call an ActionListener using an ActionListener. Here is some of my codes. The bottom part has the two action listeners and I added a simple comment for easy understanding.
package onlinedelivery;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainMenu extends JFrame {
public JButton mainMenuButton;
public JButton exitButton;
public MainMenuButtonHandler mmHandler;
public ExitButtonHandler exHandler;
public static final int width = 400;
public static final int heigth = 300;
public MainMenu() {
Font bigFont = new Font("Arial",Font.BOLD,12);
mainMenuButton = new JButton("Main Menu");
mmHandler = new MainMenuButtonHandler();
mainMenuButton.addActionListener(mmHandler);
exitButton = new JButton("Exit");
exHandler = new ExitButtonHandler();
exitButton.addActionListener(exHandler);
setTitle("Main Menu");
Container pane = getContentPane();
pane.setLayout(new GridLayout(5,2));
pane.add(mainMenuButton);
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class MainMenuButtonHandler implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
// ExitButtonHandler should be called here
// When I click Main Menu Button Handler, ExitButtonHandler shall perform
}
}
public class ExitButtonHandler implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}
If both Actions logic is the same you can define just one and use it for both menu and button.
If not you can extend one action from another
public class MainMenuButtonHandler extends ExitButtonHandler {
#Override public void actionPerformed(ActionEvent e) {
// An additional logic here
super.actionPerformed(e);
}
}
You can use the doClick() method in JButton (inherited from AbstractButton)
With that alter the Handler Class of MainMenuButton like this:
public class MainMenuButtonHandler implements ActionListener {
private JButton exitButton;
public void setExitButton(JButton exitButton){
this.exitButton = exitButton;
}
#Override public void actionPerformed(ActionEvent e) {
//Do your work and invoke Click of exitButton
this.exitButton.doClick();
}
}
Also the MainMenu():
exitButton = new JButton("Exit");
exHandler = new ExitButtonHandler();
exitButton.addActionListener(exHandler);
mainMenuButton = new JButton("Main Menu");
mmHandler = new MainMenuButtonHandler();
mmHandler.setExitButton(exitButton) // newly added
mainMenuButton.addActionListener(mmHandler);
public class buttonInitialization extends JFrame {
public JButton[] button;
public buttonInitialization() {
setLayout(new FlowLayout());
JButton[] button = new JButton[2];
button[0] = new JButton("");
button[0].setText("dsadsa");
button[0].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
button[0].setText("dsaadsdsa");
}
I cannot access this button[0] in action listener. How can I do that???
Make button variable final.
final JButton[] button = new JButton[2];
That is a requirement because anonymous inner classes (like your new ActionListener()) can access outer class variables only if they are final.
EDIT I tried to compile and it works. Here it goes again:
final JButton[] button = new JButton[2];
button[0] = new JButton("");
button[0].setText("dsadsa");
button[0].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
button[0].setText("dsaadsdsa");
}
});
public class buttonInitialization extends JFrame {
public JButton[] button;
public buttonInitialization() {
setLayout(new FlowLayout());
JButton[] button = new JButton[2];
button[0] = new JButton("");
button[0].setText("dsadsa");
for(int i = 0; i< button.length; ++i)
button[i].addActionListener(new MyActionListener(button[i]));
}
private class MyActionListener implements ActionListener
{
private JButton button;
public MyActionListener(JButton button)
{
this.button = button;
}
#Override
public void actionPerformed(ActionEvent arg0) {
this.button.setText("dsaadsdsa");
}
}
I cannot seem to make the Exit Button work and thus my program does not compile. If I comment out everything related to the exit button the program works and functions properly. All other buttons work. What is wrong with my Exit Button?
/**
* Write a description of class Converterr here.
*
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
public class Converterr
{
private JLabel usdL, pesosL, eurosL;
private JTextField usdTF, pesosTF, eurosTF;
private JButton pesosB, eurosB, exitB;
PesosButtonHandler pbHandler;
EurosButtonHandler eubHandler;
ExitButtonHandler ebHandler;
public void driver()
{
JFrame c = new JFrame ("Currency Converter");
c.setSize(400,300);
c.setDefaultCloseOperation(c.EXIT_ON_CLOSE);
//Content Pane
Container cp = c.getContentPane ( );
cp.setLayout ( new GridLayout (5,2) );
pesosL = new JLabel ("Pesos: ", SwingConstants.RIGHT);
usdL = new JLabel ("USD: ", SwingConstants.RIGHT);
eurosL = new JLabel ("Euros: ", SwingConstants.RIGHT);
usdTF = new JTextField(8);
pesosTF = new JTextField(8);
eurosTF = new JTextField(8);
pesosTF.setEditable(false);
eurosTF.setEditable(false);
pesosB = new JButton ("Convert to Pesos");
eurosB = new JButton ("Convert to Euros");
exitB = new JButton ("Exit");
// add to content pane container
cp.add(usdL);
cp.add(usdTF);
cp.add(pesosL);
cp.add(pesosTF);
cp.add(eurosL);
cp.add(eurosTF);
cp.add(pesosB);
cp.add(eurosB);
cp.add(exitB);
c.setVisible(true);
//Instantiate Listeners
pbHandler = new PesosButtonHandler();
eubHandler = new EurosButtonHandler();
ebHandler = new ExitButtonHandler();
pesosB.addActionListener(pbHandler);
eurosB.addActionListener(eubHandler);
exitB.addActionListener(ebHandler);
}
//action listener interfaces
private class PesosButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
double inusd;
double outpesos;
inusd = Double.parseDouble(usdTF.getText() );
outpesos = inusd * 12.31;
pesosTF.setText(Double.toString(outpesos));
}
}
private class EurosButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
double inusd, outeuros;
inusd = Double.parseDouble(usdTF.getText() );
outeuros = inusd * .78;
eurosTF.setText(Double.toString(outeuros));
}
}
private class ExitButtonHandler implements ActionListener
{
public void ActionPerformed (ActionEvent e)
{
System.exit(0);
}
}
public static void main (String [ ] args)
{
Converterr conv = new Converterr();
conv.driver();
}
}
Error Message:
Converterr.ExitButtonHandler is not abstract and does not override
abstract method actionPerformed(java.awt.event.ActionEnvt) in java.awt.event.ActionListener
public void ActionPerformed (ActionEvent e)
You have a typo in the method name. It should be:
public void actionPerformed (ActionEvent e)