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.
Related
I'm trying to make cookie clicker game and i'm at point where i want to program upgrades, for ex: when i buy first upgrade i want if i click once to get 2 cookies, before upgrade it was if i click once i get only 1 cookie. I'm not sure how to code that and also in the future i want to code even more upgrades. What i'm asking to someone help me to make peace of code that can be used to make clicking upgrades.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.*;
public class JavaApplication13 {
public static void main(String[] args) {
DBP prozor = new DBP();
prozor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prozor.setVisible(true);
}
}
class DBP extends JFrame {
private JLabel oznaka;
public DBP() {
setTitle("Cookie Clicker");
setSize(500, 150);
setLayout(new FlowLayout(FlowLayout.CENTER, 30, 20));
oznaka = new JLabel("No points!");
add(oznaka);
JButton dugme = new JButton("Click");
add(dugme);
JButton upgrade = new JButton("Buy upgrade!");
add(upgrade);
upgrade.setVisible(false);
dugme.addActionListener(new ActionListener() {
private int brojac;
#Override
public void actionPerformed(ActionEvent e) {
brojac++;
oznaka.setText("Points " + brojac);
if (brojac == 5) {
upgrade.setVisible(true);
}
}
});
upgrade.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
upgrade.setVisible(false);
System.out.println("SA");
}
});
}
}
The simplest way to do it, is to keep a boolean value if the user has clicked the upgrade button. If he did, increase "cookies" one more time.
public class JavaApplication13 {
public static void main(String[] args) {
// All swing applications must run on their own thread.
SwingUtilities.invokeLater(() -> {
DBP prozor = new DBP();
prozor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prozor.setVisible(true);
});
}
}
class DBP extends JFrame {
private JLabel oznaka;
private boolean upgraded; //whether user upgraded
public DBP() {
setTitle("Cookie Clicker");
setSize(500, 150);
setLayout(new FlowLayout(FlowLayout.CENTER, 30, 20));
oznaka = new JLabel("No points!");
add(oznaka);
JButton dugme = new JButton("Click");
add(dugme);
JButton upgrade = new JButton("Buy upgrade!");
add(upgrade);
upgrade.setVisible(false);
dugme.addActionListener(new ActionListener() {
private int brojac;
#Override
public void actionPerformed(ActionEvent e) {
brojac++;
if (upgraded)
brojac++;
oznaka.setText("Points " + brojac);
if (brojac == 5) {
upgrade.setVisible(true);
}
}
});
upgrade.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
upgrade.setVisible(false);
upgraded = true;
}
});
}
}
How do I make the Enter key trigger a JComboBox or JButton in a GUI rather than having to hit the Space key? I have an assortment of text fields and check boxes with buttons and combo boxes in between. I'd like to avoid having to switch between hitting space and enter and rather only have to hit enter for all components.
package koning.personal.dungeonsanddragons;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test {
JFrame window = new JFrame("testGUI");
JPanel windowPanel = new JPanel();
public static JLabel labelSize;
public static JComboBox<String> comboSize;
public static JLabel labelButton;
public static JButton buttonButton;
public test () {
super();
labelSize = new JLabel("Monster Size:");
String[] sizeChoices = { "None", "Tiny", "Small", "Medium", "Large", "Huge", "Colossal"};
comboSize = new JComboBox<String>(sizeChoices);
comboSize.setToolTipText("The creature's size.");
labelButton = new JLabel("Button:");
buttonButton = new JButton();
windowPanel.setLayout(new FlowLayout());
windowPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
windowPanel.add(labelSize);
windowPanel.add(comboSize);
windowPanel.add(labelButton);
windowPanel.add(buttonButton);
windowPanel.setVisible(true);
window.setSize(500, 500);
window.setLayout(new FlowLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.add(windowPanel);
comboSize.addActionListener(handler);
buttonButton.addActionListener(handler);
}
ActionHandler handler = new ActionHandler();
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent eventFocus){
if (eventFocus.getSource() == comboSize){
buttonButton.requestFocusInWindow();
}
if (eventFocus.getSource() == buttonButton){
comboSize.requestFocusInWindow();
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args) {
test GUITest = new test();
}
}
You can add a KeyListener and execute doClick
JButton btn = new JButton();
btn.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
btn.doClick();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
});
If the goal is to have something happen when the enter button is pressed (pressed once and something happens with all the components) then you can add a KeyListener to the JFrame:
JFrame frame = new JFrame("Examplpe");
//here you create and add the components to the frame
and then you can add a KeyListener:
frame.addKeyListener(new KeyListener(
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode == KeyEvent.VK_ENTER){//this is the if block I'm refering to in the following explanation
//do something with all the components
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {}
}
and then when you press Enter, the code inside the if block will be executed.
Hope this helps :)
I have a instance of a custom JLabel and i want to changes its text in all frames, but the text is changing only on the last opened frame. There's a way i can achieve this?
Here's what happens:
And my code:
App.java
package test;
import javax.swing.JFrame;
public class App extends JFrame {
protected static App app;
private String loggedUser;
private MyCustomLabel myCustomLabel;
public App() {
loggedUser = "User One";
myCustomLabel = new MyCustomLabel(loggedUser);
}
public static App getApp() {
return app;
}
public MyCustomLabel getMyCustomLabel() {
return myCustomLabel;
}
public String getLoggedUser() {
return loggedUser;
}
public void setLoggedUser(String loggedUser) {
this.loggedUser = loggedUser;
}
}
FrmApp.java
package test;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
*
* #author Marco
*/
public class FrmApp extends App {
public FrmApp() {
app = new App();
initComponents();
}
private void initComponents() {
setLayout(new FlowLayout());
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
btnFrmOne = new JButton("Open frmOne");
btnFrmOne.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FrmOne frmOne = new FrmOne();
frmOne.setVisible(true);
}
});
add(btnFrmOne);
btnFrmTwo = new JButton("Open frmTwo");
btnFrmTwo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FrmTwo frmTwo = new FrmTwo();
frmTwo.setVisible(true);
}
});
add(btnFrmTwo);
btnChangeUser = new JButton("Change user");
btnChangeUser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (App.getApp().getLoggedUser().equals("User One")) {
App.getApp().setLoggedUser("User Two");
} else {
App.getApp().setLoggedUser("User One");
}
App.getApp().getMyCustomLabel().refresh();
}
});
add(btnChangeUser);
}
private JButton btnFrmOne;
private JButton btnFrmTwo;
private JButton btnChangeUser;
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmApp().setVisible(true);
}
});
}
}
FrmOne.java
package test;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class FrmOne extends JFrame {
public FrmOne() {
initComponents();
}
private void initComponents() {
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(150, 100);
add(App.getApp().getMyCustomLabel());
}
}
FrmTwo.java
package test;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class FrmTwo extends JFrame {
public FrmTwo() {
initComponents();
}
private void initComponents() {
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(150, 100);
add(App.getApp().getMyCustomLabel());
}
}
MyCustomLabel.java
package test;
import javax.swing.JLabel;
public class MyCustomLabel extends JLabel {
public MyCustomLabel(String loggedUser) {
initComponents(loggedUser);
}
private void initComponents(String loggedUser) {
setText(loggedUser);
}
public void refresh() {
setText(App.getApp().getLoggedUser());
}
}
Update
This is what im doing now to do what i wanted.
App.java
public class App extends JFrame {
public App() {
User user = new User(1, "User One");
LoggedUser.getInstance().setUser(user);
initComponents();
}
public static void main(String[] args) {
new App().setVisible(true);
}
private void initComponents() {
setSize(200, 200);
setLocation(400, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton btn1 = new JButton("dlgOne");
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DlgOne dlgOne = new DlgOne(App.this, false);
dlgOne.setVisible(true);
}
});
JButton btn2 = new JButton("dlgTwo");
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DlgTwo dlgTwo = new DlgTwo(App.this, false);
dlgTwo.setVisible(true);
}
});
JButton btn3 = new JButton("change user");
btn3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (LoggedUser.getInstance().getUser().getId() == 1) {
User user = new User(2, "User Two");
LoggedUser.getInstance().setUser(user);
} else {
User user = new User(1, "User One");
LoggedUser.getInstance().setUser(user);
}
}
});
add(btn1);
add(btn2);
add(btn3);
}
}
MyCustomPanel.java
public class MyCustomPanel extends JPanel implements Observer {
private JLabel label;
public MyCustomPanel() {
initComponents();
}
#Override
public void update(Observable o, Object arg) {
//LoggedUser u = (LoggedUser) o;
//System.out.println(u.getUser().getId());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
label.setText(LoggedUser.getInstance().getUser().getName());
}
});
}
private void initComponents() {
LoggedUser.getInstance().addObserver(this);
label = new JLabel(LoggedUser.getInstance().getUser().getName());
add(label);
}
}
User.java
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DlgOne.java
public class DlgOne extends JDialog {
public DlgOne(Frame owner, boolean modal) {
super(owner, modal);
initComponents();
}
private void initComponents() {
setTitle("dlgOne");
setSize(200, 200);
setLocation(600, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
add(new MyCustomPanel());
}
}
DlgTwo.java
public class DlgTwo extends JDialog {
public DlgTwo(Frame owner, boolean modal) {
super(owner, modal);
initComponents();
}
private void initComponents() {
setTitle("dlgTwo");
setSize(200, 200);
setLocation(800, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
add(new MyCustomPanel());
}
}
LoggedUser.java
public class LoggedUser extends Observable {
private static LoggedUser instance;
public static LoggedUser getInstance() {
if (instance == null) {
instance = new LoggedUser();
}
return instance;
}
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
setChanged();
notifyObservers();
}
}
I have a instance of a custom JLabel and i want to changes its text in all frames,
A Swing component can only have a single parent. So you actually have two instances of your custom label. So updating the text in one label does not affect the other.
What you can do is create a PlainDocument to contain the text to be shared by multiple JTextFields. Then when the text is the Document is changed all the text fields will be updated.
So in the App class you would have:
private PlainDocument sharedDocument = new PlainDocument();
and you would create a method to access the Document. Maybe something like getSharedDocument().
Then in the form classes you would do something like:
//add(App.getApp().getMyCustomLabel());
JTextField textField = new JTextField( App.getApp().getSharedDocument() );
// customize text field to look like a label
textField.setBorder( null );
textField.setEditable( false );
add( textField );
I learned this code from some tutorial but it only counts left mouse clicks. I try with MouseListener but it kept counting while the timer came to 0. And with ActionListener it isn't counting the right mouse clicks. Any suggestions? Maybe its a foolish question but I'm new here.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class game extends JFrame
{
private static final int SwingConstants=0;
Timer timer;
int timercounter;
int clickcounter;
JLabel directions,entertime,clicklabel,timeleft,label;
JButton startbutton,clickbutton;
JTextField tf;
JMenuBar menubar;
JMenu file,help;
JMenuItem reset,exit,mhelp;
JFrame frame=new JFrame();
public game()
{
Container pane=this.getContentPane();
pane.setLayout(new GridLayout(3,1,2,2));
menubar=new JMenuBar();
setJMenuBar(menubar);
file=new JMenu("File");
menubar.add(file);
help=new JMenu("Help");
menubar.add(help);
reset=new JMenuItem("Reset");
file.add(reset);
exit=new JMenuItem("Quit");
file.add(exit);
mhelp=new JMenuItem("More Help!!");
help.add(mhelp);
ResetClass rc=new ResetClass();
reset.addActionListener(rc);
ExitClass ec=new ExitClass();
exit.addActionListener(ec);
MhelpClass mc=new MhelpClass();
mhelp.addActionListener(mc);
JPanel top=new JPanel();
top.setLayout(new GridLayout(1,1));
directions=new JLabel("Enter time & press <Click Here> REPEATEDLY!!");
top.add(directions);
pane.add(top);
JPanel middle=new JPanel();
middle.setLayout(new GridLayout(1,3));
entertime=new JLabel("Enter Time (sec):");
middle.add(entertime);
tf=new JTextField();
middle.add(tf);
startbutton=new JButton("Click Here");
middle.add(startbutton);
pane.add(middle);
JPanel bottom=new JPanel();
bottom.setLayout(new GridLayout(1,3));
clickbutton=new JButton("Click Here!");
clickbutton.setEnabled(false);
bottom.add(clickbutton);
clicklabel=new JLabel("Clicks: 0");
bottom.add(clicklabel);
timeleft=new JLabel("Time left: ?");
bottom.add(timeleft);
pane.add(bottom);
StartButtonClass sbc=new StartButtonClass();
startbutton.addActionListener(sbc);
ClickButtonClass cbc=new ClickButtonClass();
clickbutton.addActionListener(cbc);
}
public class StartButtonClass implements ActionListener
{
#Override
public void actionPerformed(ActionEvent sbc)
{
try
{
int timeCount=(int)(Double.parseDouble(tf.getText()));
if(timeCount<=0)
{
tf.setText("Positive number!");
//startbutton.setEnabled(false);
}
else
{
timeleft.setText("Time left: "+timeCount);
TimeClass tc=new TimeClass(timeCount);
timer=new Timer(1000,tc);
timer.start();
startbutton.setEnabled(false);
clickbutton.setEnabled(true);
}
}
catch(NumberFormatException ex)
{
tf.setText("Number only!");
}
}
}
public class ClickButtonClass implements MouseListener
{
public void mouseReleased(MouseEvent cbc)
{
clickcounter++;
clicklabel.setText("Clicks: "+clickcounter);
}
#Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e)
{
// TODO Auto-generated method stub
}
}
public class TimeClass implements ActionListener
{
int timerCounter;
public TimeClass(int timerCounter)
{
this.timerCounter=timerCounter;
}
public void actionPerformed(ActionEvent tc)
{
timerCounter--;
if(timerCounter>=1)
{
timeleft.setText("Time left: "+timerCounter);
}
else
{
timer.stop();
timeleft.setText("Done!");
clickbutton.setEnabled(false);
Toolkit.getDefaultToolkit().beep();
}
}
}
public class ResetClass implements ActionListener
{
public void actionPerformed(ActionEvent rc)
{
clickbutton.setEnabled(false);
startbutton.setEnabled(true);
clickcounter=0;
clicklabel.setText("Clicks: 0");
tf.setText("");
timeleft.setText("Time left: ?");
}
}
public class ExitClass implements ActionListener
{
public void actionPerformed(ActionEvent ec)
{
System.exit(0);
}
}
public class MhelpClass implements ActionListener
{
public void actionPerformed(ActionEvent mc)
{
JOptionPane.showMessageDialog(null, "Read the Readme file carefully!!", "Help!!", JOptionPane.PLAIN_MESSAGE);
}
}
}
Use this it will let you see right mouse clicks
class MyMouseListener implements MouseListener{
#Override
public void mouseReleased(MouseEvent arg0) {
if(SwingUtilities.isRightMouseButton(arg0)&&clickButton.isEnabled()){
//my code
}
}
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();
}
});