ActionListener Anonymous class between two JPanel - java

I'm trying to get to panels to work with each other RECURSIVELY.
When I'm on the main GUI I have the first JPanel with a Button Add Client,
Once clicked it brings me to the JPanel with a Form and then I recuperate those values,
and send them away in a JTable in the first JPanel the Main GUI.
When I then try to insert a second record. I get a blank GUI. I'm not too sure what I am doing wrong. How can I implement multiple time the same action to repeat ? Which is Load up the form, enter the information, push it on the Table, and the process repeats as much as I need it.
This is the Add Client button declaration in the MAIN GUI
Button btn_AddClient = new Button("Add Client");
btn_AddClient.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(false);
contentPane.setVisible(false);
setContentPane(contentPaneClient);
}
});
btn_AddClient.setBounds(259, 12, 70, 22);
contentPane.add(btn_AddClient);
This is the Add Button of the Form in the second Panel
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setContentPane(contentPaneClient);
panel.setVisible(true);
contentPane.setVisible(true);
contentPaneClient.setVisible(false);
LigneJTab l = new LigneJTab(textFieldPrenomClient.getText(),textFieldNomClient.getText(), textFieldAdresseClient.getText(), chckbxHomme.isSelected(), Sport.FOOTBALL);
myModel.addLine(l);
setContentPane(contentPane);
}
});
btnAdd.setBounds(263, 40, 117, 29);
contentPaneClient.add(btnAdd);

JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//setContentPane(contentPaneClient);
//panel.setVisible(true);
//contentPane.setVisible(true);
//contentPaneClient.setVisible(false);
LigneJTab l = new LigneJTab(textFieldPrenomClient.getText(),textFieldNomClient.getText(), textFieldAdresseClient.getText(), chckbxHomme.isSelected(), Sport.FOOTBALL);
myModel.addLine(l);
panel.setVisible(true);
contentPane.setVisible(true);
setContentPane(contentPane);
}
});
btnAdd.setBounds(263, 40, 117, 29);
contentPaneClient.add(btnAdd);
Commented the top part and added the setContentPane(contentPane); and that worked !
Thanks !

Another idea: You don't need to swap out the content panes to ask for data. A much more elegant way is using a modal dialog box. To make one, first create a dialog class:
public class MyDialog extends JDialog {
public MyDialog(Frame parent) {
super(parent);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
// add components to getContentPane()
// to close dialog, use setVisible(false) in listeners
}
public OutputData getData() {
OutputData data = new OutputData();
show();
// show only returns after a setVisible(false)
data.field = textField.getText();
// for example, repeat as many times as necessary
return data;
}
}
To invoke this dialog from the JFrame, use the following code:
MyDialog dialog = new MyDialog(this);
OutputData data = dialog.getData()
// now retrieve fields from data

Related

Have a Button Group in Java where all buttons can be deselected?

I want to have a Button Group in which either only one option is selected or none of them are. At the moment, I can get it to have no options ticked by default, and then if one of them is ticked only one of them can be ticked, but I also want to be able to untick the button that was selected. Is this possible?
EDIT: Ideally without having a clear all button, as it would ruin the symmetry of my GUI. Also, here is my code thus far:
ButtonGroup option = new ButtonGroup();
for(int i = 0; i < n; i++) {
JCheckBox check = new JCheckBox("", false);
option.add(check);
row3b.add(check);
}
Just use the clearSelection() method of ButtonGroup :
ButtonGroup.clearSelection()
Clears the selection such that none of the buttons in the ButtonGroup
are selected.
This snippet demonstrates how you can clear selections using ButtonGroup.clearSelection():
//The buttons
JFrame frame = new JFrame("Button test");
JPanel panel = new JPanel();
JRadioButton btn1 = new JRadioButton("Button1");
JRadioButton btn2 = new JRadioButton("Button2");
JButton clearbutton = new JButton("Clear");
panel.add(btn1);
panel.add(btn2);
panel.add(clearbutton);
frame.add(panel);
frame.setVisible(true);
frame.pack();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup btngroup = new ButtonGroup();
btngroup.add(btn1);
btngroup.add(btn2);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
clearbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Clear all selections
btngroup.clearSelection();
}
});
As you can see, this creates two JRadioButtons and adds them to group then makes a button that clears selections. Really simple. Or you could create your own radio button class that allows for the unchecking of the button, which is also doable relatively easily.

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

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

How to update JTextfield after click SAVE button

I have a main frame : JFrame>contentFrame>ScrollPane>BigPanel>panel_1T
private JPanel contentPane;
private JPanel BigPanel;
private JPanel panel_1T;
In panel_1T, I have put a FOOD button WITH its actionListener:
JButton button_19 = new JButton("FOOD");
button_19.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
});
panel_1T.setLayout(new GridLayout(0, 2, 0, 0));
panel_1T.add(button_19);
When user click FOOD button, new JFrame in newFoodUI class will be shown.:
JFrame>contentPane>panel>tabbedPane>panel_3>panel_5
In panel_5, I put a JTextField:
public static JTextField textField_3;
textField_3 = new JTextField();
panel_5.add(textField_3, "9, 4, fill, default");
textField_3.setColumns(10);
User will write some text into textField_3. Then user click SAVE button in panel_3, it will perform this:
JButton button_4 = new JButton("SAVE");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setContentPane(contentPane);
panel_3.revalidate();
panel_3.repaint();
panel_3.updateUI();
panel_5.revalidate();
panel_5.repaint();
panel_5.updateUI();
contentPane.revalidate();
contentPane.repaint();
JOptionPane.showMessageDialog(null, "Saved !");
}
});
button_4.setBounds(873, 396, 75, 33);
contentPane.add(button_4);
}
The result is, when I click SAVE button and close the Frame in newFoodUI, I will reopen back by click the FOOD button to check whether the text I wrote has been saved or not. But its not saving the text I wrote.
You have to save the value from the textfeld textField_3.getText() and set this value manually to textfeld when showing textField_3.setText(value). So you have to keep your value in your project or store persistent somewhere.
There are a couple of things to fix here and I will not give you complete code but I will point out some errors. First let's consider your button_19 listener
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
When this is performed, it creates a totally new object of newFoodUI and gives it no parameters. So how could this frame know about anything that happened before its creation if you give it nothing? Additionally, you explicitly say DISPOSE_ON_CLOSE, when you could use HIDE_ON_CLOSE if you wish to reuse it.
Then in your JButton button_4 = new JButton("SAVE"); listener you want to save the data in the text field, but your implementation does nothing to the text field. You should, for example, get the text from textField_3 and write it to a file or send back to the first JFrame.
Then there is the issue of using multiple JFrames in the first place.

How to make a JButton do something

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

Java- How to add more textfields by clicking a button?

I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.
How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?
Thank you !
It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameExample
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public JFrameExample()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add JTextField");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate(); // For JDK 1.7 or above.
//frame.getContentPane().revalidate(); // For JDK 1.6 or below.
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new JFrameExample().displayGUI();
}
});
}
}
Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:
// handle the button action event
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create the new text field
JTextField newTextField = new JTextField();
// add it to the container
panel.add(newTextField);
panel.validate();
panel.repaint();
}
});
When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).

Categories

Resources