Hi I have this loop that created buttons for each of the number between an interval and I was wondering how do I access the action listener of these buttons?
////FOR EACH DATE
for (int i=(timeLine.getInterval())[0]; i<(timeLine.getInterval())[1] +1; i++)
{
listPanel.add(new JButton(""+i));
}
Normaly I would do this:
button.addActionListener(new ActionListener()...
but I dont have a name set to any of my buttons because the ammount is indefinite. Thank you:)
You need to write a generic ActionListener that can be used for all the buttons. The ActionListener will get the source of the event and then use information from the button to do process.
For example here is how you can create a simple "calculator panel" by using buttons that have the same functionality:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(30, 30) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You need to assign the new button to temp variable, and you need to be able to use the "amount" in the action:
for (int i=(timeLine.getInterval())[0]; i<(timeLine.getInterval())[1] +1; i++)
{
JButon b = new JButton(""+i);
final int amount = i;
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something with amount
aplyAmount(amount);
}
});
listPanel.add(b);
}
Related
I tried fixing this in so many ways, and tried searching for answers everywhere, my color buttons are working, but same way built number buttons do not....
package tralala;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class DugmiciKojiMenjajuBoju extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 4317497849622426733L;
private JButton dugme1;
private JButton dugme2;
private JButton dugme3;
private JPanel panel;
private JOptionPane a;
private JPanel panel1;
private JButton dugmeBroja0;
private JButton dugmeBroja1;
private JButton dugmeBroja2;
private JButton dugmeBroja3;
private JButton dugmeBroja4;
private JButton dugmeBroja5;
private JButton dugmeBroja6;
private JButton dugmeBroja7;
private JButton dugmeBroja8;
private JButton dugmeBroja9;
private JButton dugmeZaPlus;
private JButton dugmeZaMinus;
private JButton dugmeZaPuta;
private JButton dugmeZaPodeljeno;
private JButton dugmeZaJednako;
private JTextField polje;
DugmiciKojiMenjajuBoju(){
getContentPane().setBackground(Color.white);
this.setLayout(new FlowLayout());
a = new JOptionPane("");
dugme1 = new JButton("zuta");
dugme2 = new JButton("plava");
dugme3 = new JButton("crvena");
dugmeBroja0 = new JButton("0");
dugmeBroja1 = new JButton("1");
dugmeBroja2 = new JButton("2");
dugmeBroja3 = new JButton("3");
dugmeBroja4 = new JButton("4");
dugmeBroja5 = new JButton("5");
dugmeBroja6 = new JButton("6");
dugmeBroja7 = new JButton("7");
dugmeBroja8 = new JButton("8");
dugmeBroja9 = new JButton("9");
dugmeZaPlus = new JButton("+");
dugmeZaMinus = new JButton("-");
dugmeZaPuta = new JButton("*");
dugmeZaPodeljeno = new JButton("/");
dugmeZaJednako = new JButton("=");
polje = new JTextField("", 20);
panel = new JPanel();
panel1 = new JPanel();
dugmeBroja0.setSize(50,50);
dugmeBroja1.setSize(50,50);
dugmeBroja2.setSize(50,50);
dugmeBroja3.setSize(50,50);
dugmeBroja4.setSize(50,50);
dugmeBroja5.setSize(50,50);
dugmeBroja6.setSize(50,50);
dugmeBroja7.setSize(50,50);
dugmeBroja8.setSize(50,50);
dugmeBroja9.setSize(50,50);
panel1.add(dugmeBroja0);
panel1.add(dugmeBroja1);
panel1.add(dugmeBroja2);
panel1.add(dugmeBroja3);
panel1.add(dugmeBroja4);
panel1.add(dugmeBroja5);
panel1.add(dugmeBroja6);
panel1.add(dugmeBroja7);
panel1.add(dugmeBroja8);
panel1.add(dugmeBroja9);
panel1.add(dugmeZaPlus);
panel1.add(dugmeZaMinus);
panel1.add(dugmeZaPuta);
panel1.add(dugmeZaPodeljeno);
panel1.add(dugmeZaJednako);
panel1.add(polje);
panel1.setLayout(new FlowLayout(50, 0 ,0));
FlowLayout mojLayout = new FlowLayout(FlowLayout.CENTER , 20 , 20);
panel.setLayout(mojLayout);
panel.add(dugme1);
panel.add(dugme2);
panel.add(dugme3);
this.setTitle("Kalkulator Koji Menja Boju Pozadine");
this.setSize(500,500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.add(panel1);
this.add(panel);
dugme1.addActionListener(this);
dugme2.addActionListener(this);
dugme3.addActionListener(this);
polje.addActionListener(this);
panel.setBackground(Color.white);
panel1.setBackground(Color.white);
}
public static void main(String[] args) {
DugmiciKojiMenjajuBoju a = new DugmiciKojiMenjajuBoju();
a.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if( arg0.getSource() == dugme1){
panel.setBackground(Color.yellow);
panel1.setBackground(Color.yellow);
getContentPane().setBackground(Color.yellow);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D" ,"Postavili ste zutu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme2){
panel.setBackground(Color.blue);
panel1.setBackground(Color.blue);
getContentPane().setBackground(Color.blue);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste plavu", JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugme3){
panel.setBackground(Color.red);
panel1.setBackground(Color.red);
getContentPane().setBackground(Color.red);
a.setSize(200,200);
a.showMessageDialog(this, "Klikcite dalje :D","Postavili ste crvenu",JOptionPane.INFORMATION_MESSAGE);
}
else if(arg0.getSource() == dugmeBroja0){
polje.setText("0");
System.out.println("blabla");
}
}
}
My button 0 is not working... so i cannot continue writing the code.
My button 0 is not working... so i cannot continue writing the code.
You didn't add an ActionListener to the button.
However, before just fixing that problem you should simplify your code an learn how to use loops to create multiple components with the same functionality. Here is an example that creates a single ActionListener and add it to each button:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Also, don't use setSize() on your components. The layout manager is responsible for determining the size of a component.
You have never added ActionListener to that button, just to three color buttons and a JTextField polje
I think you didn't added this as the actionListener of dugmeBroja0:
you need this:
dugmeBroja0.addActionListener(this);
My application has 15 different buttons and I've been wondering if it's a good idea to have a individual class for each button listener?
I currently have only one class that handles all buttons using switch/case but it's hard to maintain and read.
I'm not huge fan of using anonymous classes - again because of the readability.
Any suggestions that can help me resolve this issue would be appreciated.
I'm using Java Swing if this matters.
You can use one class but it is not a good dsign because you need to apply a principle of separation of concerns. You want coherance in a class so that the methods are meaningfull and logical according to the business domain your are dealing with. Also in some cases the same action listener can handle many buttons.
Example: assuming I am building a calculator. I know that the behavior of operators is similar when they are clicked on. And so is it with the digits buttons. Therefore I can have some classes, let's say
public class OperationActionListener {
public void actionPerformed(ActionEvent e) {
// Handle what happens when the user click on +, -, * and / buttons
}
}
public class DigitActionListener {
public void actionPerformed(ActionEvent e) {
// Handle what happens when the user click on a digit button
}
}
etc.
Now in my user interface I will add an instance of the same action listener
JButton buttonPlus = new JButton("+")
JButton buttonMinus = new JButton("-");
...
JButton buttonOne = new JButton("1");
JButton buttonTwo = new JButton("2");
...
OperationActionListener operationListener = new OperationActionListener();
DigitActionListener digitListener = new DigitsActionListener();
buttonPlus.addActionListener(operationListener);
buttonMinus.addActionListener(operationListener);
....
buttonOne.addActionListener(digitListener);
buttonTwo.addActionListener(digitListener);
....
Hope this helps.
Here is an example of the same listener being used by multiple buttons:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
// button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Developing an application in swing, just a little query :-
I want to clear the current focus owner textfield using a button. It is possible to determine whether a textfield is the current focus owner or not using isFocusOwner() but how to clear the textfield which is currently on focus?
Thanks!!!
You might be able use a TextAction. A TextAction has access to the last text component that had focus. So then in the text action you just clear the text in the component. All the logic is fully contained in the one place.
Here is an example that demonstrates the concept of using a TextAction. In this case the number represented by the button is appended to the text field with focus:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class NumpadPanel extends JPanel
{
public NumpadPanel()
{
setLayout( new BorderLayout() );
JTextField textField1 = new JTextField(4);
JTextField textField2 = new JTextField(2);
JTextField textField3 = new JTextField(2);
JPanel panel = new JPanel();
panel.add( textField1 );
panel.add( textField2 );
panel.add( textField3 );
add(panel, BorderLayout.PAGE_START);
Action numberAction = new TextAction("")
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent textComponent = getFocusedComponent();
if (textComponent != null)
textComponent.replaceSelection(e.getActionCommand());
}
};
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setMargin( new Insets(20, 20, 20, 20) );
button.setFocusable( false );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Numpad Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new NumpadPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
In your case instead of using the replaceSelection() method you would just use the setText() method.
If you want to clear a textfield using the clicking of a button, you have to write the code to clear the textfield in the the ActionListener class's ActionPerformed method. This method is called when the button is pressed. But in order to press the button you have to get the focus from other component to this button. So in the method ActionPerformed you would get false to textField.isFocusOwner().
My suggestion to overcome this problem is:
add focus listeners to these 6 text fields.
declare a variable say lastFocused as type JTextField in initialise it to null in the Class that you are implementing all these.
write the following code to the focusListerners Overridden methods
void focusGained(FocusEvent e){
lastFocused = (JTextField) e.getComponent();
}
void focusLost(FocusEvent e){
lastFocused = null;
}
now in the ActionListener overridden method write the following:
void actionPerformed(ActionEvent e){
if(lastFocused != null){
lastFocused.setText("");
}
}
I feel this should solve your problem.
I want to append a value into a JTextField in Java. Something like:
String btn1="1";
textField.appendText(btn1);
I think you'll find setText is the answer. Just combine the current value with the new value:
textField.setText(textField.getText() + newStringHere);
If you text field is not editable, you could use:
textField.replaceSelection("...");
If it is editable you might use:
textField.setCaretPosition( textField.getDocument().getLength() );
textField.replaceSelection("...");
This would be slightly more efficient (than using setText()) because you are just appending text directly to the Document and would more resemble a JTextArea.append(...).
It would only result in a single DocumentEvent - insertUpdate().
You can also access the Document directly and do the insert:
Document doc = textField.getDocument();
doc.insertString(...);
but I find this more work because you also have to catch the BadLocationException.
Simple example, that also demonstrate the use of Key Bindings:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
// UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
I am simply trying to make an employee clock. I have a keypad of numbers 0-9 and a text field. I want to be able to click the numbers and the numbers will appear on the text field. This seems so easy but I can't find any answers for it.
I'm using netbeans and I created the design of the Jframe in the Design.
I added action events to all of the buttons.
I'm calling each button like Btn0 (the button with 0 on it, Btn1, etc etc.
You need to retrieve the JButton on which ActionEvent is fired and then append the text retrieved from the JButton to the JTextField. Here is the short Demo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class EClock extends JFrame
{
JTextField tf;
public void createAndShowGUI()
{
setTitle("Eclock");
Container c = getContentPane();
tf = new JTextField(10);
JPanel cPanel = new JPanel();
JPanel nPanel = new JPanel();
nPanel.setLayout(new BorderLayout());
nPanel.add(tf);
cPanel.setLayout(new GridLayout(4,4));
for (int i =0 ; i < 10 ; i++)
{
JButton button = new JButton(String.valueOf(i));
cPanel.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
String val = ((JButton)evt.getSource()).getText();
tf.setText(tf.getText()+val);
}
});
}
c.add(cPanel);
c.add(nPanel,BorderLayout.NORTH);
setSize(200,250);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
EClock ec = new EClock();
ec.createAndShowGUI();
}
});
}
}
Add action listener on your button first (double click on button in GUI Designer :) ):
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set text by calling setText() method for your textfield
textfield.setText("Desired text");
}
});
Regards.
Create an Action that can be shared by all the buttons. Something like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ButtonCalculator extends JFrame implements ActionListener
{
private JButton[] buttons;
private JTextField display;
public ButtonCalculator()
{
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( this );
button.setMnemonic( text.charAt(0) );
button.setBorder( new LineBorder(Color.BLACK) );
buttons[i] = button;
buttonPanel.add( button );
}
getContentPane().add(display, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setResizable( false );
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
display.replaceSelection( source.getActionCommand() );
}
public static void main(String[] args)
{
ButtonCalculator frame = new ButtonCalculator();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
I know nothing of netbeans, however, a search on google gave me this
Netbeans GUI Functionality
it seems to have the data needed, give it a read and no doubt you can figure out what needs to be amended for it to suit your purposes