How to make these Buttons function when pressed with a key? - java

This is the code.
The button doesnt work with key, if i dont click it first. It would
be great if you could help me.
I used eclipse when i created this frame
This is just an example code, but I just want to know how it functions
For any more detalis, ask here.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class ExampleApp {
private JFrame frmHi;
private JTextField textField;
private JButton btnAnother;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleApp window = new ExampleApp();
window.frmHi.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ExampleApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHi = new JFrame();
frmHi.setTitle("Hi");
frmHi.setBounds(100, 100, 450, 300);
frmHi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHi.getContentPane().setLayout(null);
JButton btnEnter = new JButton("Enter");
btnEnter.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
textField.setText("You pressed enter");
}
}
});
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("Hi there from button");
}
});
btnEnter.setBounds(119, 63, 89, 23);
frmHi.getContentPane().add(btnEnter);
textField = new JTextField();
textField.setEnabled(false);
textField.setEditable(false);
textField.setBounds(108, 30, 173, 20);
frmHi.getContentPane().add(textField);
textField.setColumns(10);
btnAnother = new JButton("Backspace");
btnAnother.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_BACK_SPACE){
textField.setText("you pressed backspace");
}
}
});
btnAnother.setBounds(119, 119, 89, 23);
frmHi.getContentPane().add(btnAnother);
}
}

Your KeyListener addded to JButton so it works only when the button has focus (after click).
It's better to define KeyBindings for the keys you have to process.

Related

java open a frame from another class

So I am trying to just make it so when I click a button it will open a frame from another class my filechooser frame just won't open.
This is the class called mainFrame:
package javatut;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class mainFrame {
private JFrame frmMainwindow;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame window = new mainFrame();
window.frmMainwindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainFrame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmMainwindow = new JFrame();
frmMainwindow.setTitle("Mainwindow");
frmMainwindow.setBounds(100, 100, 280, 150);
frmMainwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMainwindow.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
myButtonAction();
}
});
btnBrowse.setBounds(155, 11, 100, 23);
frmMainwindow.getContentPane().add(btnBrowse);
textField = new JTextField();
textField.setBounds(10, 12, 135, 20);
frmMainwindow.getContentPane().add(textField);
textField.setColumns(10);
}
private void myButtonAction(){
Toolkit.getDefaultToolkit().beep();
}
}
And this is the FileChooser class called simply frame:
package javatut;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class frame {
private JFrame frmFilechooser;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame window = new frame();
window.frmFilechooser.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmFilechooser = new JFrame();
frmFilechooser.setTitle("FileChooser");
frmFilechooser.setBounds(100, 100, 470, 350);
frmFilechooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFilechooser.getContentPane().setLayout(new BorderLayout(0, 0));
JFileChooser fileChooser = new JFileChooser();
frmFilechooser.getContentPane().add(fileChooser);
}
}
The easiest and most logical solution is to change the myButtonAction() method to:
private void myButtonAction() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(frmMainwindow);
if (result==JFileChooser.APPROVE_OPTION) {
// do something with the chosen file ..
}
}
If I understand you correctly, you're just missing two lines. The first in mainFrame's myButtonAction:
private void myButtonAction(){
// Toolkit.getDefaultToolkit().beep();
new frame();
}
And the other in frame's initialize:
private void initialize() {
frmFilechooser = new JFrame();
frmFilechooser.setTitle("FileChooser");
frmFilechooser.setBounds(100, 100, 470, 350);
frmFilechooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFilechooser.getContentPane().setLayout(new BorderLayout(0, 0));
JFileChooser fileChooser = new JFileChooser();
frmFilechooser.getContentPane().add(fileChooser);
frmFilechooser.setVisible(true);
}
(I just added the setVisible line at the bottom)

Opening a different frame with a button in Java

I am trying to open the menu frame using a button on the main frame. I added an event to the button and I tried calling the other class but it keeps giving me an error of ":: expected after this token"
This is my main frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
public static JPanel mainPane;
public final JButton menuButton = new JButton("New button");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
mainPane = new JPanel();
mainPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(mainPane);
mainPane.setLayout(null);
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(String[] args);
}
});
menuButton.setBounds(76, 89, 104, 32);
mainPane.add(menuButton);
}
}
And this is my menu frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class Menu extends JFrame {
public static JPanel menuPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Menu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuPane = new JPanel();
menuPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(menuPane);
menuPane.setLayout(null);
JLabel menuTitle = new JLabel("Menu");
menuTitle.setBounds(194, 11, 46, 14);
menuPane.add(menuTitle);
}
}
change your action event to this.no need to call main method .create a new instance of Menu class instead.
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu menu = new Menu();
menu.setVisible(true);
}
});
if you relly want to call main method then use
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(new String[0]);
}
});
the error is here
Menu.main(String[] args);//error
this is not a correct way of passing arguments to a methods.this is declaration of parameter list.
you can correct error by changing it to ,
String args[] = null;
Menu.main(args); //correct

Java Swing processing status

I am trying to implement a swing frame. In this, I want to display a processing status in a textPanel using a different thread while performing the needed task. I tried the following code. Of course there is something wrong with the logic. Please provide me with the proper approach
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleSwing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(0, 31, 434, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
processing=true;
Processingstatus ps=new Processingstatus();
ps.start();
/*perform the actual task*/
processing=false;
}
});
btnNewButton.setBounds(174, 74, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
class Processingstatus extends Thread{
public void run() {
try {
while(SampleSwing.processing) {
SampleSwing.textField.setText("Processing");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing..");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing...");
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
First I thought, "you should be using a SwingWorker, as it has methods to handle progress and EDT updates..."
But when I looked closer, you don't actually really care about the process itself, you just want some where to show that a process is running...They are two separate entities, that are only related because one (the UI updates) will run so long as the other is running.
So, instead, I used a javax.swing.Timer. This allows me to schedule an event to occur every n milliseconds and have that triggered in the EDT, nice and clean...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing = false;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SampleSwing() {
initialize();
}
private Timer processTimer;
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(25);
frame.add(textField, gbc);
processTimer = new Timer(500, new ActionListener() {
private StringBuilder dots = new StringBuilder(3);
#Override
public void actionPerformed(ActionEvent e) {
dots.append(".");
if (dots.length() > 3) {
dots.delete(0, dots.length());
}
textField.setText("Processing" + dots.toString());
}
});
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!processing) {
processing = true;
processTimer.start();
} else {
processTimer.stop();
processing = false;
textField.setText(null);
}
}
});
frame.add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
ps For the reason why your original code didn't work, see my comment in the above comments section ;)

How to make the JButton execute when holding the button?

First, my program is very simple. I just need to click or press Alt + Enter the JButton to increment the counter.
Here is the program so you can try it:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class holdDownClass implements ActionListener {
private static JButton exebouton;
private JTextArea ecran = new JTextArea();
private JScrollPane scrollecran = new JScrollPane(ecran);
private int counter = 0;
public static void main(String[] args) {
new holdDownClass();
}
private holdDownClass() {
// Window
JFrame frame = new JFrame("Name");
frame.setBounds(400, 350, 625, 355);
frame.setLayout(null);
Container container = frame.getContentPane();
// Panel
JPanel panneau = new JPanel();
panneau.setLayout(null);
panneau.setBounds(2, 42, 146, 252);
frame.add(panneau);
JLabel nglabel = new JLabel("Click or Press Alt+Enter");
nglabel.setBounds(5, 0, 200, 20);
panneau.add(nglabel);
// Button
exebouton = new JButton("Execute");
exebouton.setMnemonic(KeyEvent.VK_ENTER); // Shortcut: Alt + Enter
exebouton.setBounds(4, 18, 138, 47);
exebouton.addActionListener(this);
panneau.add(exebouton);
// Text Area
ecran.setEditable(true);
scrollecran.setBounds(150, 42, 467, 252);
container.add(scrollecran);
// Show
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
Object test = e.getSource();
if (test.equals(exebouton)) {
counter += 1;
ecran.setText(ecran.getText() + counter + "\n");
}
}
}
My objective is: Instead of repetitively pressing Alt+Enter, I want to hold Alt+Enter to increment the counter "quicker".
You could use a MouseListener, but, personally, I feel it's not the most appropriate means for achieving what it is you are trying to achieve, as it fights against the workings of the button.
Instead, you could attach a change listener to the buttons model and while the button's state remains pressed, cycle a Swing Timer....
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestButton04 {
public static void main(String[] args) {
new TestButton04();
}
private int counter = 0;
private Timer trigger;
private JButton btn;
public TestButton04() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
btn = new JButton("0");
trigger = new Timer(125, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
btn.setText(String.valueOf(counter));
}
});
trigger.setCoalesce(true);
trigger.setRepeats(true);
btn.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (btn.getModel().isPressed()) {
trigger.start();
} else {
trigger.stop();
}
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Here's the way you can do it-
private boolean mousePressed;
And a mouse listener-
exebouton.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
mousePressed = true;
new Thread() {
public void run() {
while (mousePressed) {
counter += 1;
ecran.setText(ecran.getText() + counter + "\n");
}
}
}.start();
}
public void mouseReleased(MouseEvent e) {
mousePressed = false;
}
});
That's it.

How can I use another classes variables in a java class?

Ok so I'm trying to get familier with Java, and I've made a simple thing where if you click a button then some text appears. How can I make it so the button and label are created in one class file, and put the code for when the button is clicked in another? Sorry if it sounds like a silly question.
Pastebin code:
package com.nate.derp;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Derp {
private JFrame frmHello;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Derp window = new Derp();
window.frmHello.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Derp() {
initialize();
}
public void initialize() {
frmHello = new JFrame();
frmHello.setTitle("Hello");
frmHello.setBounds(100, 100, 225, 160);
frmHello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHello.getContentPane().setLayout(null);
final JLabel helloLabel = new JLabel("Hello World!");
helloLabel.setVisible(false);
helloLabel.setBounds(40, 89, 145, 16);
frmHello.getContentPane().add(helloLabel);
final JButton btnClickMe = new JButton("Click Me!");
btnClickMe.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
helloLabel.setVisible(true);
}
});
btnClickMe.setBounds(54, 29, 117, 29);
frmHello.getContentPane().add(btnClickMe);
}
}
You can do this by creating a JButton and adding an ActionListener, which can be implemented by another class.
So you first create the JButton:
Jbutton button = new JButton("hello");
Then add the Actionlistener:
button.addActionListener(new MyListener());
Where MyListener is your implementation class
class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
...
}
}

Categories

Resources