I use the following code to create hot keys for the java form using swing. If I press ALT+N,ALT+R,ALT+1,ALT+2 the cursor moves to correct text fields and I enter the value in corresponding Text Fields. It works properly. My problem is, I have Save and exit JButtons in this form if. I press CTRL+S means the Save button will be selected at the same time If i press CTRL+X means the exit button will be selected. How to create mnemonics for JButton? How to do CTRL+S,CTRL+X this using the following code?
Thanks in advance.
package hotkeys;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class hotkey extends JFrame {
public static void main(String arg[]) {
JLabel Name = new JLabel("Name");
JTextField tf1 = new JTextField(20);
Name.setLabelFor(tf1);
Name.setDisplayedMnemonic('N');
JLabel Regno = new JLabel("RegNO");
JTextField tf2 = new JTextField(20);
Regno.setLabelFor(tf2);
Regno.setDisplayedMnemonic('R');
JLabel Mark1 = new JLabel("Mark1");
JTextField tf3 = new JTextField(20);
Mark1.setLabelFor(tf3);
Mark1.setDisplayedMnemonic('1');
JLabel Mark2 = new JLabel("Mark2");
JTextField tf4 = new JTextField(20);
Mark2.setLabelFor(tf4);
Mark2.setDisplayedMnemonic('2');
JButton b1 = new JButton("Save");
JButton b2 = new JButton("eXit");
JFrame f = new JFrame();
JPanel p = new JPanel();
p.add(Name);
p.add(tf1);
p.add(Regno);
p.add(tf2);
p.add(Mark1);
p.add(tf3);
p.add(Mark2);
p.add(tf4);
p.add(b1);
p.add(b2);
f.add(p);
f.setVisible(true);
f.pack();
}
}
You need to register a keyBinding in the button's component inputmap. In code (repeating a subtle variant of what you have been told to do in your previous questions :-)
// create an Action doing what you want
Action action = new AbstractAction("doSomething") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("triggered the action");
}
};
// configure the Action with the accelerator (aka: short cut)
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
// create a button, configured with the Action
JButton toolBarButton = new JButton(action);
// manually register the accelerator in the button's component input map
toolBarButton.getActionMap().put("myAction", action);
toolBarButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
(KeyStroke) action.getValue(Action.ACCELERATOR_KEY), "myAction");
Sun has a really good Description of the whole Key Binding issue. You can find it here:
JavaSE Tutorial on Keybinding
//EDIT
Edited my example code so you can just copy + paste it and it will work. Included the points that were missing, thanks for the feedback.
KeyStroke keySave = KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK);
Action performSave = new AbstractAction("Save") {
public void actionPerformed(ActionEvent e) {
//do your save
System.out.println("save");
}
};
JButton b1 = new JButton(performSave);
b1.getActionMap().put("performSave", performSave);
b1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySave, "performSave");
KeyStroke keyExit = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK);
Action performExit = new AbstractAction("Exit") {
public void actionPerformed(ActionEvent e) {
//exit
System.out.println("exit");
}
};
JButton b2 = new JButton(performExit);
b2.getActionMap().put("performExit", performExit);
b2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyExit, "performExit");
Just modified your code. (inserted code in //**)
Just 1 comment... Ctrl-X is shortcut for edit command "Cut" (along with Ctrl-C & Ctrl-V). You have editable fields in frame. I used Ctrl-Q (quit) instead.
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.plaf.ActionMapUIResource;
import java.net.*;
public class HotKeys extends JFrame {
public static void main(String arg[]) {
JLabel Name = new JLabel("Name");
JTextField tf1 = new JTextField(20);
Name.setLabelFor(tf1);
Name.setDisplayedMnemonic('N');
JLabel Regno = new JLabel("RegNO");
JTextField tf2 = new JTextField(20);
Regno.setLabelFor(tf2);
Regno.setDisplayedMnemonic('R');
JLabel Mark1 = new JLabel("Mark1");
JTextField tf3 = new JTextField(20);
Mark1.setLabelFor(tf3);
Mark1.setDisplayedMnemonic('1');
JLabel Mark2 = new JLabel("Mark2");
JTextField tf4 = new JTextField(20);
Mark2.setLabelFor(tf4);
Mark2.setDisplayedMnemonic('2');
JButton b1 = new JButton("Save");
JButton b2 = new JButton("eXit");
JFrame f = new JFrame();
JPanel p = new JPanel();
p.add(Name);
p.add(tf1);
p.add(Regno);
p.add(tf2);
p.add(Mark1);
p.add(tf3);
p.add(Mark2);
p.add(tf4);
p.add(b1);
p.add(b2);
// *****************************************************
ActionMap actionMap = new ActionMapUIResource();
actionMap.put("action_save", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save action performed.");
}
});
actionMap.put("action_exit", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Exit action performed.");
}
});
InputMap keyMap = new ComponentInputMap(p);
keyMap.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
java.awt.Event.CTRL_MASK), "action_save");
keyMap.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q,
java.awt.Event.CTRL_MASK), "action_exit");
SwingUtilities.replaceUIActionMap(p, actionMap);
SwingUtilities.replaceUIInputMap(p, JComponent.WHEN_IN_FOCUSED_WINDOW,
keyMap);
// *****************************************************
f.add(p);
f.setVisible(true);
f.pack();
}
}
I provide this as much for me as a learning experience as for anyone else. I've always had difficulty applying code snippets for key binding that I've found in the past and I hope my explanation and code will be clear. Thanks to #kleopatra for her code snippet, on which I base my code below.
(I'm using CAPITAL LETTERS where I should NOT in order to more clearly show what MUST MATCH.)
The code links the Ctrl-Shift-U keystroke to the code in actionPerformed for MYACTION via the matching strings in getInputMap and getActionMap.
The three instances of MYACTION below must match, as must the four instances of MYACTIONBUTTON, as must the two instances of the string MAKE_THESE_MATCH. Call them what you will; just make them match.
The button MYACTIONBUTTON must have MYACTION as the argument to the JButton defining it AND must have getInputMap and getActionMap applied to it.
private static JButton MYACTIONBUTTON;
private static JFrame frame;
private static JPanel panel;
...
Action MYACTION = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// put action code here
}
};
MYACTIONBUTTON = new JButton(MYACTION);
MYACTIONBUTTON.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(getKeyStroke(VK_U, CTRL_DOWN_MASK | SHIFT_DOWN_MASK),
"MAKE_THESE_MATCH");
MYACTIONBUTTON.getActionMap().put("MAKE_THESE_MATCH", MYACTION);
panel.add(MYACTIONBUTTON);
frame.add(panel);
Related
I am trying to figure out how to properly use listeners in this example. What I want it to do is display a pop-up after clicking the submit button showing what boxes are checked, but right now I get a popup after each box is clicked. I have tried implementing an action listener for the radio buttons and an item listener for the check boxes, but I'm not sure if this is the right thing to do. What am I missing?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CarSelector extends JFrame implements ActionListener, ItemListener{
JButton submit = new JButton("Submit");
JLabel label1 = new JLabel("Select Vehicle type and options");
JLabel carLabel = new JLabel("Vehicle Type");
JLabel options = new JLabel("Options");
ButtonGroup group = new ButtonGroup();
JRadioButton carRadio = new JRadioButton("Car", true);
JRadioButton vanRadio = new JRadioButton("Minivan");
JRadioButton truckRadio = new JRadioButton("Pickup Truck");
JRadioButton suvRadio = new JRadioButton("SUV");
JCheckBox leather = new JCheckBox("Leather Seats");
JCheckBox ac = new JCheckBox("Air Conditioning");
JCheckBox sat = new JCheckBox("Sattelite Radio");
JCheckBox warmer = new JCheckBox("Seat Warmers");
String optionsSelected;
String carSelected;
ActionListener listen = new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(
CarSelector.this, sb.toString + ssb.toString());
}
};
CarSelector(){
super("Vehicle Selector");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
CarGUI();
}
public void CarGUI(){
JPanel vehicleTypes = new JPanel();
JPanel carOptions = new JPanel();
JPanel submitButton = new JPanel();
carRadio.addActionListener(listen);
vanRadio.addActionListener(listen);
truckRadio.addActionListener(listen);
suvRadio.addActionListener(listen);
leather.addActionListener(listen);
ac.addActionListener(listen);
sat.addActionListener(listen);
warmer.addActionListener(listen);
submit.addActionListener(listen);
add(submitButton);
submitButton.setLayout(new BoxLayout(submitButton, BoxLayout.X_AXIS));
submitButton.setBounds(100, 150, 100, 100);
add(vehicleTypes);
vehicleTypes.setLayout(new BoxLayout(vehicleTypes, BoxLayout.Y_AXIS));
vehicleTypes.setBounds(150,0,125,125);
add(carOptions);
carOptions.setLayout(new BoxLayout(carOptions, BoxLayout.Y_AXIS));
vehicleTypes.add(carLabel);
vehicleTypes.add(carRadio);
vehicleTypes.add(vanRadio);
vehicleTypes.add(truckRadio);
vehicleTypes.add(suvRadio);
group.add(carRadio);
group.add(vanRadio);
group.add(truckRadio);
group.add(suvRadio);
carOptions.add(options);
carOptions.add(leather);
carOptions.add(ac);
carOptions.add(sat);
carOptions.add(warmer);
submitButton.add(submit);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void itemStateChanged(ItemEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
This is the code for running the program.
public class GUITest {
public static void main (String[] args){
CarSelector car = new CarSelector();
}
}
To further my comment above, for your use case, you should only be adding an ActionListener to your submit button.
Within the ActionListener you will need to call isSelected on each of your JRadioButtons and JCheckBoxes.
Something like this will do the trick:
public void CarGUI(){
JPanel vehicleTypes = new JPanel();
JPanel carOptions = new JPanel();
JPanel submitButton = new JPanel();
//The below syntax assumes you are running Java 8. Please let me know if you are not
//and I will update the syntax
submit.addActionListener((e)=>{
StringBuilder sb = new StringBuilder();
sb.append("Vehicle Type: ");
if(carRadio.isSelected()) sb.append("Car");
else if(vanRadio.isSelected()) sb.append("Van");
//Continue with the rest of radiobuttons
// and do the same with the Checkboxes just make sure to
// not use "else" if and make a new conditional for each Checkbox
JOptionPane.showMessageDialog(
CarSelector.this, sb.toString);
});
A cleaner and more sustainable way to handle this sort of thing would be to put your JRadioButtons and JCheckBoxes in Arrays. It would make your ActionListener code a lot cleaner and it would be easier to add more options because your would just need to insert a new checkbox or radiobutton into your arrays and not have to change any of your ActionListener code.
JRadioButton[] vehicleTypes = new JRadioButton[] { new JRadioButton("Car", true), new JRadioButton("Van") ... };
// then in ActionListener
for(JRadioButton rBtn: vehicleTypes){
if(rBtn.isSelected()){
sb.append(rBtn.getText());
}
}
I am new to java and creating a Simple gui App. In this simple app, I am trying to write a e-commerce letter for Firms. So, I planned my app something like this..
First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).
The problem is I don't have any idea to get Radiobutton command when i trigger jButton. Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value..
Here is my java Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class englet{
static public JFrame f;
static public JPanel p;
static class getTypeOfLetter implements ActionListener{
public void actionPerformed( ActionEvent e){
String btnInput = e.getActionCommand();
System.out.println(btnInput);
}
}
public static void askletter(){
JRadioButton btnRadio1;
JRadioButton btnRadio2;
ButtonGroup btngrp;
JButton btnGo = new JButton("Write");
btnRadio1 = new JRadioButton("Write Letter For American Firm");
btnRadio1.setActionCommand("Amer");
btnRadio2 = new JRadioButton("Write Letter For British Firm");
btnRadio2.setActionCommand("Brit");
btngrp = new ButtonGroup();
btnGo.setActionCommand("WriteTest");
btnGo.addActionListener(new getTypeOfLetter());
btngrp.add(btnRadio1);
btngrp.add(btnRadio2);
p.add(btnRadio1);
p.add(btnRadio2);
p.add(btnGo);
}
englet(){
f = new JFrame("English Letter");
p = new JPanel();
askletter();
f.add(p);
f.setSize(400,200);
f.setVisible(true);
}
public static void main (String[] argv ){
englet i = new englet();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I am using Notepad++ and CMD.. Not any another tools like netbeans initllli ecplisse.
**RE-EDIT ** I want a possible solution and can satisfy me.. this app works but i am not able to get radiobuttons commmand with jubtton..
You've got several issues:
Over-use of static. Most of the fields and methods of your code should be non-static
You're missing key fields that will be necessary to transmit the information needed. To get the selected JRadioButton, you need to make JRadioButton fields and check which is selected, or (and my preference), you need to make the ButtonGroup variable a field and check which JRadioButton has been selected based on the ButtonModel returned by the ButtonGroup.
You're currently using local variables and these won't be visible throughout the class, which is why either the JRadioButtons or the ButtonModel most be fields (declared in the class).
If you go with ButtonModel above, you must give each JRadioButton an appropriate actionCommand String.
For example:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GetRadio extends JPanel {
private static final String[] FIRMS = {"American Firm", "British Firm"};
// You need this field to access it in your listener
private ButtonGroup buttonGroup = new ButtonGroup();
public GetRadio() {
// create JButton and add ActionListener
JButton button = new JButton("Select");
button.addActionListener(new ButtonListener());
// JPanel with a grid layout with one column and variable number of rows
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
for (String firm : FIRMS) {
// create radiobutton and set actionCommand
JRadioButton radioButton = new JRadioButton(firm);
radioButton.setActionCommand(firm);
// add to button group and JPanel
buttonGroup.add(radioButton);;
radioButtonPanel.add(radioButton);
}
// add stuff to main JPanel
add(radioButtonPanel);
add(button);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get button model of selected radio button from ButtonGroup
ButtonModel model = buttonGroup.getSelection();
// if null, no country selected
if (model == null) {
Component component = GetRadio.this;
String message = "You must first select a country!";
String title = "Error: No Country Selected";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(component, message, title, type);
} else {
// valid country selected
String country = model.getActionCommand();
System.out.println("Letter to " + country);
}
}
}
private static void createAndShowGui() {
GetRadio mainPanel = new GetRadio();
JFrame frame = new JFrame("Get Radio Btn");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I'm looking to recall a JButton's value when clicked i.e. when the user clicks a JButton, the value of that JButton (which is a single letter) will be written to a JLabel. The user will click multiple buttons and as such, multiple values will need to be stored and printed. Finally the user will click a button and the JLabel holding all recieved JButton values will be stored (Obviously using an array).
Here is what my JButton's look like in code:
theModel.randomLetters();
for(int i=0;i<16;i++){
JButton dice = new JButton(theModel.letters.get(i));
dice.addActionListener(disableButtonListener);
boggleGrid.add(dice);
}
theModel.randomLetters(); is a reference to another class with "letters" being an array holding 16 values. Will I need to add each JButton individually to the boggleGrid so their individual names can be recalled to achieve the goal stated above, or do they have individual names and I don't know it? (I've used a for loop someone gave me so I'm not sure if there are individual names for each JButton)
Thanks, and sorry if this is elementary
Read the following code, you'll get some ideas...
I used a StringBuilder to store the values of the Button's each time they were clicked by using StringBuilder.append(JButton.getText().toString()). That was done in the actionPerformed methods of the JButtons.
Then finally in the Done buttons actionPerformed method I had stored the text the string builder held in an array.
P.S. I know you're using 16 JButton's I just used 3 for simplicity...
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.ArrayList;
public class GUI extends JFrame{
ArrayList<String> numbers = new ArrayList<>();
StringBuilder sb = new StringBuilder();
JButton button1;
JButton button2;
JButton button3;
JButton doneButton;
JPanel row1 = new JPanel();
JPanel textLabelRow = new JPanel();
JLabel label = new JLabel();
JPanel row3 = new JPanel();
public void create(){
setTitle("S-O");
setSize(500,200);
setLayout(new GridLayout(3,1,10,10));
button1 = new JButton("1");
button2 = new JButton("2");
button3 = new JButton("3");
doneButton = new JButton("Done");
row1.add(button1);
row1.add(button2);
row1.add(button3);
button1.addActionListener(new Button1Listener());
button2.addActionListener(new Button2Listener());
button3.addActionListener(new Button3Listener());
doneButton.addActionListener(new doneButtonListener());
textLabelRow.add(label);
row3.add(doneButton);
add(row1);
add(textLabelRow);
add(row3);
setVisible(true);
}
private class Button1Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
sb.append(button1.getText().toString());
}
}
private class Button2Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
sb.append(button2.getText().toString());
}
}
private class Button3Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
sb.append(button3.getText().toString());
}
}
private class doneButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
label.setText(sb.toString());
numbers.add(sb.toString());
sb = new StringBuilder();
}
}
public static void main(String[] args){
GUI start = new GUI();
start.create();
}
}
EDIT:
You could just use one class which implements ActionListener opposed to having one for each JButton.
With in the actionPerformed method "public void actionPerformed(ActionEvent ev)"
You would have to ev.getActionCommand(), that would return the text value of the JButton which caused the event. Then you could append that to the StringBuilder.
So something along the lines of this:
private ArrayList listForEdit = new ArrayList<>();
StringBuilder sbEdit = new StringBuilder();
class actionHandler implements ActionListener{
public void actionPerformed(ActionEvent ev){
if(ev.getActionCommand.equals("Done"))
listForEdit.add(sbEdit);
sbEdit = new StringBuilder();
}
else{
sbEdit.append(ev.getActionCommand());
}
}
A typical way to use JFileChooser includes checking whether user clicked OK, like in this code:
private void addModelButtonMouseClicked(java.awt.event.MouseEvent evt) {
JFileChooser modelChooser = new JFileChooser();
if(modelChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ){
File selectedFile = modelChooser.getSelectedFile();
if(verifyModelFile(selectedFile)){
MetModel newModel;
newModel = parser.parse(selectedFile, editedCollection.getDirectory() );
this.editedCollection.addModel(newModel);
this.modelListUpdate();
}
}
}
I tried to mimic this behavior in my own window inheriting JFrame. I thought that this way of handling forms is more convenient than passing collection that is to be edited to the new form. But I have realized that if I want to have a method in my JFrame returning something like exit status of it I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window.
So, how does showOpenDialog() work? When I tried to inspect the implementation, I found only one line methods with note "Compiled code".
I tried to mimic this behavior in my own window inheriting JFrame.
JFrame is not a modal or 'blocking' component. Use a modal JDialog or JOptionPane instead.
E.G.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/** Typical output:
[JTree, colors, violet]
User cancelled
[JTree, food, bananas]
Press any key to continue . . .
*/
class ConfirmDialog extends JDialog {
public static final int OK_OPTION = 0;
public static final int CANCEL_OPTION = 1;
private int result = -1;
JPanel content;
public ConfirmDialog(Frame parent) {
super(parent,true);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
content = new JPanel(new BorderLayout());
gui.add(content, BorderLayout.CENTER);
JPanel buttons = new JPanel(new FlowLayout(4));
gui.add(buttons, BorderLayout.SOUTH);
JButton ok = new JButton("OK");
buttons.add(ok);
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = OK_OPTION;
setVisible(false);
}
});
JButton cancel = new JButton("Cancel");
buttons.add(cancel);
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = CANCEL_OPTION;
setVisible(false);
}
});
setContentPane(gui);
}
public int showConfirmDialog(JComponent child, String title) {
setTitle(title);
content.removeAll();
content.add(child, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getParent());
setVisible(true);
return result;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Test ConfirmDialog");
final ConfirmDialog dialog = new ConfirmDialog(f);
final JTree tree = new JTree();
tree.setVisibleRowCount(5);
final JScrollPane treeScroll = new JScrollPane(tree);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Choose Tree Item");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = dialog.showConfirmDialog(
treeScroll, "Choose an item");
if (result==ConfirmDialog.OK_OPTION) {
System.out.println(tree.getSelectionPath());
} else {
System.out.println("User cancelled");
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(b);
p.setBorder(new EmptyBorder(50,50,50,50));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
I guess you wait for the user to click some button by constantly checking what button is pressed.
"I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window."
May be you should use evens to get notified, when the user clicks on something, not waiting for them to press the button - maybe there is some OnWindowExit event?
Or maybe something like this:
MyPanel panel = new MyPanel(...);
int answer = JOptionPane.showConfirmDialog(
parentComponent, panel, title, JOptionPane.YES_NO_CANCEL,
JOptionPane.PLAIN_MESSAGE );
if (answer == JOptionPane.YES_OPTION)
{
// do stuff with the panel
}
Otherwise you might see how to handle window events, especially windowClosing(WindowEvent) here
i am trying to make an actionListener on a button in another button which has also an actionlistener and i just couldn't figure it out for some way. I am trying to make an action on the 2nd button but i couldn't figure it out.If anyone helps me i'd appreciate! here is the code below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class basic implements ActionListener{
public static void main(String[] args) {
basic process = new basic ();
}
public basic(){
JFrame fan = new JFrame("Scheme");
JPanel one = new JPanel(new BorderLayout());
fan.add(one);
JPanel uno = new JPanel();
uno.setLayout(new BoxLayout(uno, BoxLayout.Y_AXIS));
JButton addB = new JButton("first choice");
addB.setAlignmentX(Component.CENTER_ALIGNMENT);
uno.add(addB);
addDButton.setActionCommand("hehe");
addDButton.addActionListener(this);
one.add(uno,BorderLayout.CENTER);
fan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fan.setSize(500,700);
fan.setLocationByPlatform(true);
fan.setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
JPanel markP = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,20));
JDialog dialog = new JDialog((JFrame)null);
dialog.getContentPane().add(markP,BorderLayout.CENTER);
if (evt.getActionCommand().equals("hehe")) {
JLabel title = new JLabel("Proceed");
title.setFont(new Font("Arial",Font.BOLD,15));
markP.add(title,BorderLayout.NORTH);
JButton exit = new JButton("Exit");
markP.add(exit);
//here i want to create another actionListener on the exit button only without affecting the other content which is in the button "addB " so that when i click on the addB button the J dialog pops up, and than when i click on exit button the program will return to the menu.I couldn't figure it out.
dialog.toFront();
dialog.setModal(true);
dialog.pack(); //
dialog.setLocationRelativeTo(null); //
dialog.setVisible(true);
}
// here the code goes on but the problem is that of the actionListener which is concerned.
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// you code here
}
});
You should use better variables names. It is not easy to follow your code
You could use the same ActionListener if you check the source of the action using
if (evt.getSource().equals(addDButton) { original code }
else { code for the other button }