nothing happen when i click the button java - java

I have an app and when you run it you take a panel in order to add 3 values and after you need press the OK button in order to continue.
I put a Click() method but when i push OK nothing happen.
Also to mention when i am deluging is working but when i export it as executable jar is not.
JFrame frame = new JFrame();
JLabel mlabel = new JLabel("Please provide xxxx",JLabel.CENTER);
JLabel uLabel = new JLabel("User ID:",JLabel.LEFT);
JPanel buttonField = new JPanel(new GridLayout (1,3));
JPanel userArea = new JPanel(new GridLayout (0,3));
frame.setLayout(new GridLayout (0,1));
buttonField.setLayout(new FlowLayout());
JButton confirm =new JButton("OK");
confirm.addMouseListener((MouseListener) new mouseClick());
buttonField.add(confirm);
App.insertText = new JTextField(20);
frame.add(mlabel);
userArea.add(uLabel);
userArea.add(insertText);
frame.add(buttonField);
frame.setSize(300,600);
App.credGet = false;
frame.setVisible(true);
and the Click :
public void mouseClicked(MouseEvent e) {
App.un = App.insertText.getText();
App.project = ((JTextComponent) App.insertProject).getText();
//App.pw = char[] App.insertPass.getPassword();
char[] input = App.insertPass.getPassword();
App.pw = "";
for (int i1 = 0; i1 < input.length; i1++){
App.pw = App.pw + input[i1];
}
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub

Line
confirm.addMouseListener((MouseListener) new mouseClick());
I suppose mouseClick is a class you posted in the example below. Why do you cast it to MouseListener? Does it not implement the MouseListener?
Anyway, you'll be better off replacing it with an ActionListener (anonymous class will work fine for you here), e.g.
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
...
}
});
Read Pros and cons of using ActionListener vs. MouseListener for capturing clicks on a JButton for more info

You should do something like this:
JButton button = new JButton("ButtonName");
//add button to frame
frame.add(button);
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});

You could either use an ActionListener using something like this:
anyBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Your Code Here
}
});
Or you could use a Lambda as shown here:
anyBtn.addActionListener(e ->
{
//Your Code Here
});
You should not be using a MouseListener in that way ever. That is not what it is intended for.

Related

Clicking a JButton from keyboard using KeyListener

Like I described in the title, I am required to make a JButton clicked if a key from a keyboard is pressed. For example :
ActionListenerClass actionListener = new ActionListenerClass();
KeyListenerClass actionListener = new KeyListenerClass();
JButton aButton = new JButton("A");
aButton.setActionCommand("A");
aButton.addActionListener(actionListener);
aButton.addKeyListener(keyListener);
When "A" is pressed from the keyboard, button A will perform a doClick() and send the action command to a private class of the action listener for event handling. Now I have read a lot of solution from stack overflow, and they all used key binding, which is to bind between an input map and an action map. The thing is I absolutely have to use a key listener with a private class but not the binding. The only thing I can guess now is the keyListener above have to somehow receive the keyboard input and perform doClick on the button it is binded to in a keyPressed method, which I have try and it didn't work at all.
Edit: Here's my entire code.
CalculatorViewController.java
import java.awt.*;
import java.awt.event.*;
import java.util.regex.Pattern;
import javax.swing.*;
/**Create the app GUI
* #author Bach Le
* #version 1.0
* #see java.awt, java.awt.event, javax.swing
* #since 12.0.1
*/
public class CalculatorViewController extends JPanel {
private JButton backSpaceButton;
public CalculatorViewController() {
Controller controller = new Controller();
KeyController keyController = new KeyController();
setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5,Color.black));//Adding the panel border
backSpaceButton = new JButton("\u21DA");
backSpaceButton.setPreferredSize(new Dimension(52,55));
backSpaceButton.setOpaque(false);//set transparency
backSpaceButton.setContentAreaFilled(false);
backSpaceButton.setBorderPainted(false);
backSpaceButton.setActionCommand("Backspace Button");//set the action command
backSpaceButton.addActionListener(controller);//add action listener
backSpaceButton.setToolTipText("Backspace (Alt+B)");//set tooltip text
backSpaceButton.setFont(font);//set the font
backSpaceButton.addKeyListener(keyController);
add(backSpaceButton) ;
}
private class Controller implements ActionListener{
public void actionPerformed(ActionEvent e) {
//event handling here
}
}
private class KeyController implements KeyListener{
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==65) {
backSpaceButton.doClick();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
2.Calculator.java
public class Calculator {
public static void main(String[] args) {
CalculatorViewController pane = new CalculatorViewController();
JFrame frame = new JFrame("Calculator");
frame.setContentPane(pane);
frame.setSize(380, 520);
frame.setLocationByPlatform(true);
frame.setResizable(true);
frame.setVisible(true);
}
}
Focus on CalculatorViewController, I am trying to make backSpaceButton clicked when A is pressed (Of course it is the actual backspace button but I will fix it later), so it will send its action command to the action listener registered to it, which will be processed in the method of Controller inner class. I am not sure the proper way to achieve this.
Adding a KeyListener will only work for components with focus. You would not want to add the KeyListener to the JButtons, because only one JButton will be in focus.
For just setting a value you could use setMnemonic but then you would have to use a modifier (such as 'alt) when you press the key.
The 'correct' way to do this is to use key bindings
Here is an example with two buttons.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonKeys{
public void buildGui(){
JFrame frame = new JFrame("key buttons");
JPanel panel = new JPanel(new BorderLayout());
JButton a = new JButton("A");
a.addActionListener(evt->{ System.out.println("a pressed");});
JButton b = new JButton("B");
b.addActionListener(evt->{ System.out.println("b pressed");});
panel.add(a, BorderLayout.EAST);
panel.add(b, BorderLayout.WEST);
frame.setContentPane(panel);
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KeyStroke us = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false);
panel.getInputMap().put(us, "A");
panel.getActionMap().put("A", new AbstractAction(){
#Override
public void actionPerformed(ActionEvent evt){
a.doClick();
}
});
KeyStroke us2 = KeyStroke.getKeyStroke(KeyEvent.VK_B, 0, false);
panel.getInputMap().put(us2, "B");
panel.getActionMap().put("B", new AbstractAction(){
#Override
public void actionPerformed(ActionEvent evt){
b.doClick();
}
});
a.setFocusable(false);
b.setFocusable(false);
}
public static void main(String[] args){
EventQueue.invokeLater( new ButtonKeys()::buildGui);
}
}
I made the buttons to not obtain focus because if they get focus then their input map will be used.
This code should work for you. For the KeyListener I used a KeyAdapter more here as it is more convenient if you simply need to use one of the methods. You can of course move the Listeners to separate own classes if needed, but the behavior would stay the same.
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("A");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
btn.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 'A' || e.getKeyChar() == 'a') {
((JButton) e.getSource()).doClick();
}
}
});
panel.add(btn);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 800, 600);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
If you really need to use a KeyListener, it would look like this:
btn.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 'A' || e.getKeyChar() == 'a') {
((JButton) e.getSource()).doClick();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
});

Java 8 - Losing all keyboard input or focus after switching windows

I'm running an application with similar behaviour to that in the test case below.
The problem is that when you switch focus to a different window by clicking on it and keeping the below application frame in view and then click directly into the text field with the focusGained listener, close the dialog and then all key input will be lost to the all of the text fields in the application.
If you click anywhere in the application first or the icon in the task bar to gain focus back then this does not occur.
This is Java 8 specific - in Java 7 it will not lose focus, not sure about java 9 but that is not an option anyway
The test case below demonstrates this behaviour.
public class FocusTest extends JFrame
{
JTextField noFocus;
public static void main(String[] args)
{
FocusTest ft = new FocusTest();
ft.setVisible(true);
}
public FocusTest()
{
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(100,100,300,150);
setLayout(new GridLayout(3,1, 2, 2));
setTitle("Losing keyboard...");
noFocus = new JTextField();
add(noFocus);
JTextField jft = new JTextField();
jft.addFocusListener(new FocusAdapter()
{
#Override
public void focusGained(FocusEvent e)
{
createDialog().setVisible(true);
noFocus.requestFocusInWindow();
}
});
add(jft);
JButton jb = new JButton("OPEN");
jb.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("OPEN"))
createDialog().setVisible(true);
}
});
add(jb);
}
private JDialog createDialog()
{
final JDialog jd = new JDialog(this, true);
jd.setLocationRelativeTo(this);
jd.setLayout(new BorderLayout());
jd.getContentPane().add(new JTextField(), BorderLayout.CENTER);
JButton jb = new JButton("Close");
jb.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Close"))
jd.dispose();
}
});
jd.getContentPane().add(jb, BorderLayout.SOUTH);
jd.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
jd.pack();
return jd;
}
}
Not exactly sure what's happening, but one solution is to use a SwingUtilities.invokeLater():
#Override
public void focusGained(FocusEvent e)
{
noFocus.requestFocusInWindow();
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createDialog().setVisible(true);
}
});
}
This will allow the text field to get focus properly before the dialog is made visible.

Method for MouseListeners and KeyListeners not working with .addMouseListener for Buttons on a Jpanel, Java

I have been having difficulty with making a method of Listeners to use repetitively in my code. Also, I am new to this, so I am very sorry for anything I leave out on this. Though, now here is my method for the Listeners:
public static void keysEvents(Optional<String> output)
{
MouseListener mouseEvents = new MouseAdapter()
{
public void mouseClick (MouseEvent mouseEvent)
{
Integer mouseModifiers = mouseEvent.getModifiers();
if ((mouseModifiers & InputEvent.BUTTON1_MASK) ==
InputEvent.BUTTON1_MASK)
{
if (output == null)
{
System.out.println("click");
}
//more options...
}
}
public void mouseRelease (MouseEvent mouseEvent)
{
}
};
//More listeners...
}
EDITED VERSION:
public static MouseListener keysEvents(Optional<String> output)
{
MouseListener mouseEvents = new MouseAdapter()
{
public void mouseClick (MouseEvent mouseEvent)
{
Integer mouseModifiers = mouseEvent.getModifiers();
if ((mouseModifiers & InputEvent.BUTTON1_MASK) ==
InputEvent.BUTTON1_MASK)
{
if (output == null)
{
System.out.println("click");
}
//more options...
}
}
public void mouseRelease (MouseEvent mouseEvent)
{
}
};
//More listeners...
return mouseEvents;
//How would I have it return different listeners?
}
Here is the code for the program's window:
JPanel MainP = new JPanel();
MainP.setLayout(new GridLayout(4, 2, 100, 30));
frame.setLayout(new GridLayout(1, 2));
frame.setBackground(Color.blue);
JPanel _B1_ = new JPanel();
JPanel _B2_ = new JPanel();
JPanel _B3_ = new JPanel();
JPanel _B4_ = new JPanel();
Button _Continue_ = new Button("Continue");
Button _Load_Game_ = new Button("Load Game");
Button _Settings_ = new Button("Settings");
Button _Exit_ = new Button("Exit");
_Continue_.addMouseListener(keysEvents(Optional.of(""))); //<edited here.
_Continue_.setBackground(Color.lightGray);
_Load_Game_.setBackground(Color.lightGray);
_Settings_.setBackground(Color.lightGray);
_Exit_.setBackground(Color.lightGray);
MainP.setBackground(Color.gray);
_B1_.setBackground(Color.gray);
_B2_.setBackground(Color.gray);
_B3_.setBackground(Color.gray);
_B4_.setBackground(Color.gray);
MainP.add(_B1_);
MainP.add(_Continue_);
MainP.add(_B2_);
MainP.add(_Load_Game_);
MainP.add(_B3_);
MainP.add(_Settings_);
MainP.add(_B4_);
MainP.add(_Exit_);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setUndecorated(!frameBorder);
frame.pack();
frame.setMinimumSize(new Dimension(_minX, _minY));
frame.setSize(windowX, windowY);
frame.add(MainP);
frame.setVisible(true);
Finally, if I asked wrongly in any way, please tell me; so I can do better, later on, when asking questions. Hope it does not suck hours out of your life like it did me.
You need to use ActionListener. This is a method used with JButtons, and I've used it many times. JButtons are more popular and are easier to use than Buttons. JButtons are part of the swing component. Here is an example of the usage of ActionListener:
JButton button = new JButton("Example"); //Create a JButton with the text "Example"
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Code to be executed upon press goes here
}
});
I'd also like to add to #camickr's comment; Java variables should always start with a lower case letter, and never start with _. For example, JButton continue = new JButton("Continue"); would be the proper way to declare and initialize a button. Any word after the beginning word in a varable name should be capitalized. For example, JButton continueButton = new JButton("Continue"); would be the proper naming.

Creating live counter within a JFrame

I tried searching for some sort of interactive JLabel. I want it to look like this:
I'm not sure what this is called or where I could find info on displaying this. I want it to print a refreshed number when the +/- is pressed. I have it working to print on the eclipse console but am unsure how to get it to print to the JFrame.
Here is some of the code:
String input = JOptionPane.showInputDialog("Please enter the number of laps.");
numLaps = Integer.parseInt(input);
//frame creation
JFrame f = new JFrame("Number of Laps");
f.setSize(550, 450);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
// label creation
JLabel label = new JLabel("You entered " + numLaps + " laps. Press + to add a lap. Press - to subtract a lap.", SwingConstants.CENTER);
label.setBounds(0,0,500,300);
f.add(label);
//display window
f.setVisible(true);
//button creation add
JButton add = new JButton ("+");
add.setBounds(350,250,50,50);
add.setPreferredSize(new Dimension(50,50));
add.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
// what happens when button is pressed
//numLaps++;
addToLap();
System.out.println(numLaps);
}
});
f.add(add);
//button creation subtract
JButton sub = new JButton ("-");
sub.setBounds(100,250,50,50);
sub.setPreferredSize(new Dimension(50,50));
sub.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
// what happens when button is pressed
//numLaps--;
subToLap();
System.out.println(numLaps);
}
});
f.add(sub);
& the add/sub methods:
private static void addToLap() {
// TODO Auto-generated method stub
numLaps++;
}
private static void subToLap() {
// TODO Auto-generated method stub
numLaps--;
}
You could try the following:
private int numLaps = 0 // Or the number you want initialize with
Then in your methods should assing the numLaps value to the JLabel like this:
this.myLabel.setText(String.valueOf(numLaps));
I hope it helps.

How to make a JButton do something

I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});

Categories

Resources