Pressing Enter to Continue - java

I have a JDialog which has two fields, username and password. I want to make the form like normal ones in which pressing enter will be like pressing continue.
I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.

I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.
than you have to invoke code for this button with method
JButton#doClick();
but better would be use KeyBindings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Test {
private static final long serialVersionUID = 1L;
private JDialog dialog = new JDialog();
private final JPanel contentPanel = new JPanel();
private Timer timer1;
private JButton killkButton = new JButton("Kill JDialog");
private JButton okButton = new JButton("OK");
public Test() {
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel buttonPane = new JPanel();
okButton.setActionCommand("OK");
buttonPane.add(okButton);
killkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
killkButton.setActionCommand("Kill JDialog");
buttonPane.add(killkButton);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
startTimer();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
dialog.setLayout(new BorderLayout());
dialog.getRootPane().setDefaultButton(okButton);
dialog.add(buttonPane, BorderLayout.SOUTH);
dialog.add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setLocation(100, 100);
dialog.setVisible(true);
setKeyBindings();
}
private void setKeyBindings() {
okButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
okButton.getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
startTimer();
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
}

JButton button = ...
JTextField password = ...
ActionListener buttonListener = ...
button.addActionListner(buttonListener);
password.addActionListener(buttonListener);
When enter is pressed in a JTextField, an action event is fired.

You can achieve this by adding an action listener to your textfield, like so.
JTextField field1 = new JTextField();
field1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//here is your method to continue
continue();
}
});

Related

cardlayout java runtime error

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Choice extends JDialog{
private JPanel panelMain;
private JButton btnPurchase;
private JButton btnRefund;
private JPanel cards;
final static String MainPage = "Main Page";
final static String PurchasePage = "Purchase Page";
final static String RefundPage = "Refund Page";
public Choice() {
setContentPane(panelMain);
setModal(true);
//getRootPane().setDefaultButton(buttonOK);
cards = new JPanel(new CardLayout());
cards.add(new Choice().ChoiceGUI(), MainPage);
cards.add(new Purchase().PurchaseGUI(), PurchasePage);
final CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, MainPage);
btnPurchase.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(cards, PurchasePage);
}
});
btnRefund.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//refund click function
}
});
}
public JPanel ChoiceGUI (){
return panelMain;
}
public static void main(String[] args){
Choice dialog = new Choice();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
}
That was Choice.java and below is Purchase.java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Purchase extends Choice{
private JPanel panelPurchase;
private JLabel lblamnt;
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btn5;
private JButton btn6;
private JButton btn7;
private JButton btn8;
private JButton btn9;
private JButton btn0;
private JButton btnClear;
private JButton btnSubmit;
/*
public Purchase(){
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "1");
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "2");
}
});
btn3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "3");
}
});
btn4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "4");
}
});
btn5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "5");
}
});
btn6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "6");
}
});
btn7.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "7");
}
});
btn8.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "8");
}
});
btn9.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "9");
}
});
btn0.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText(lblamnt.getText() + "0");
}
});
btnClear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblamnt.setText("");
}
});
btnSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//run code to confirm and show next screen to display current currency exchange.
}
});
}
*/
public JPanel PurchaseGUI(){
return panelPurchase;
}
}
im getting tons of repeating errors. I am still learning how to use cardlayouts.
I get these errors when the program runs. it compiles fine.
Exception in thread "main" java.lang.StackOverflowError
at java.awt.Window.init(Window.java:507)
at java.awt.Window.<init>(Window.java:436)
at java.awt.Window.<init>(Window.java:591)
at java.awt.Dialog.<init>(Dialog.java:665)
at java.awt.Dialog.<init>(Dialog.java:409)
at javax.swing.JDialog.<init>(JDialog.java:272)
at javax.swing.JDialog.<init>(JDialog.java:206)
at javax.swing.JDialog.<init>(JDialog.java:154)
at src.Choice.<init>(Choice.java:18)
at src.Choice.<init>(Choice.java:23) (repeating)
Exception in thread "main" Exception in thread "main"
i redid purchase.java to include a GETTER
and the Choice.java errors are at
public Choice() {
and...
cards.add(new Choice().ChoiceGUI(), MainPage);
What am i doing wrong? I have been stuck here for the entire day without progress.
I am trying to have it set up so when i push the buy button it loads the purchase form within the same window.
Seeing as how no one answered this question i was forced to figure it out. I did the cardlayouts and had to change the design.

Java Key Bindings can not be successfully implemented

The following is my project
public class KeyStrokeExample {
private JFrame jFrame;
private JPanel jPanel;
private JButton jButton;
private Action action;
public static void main(String[] args) {
KeyStrokeExample keyStrokeExample=new KeyStrokeExample();
keyStrokeExample.initLayout();
keyStrokeExample.test();
}
private void initLayout() {
jFrame=new JFrame("frame");
jPanel=new JPanel();
jButton=new JButton("test");
jPanel.add(jButton);
jFrame.add(jPanel);
jFrame.pack();
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void test() {
action=new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
};
int condition = JComponent.WHEN_FOCUSED;
InputMap inputMap = jPanel.getInputMap(condition);
ActionMap actionMap = jPanel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK ),"DELETE");
actionMap.put( "DELETE", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
});
}
}
I practice from https://tips4java.wordpress.com/2008/10/10/key-bindings/
I don't know why the program not print "test"
when I remove
action=new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
};
it can work print test"
I want to understand what happened
Thanks

How to start and stop a threads in netbeans from a jButton click

I write Java desktop app to fetch and post some data from my online rails backend app. The App have to call a get request every 5 second to update the relay state(example Arduino). here is my code:
public class GUI extends javax.swing.JFrame {
private Serial serial = null;
private Service service = null;
private volatile boolean connected = false;
private Thread updateThread;
public GUI() {
initComponents();
init_serial();
service = new Service();
updateThread = new Thread() {
public void run() {
while (connected) {
updateJob();
}
}
};
updateThread.start();
}
private void init_serial() {
serial = new Serial();
serial.searchForPorts();
serial.connect();
serial.initIOStream();
serial.initListener();
}
private void updateJob() {
ActionListener actListner = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
updateState();
}
};
Timer timer = new Timer(5000, actListner);
timer.start();
}
private void updateState() {
String portState = service.get_port_state();
serial.write(portState);
System.out.println(portState);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
connected = true;
logger.setText(null);
logger.setText("connected");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
logger.setText(null);
logger.setText("disconnected");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
}
but it didn't work as expected, my question is how can i fix my code and how to put the thread correctly?
You can use a Thread object in class's member and you can start and stop in button click action events. Here is the sample to start/stop thread.
public class GUI extends javax.swing.JFrame {
Thread updateThread = null;
public GUI() {
JButton btnStart = new JButton("Start");
JButton btnStop = new JButton("Stop");
JPanel jPanel = new JPanel();
jPanel.setBounds(0, 0, 100, 200);
jPanel.add(btnStart);
jPanel.add(btnStop);
add(jPanel);
btnStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
System.out.println("Work updated");
try {
Thread.sleep(1000);//Time to wait for next routine
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
updateThread.start();
}
});
btnStop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateThread.stop();
}
});
setVisible(true);
setBounds(0, 0, 100, 200);
}
public static void main(String[] args) {
new GUI();
}
}
You can possibly use thread.join();

JTextField is not editable in a JPopupMenu

When I add a JtextField in a JPopupMenu, I can't edit the text when the popup is displayed. Anyone know why?
Here's a code example:
public static void main(String[] args) {
JFrame frame = new JFrame();
JPopupMenu popup = new JPopupMenu();
JTextField field = new JTextField("My text");
popup.insert(field, 0);
popup.setVisible(true);
}
Seems to work alright for me:
Check out this example (right click anywhere on the content pane to make the popup visible:
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class Main {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPopupMenu popup = new JPopupMenu();
final JTextField field = new JTextField(20);
field.setText("My text");
popup.insert(field, 0);
popup.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
field.requestFocusInWindow();
field.selectAll();
}
});
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
((JComponent) frame.getContentPane()).setComponentPopupMenu(popup);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main().initUI();
}
});
}
}
to avoiding any speculations
I can't edit the text when the popup is displayed. Anyone know why?
JPopup nested JPopupMenu must has a parent, my code example (reason why is there hardcodes frame.setLocation(150, 100);)
in this form works correctly, JPopup accepting JFrames coordinates
change this code inside Swing Action
from
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
to
popupMenu.setVisible(true);
//popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
then PopupMenuListener firing and events, but JMenuItems aren't repainted too
from code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class PopupSample {
private JPopupMenu popupMenu = new JPopupMenu();
private javax.swing.Timer timer = null;
private JFrame frame = new JFrame("Popup Example");
public PopupSample() {
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Selected: "
+ actionEvent.getActionCommand());
}
};
PopupMenuListener popupMenuListener = new PopupMenuListener() {
#Override
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
System.out.println("Canceled");
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Invisible");
}
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Visible");
}
};
popupMenu.addPopupMenuListener(popupMenuListener);
JSeparator jSeparator = new JSeparator(JSeparator.VERTICAL);
jSeparator.setPreferredSize(new Dimension(2, 100));
jSeparator.setBackground(Color.red);
popupMenu.add(jSeparator);
JMenuItem cutMenuItem = new JMenuItem("Cut");
cutMenuItem.addActionListener(actionListener);
popupMenu.add(cutMenuItem);
cutMenuItem.setBorder(null);
JMenuItem copyMenuItem = new JMenuItem("Copy");
copyMenuItem.addActionListener(actionListener);
popupMenu.add(copyMenuItem);
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.addActionListener(actionListener);
pasteMenuItem.setEnabled(false);
popupMenu.add(pasteMenuItem);
popupMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find");
findMenuItem.addActionListener(actionListener);
popupMenu.add(findMenuItem);
JTextField text = new JTextField("text");
popupMenu.add(text);
MouseListener mouseListener = new JPopupMenuShower(popupMenu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(mouseListener);
frame.setLocation(150, 100);
frame.setSize(350, 250);
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(1000, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
}
});
}
};
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
PopupSample popupSample = new PopupSample();
}
});
}
static class JPopupMenuShower extends MouseAdapter {
private JPopupMenu popup;
public JPopupMenuShower(JPopupMenu popup) {
this.popup = popup;
}
private void showIfPopupTrigger(MouseEvent mouseEvent) {
if (popup.isPopupTrigger(mouseEvent)) {
popup.show(mouseEvent.getComponent(), mouseEvent.getX(),
mouseEvent.getY());
}
}
#Override
public void mousePressed(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
#Override
public void mouseReleased(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
}
}

JFrame.setVisible(false) and Robot.createScreenCapture timing

I'm trying to capture the screen without including my application's window. To do this I first call setVisible(false), then I call the createScreenCapture method, and finally I call setVisible(true). This isn't working however and I'm still getting my applications window in the screen capture. If I add a call to sleep this seems to resolve the issue, but I know this is bad practice. What is the right way to do this?
Code:
setVisible(false);
BufferedImage screen = robot.createScreenCapture(rectScreenSize);
setVisible(true);
Have you tried to use SwingUtilities.invokeLater() and run the capture inside of the runnable passed as an argument? My guess is that the repaint performed to remove your application is performed right after the end of the current event in the AWT-EventQueue and thus invoking the call immediately still captures your window. Invoking the createCapture in a delayed event through invokeLater should fix this.
you have to delay this action by implements Swing Timer, for example
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class CaptureScreen implements ActionListener {
private JFrame f = new JFrame("Screen Capture");
private JPanel pane = new JPanel();
private JButton capture = new JButton("Capture");
private JDialog d = new JDialog();
private JScrollPane scrollPane = new JScrollPane();
private JLabel l = new JLabel();
private Point location;
private Timer timer1;
public CaptureScreen() {
capture.setActionCommand("CaptureScreen");
capture.setFocusPainted(false);
capture.addActionListener(this);
capture.setPreferredSize(new Dimension(300, 50));
pane.add(capture);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(pane);
f.setLocation(100, 100);
f.pack();
f.setVisible(true);
createPicContainer();
startTimer();
}
private void createPicContainer() {
l.setPreferredSize(new Dimension(700, 500));
scrollPane = new JScrollPane(l,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
d.add(scrollPane);
d.pack();
d.setVisible(false);
d.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
f.setVisible(true);
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
capture.doClick();
f.setVisible(false);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("CaptureScreen")) {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // gets the screen size
Robot r;
BufferedImage bI;
try {
r = new Robot(); // creates robot not sure exactly how it works
Thread.sleep(1000); // waits 1 second before capture
bI = r.createScreenCapture(new Rectangle(dim)); // tells robot to capture the screen
showPic(bI);
saveImage(bI);
} catch (AWTException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
private void saveImage(BufferedImage bI) {
try {
ImageIO.write(bI, "JPG", new File("screenShot.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
private void showPic(BufferedImage bI) {
ImageIcon pic = new ImageIcon(bI);
l.setIcon(pic);
l.revalidate();
l.repaint();
d.setVisible(false);
//location = f.getLocationOnScreen();
//int x = location.x;
//int y = location.y;
//d.setLocation(x, y + f.getHeight());
d.setLocation(150, 150);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
d.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CaptureScreen cs = new CaptureScreen();
}
});
}
}

Categories