I am trying to make a sort of phonebook and my skills in Java's GUI are rusty as I haven't made one in years. So let's assume for now that I have a single button on my window. When I click it I want it to pop up with a dialog window with three sections to input text (First Name, Last Name, and Phone number) and then when the user clicks the ok button at the bottom it will add these to a list of names and phonenumbers. What code will I need to make the button perform this action? I already know how to make the button so I'm mainly wondering about the action it performs and how to make the dialog window I need.
and how to make the dialog window I need.
You make a JDialog window the same way you make a JFrame window, somethink like:
JPanel panel = new JPanel();
panel.add( someComponent );
panel.add( anotherComponent );
JDialog dialgo = new JDialog();
dialog.add(panel);
dialog.pack();
dialog.setVisible( true );
Normally this code would be contains in a separate class and you just create an instance of the class in your ActionListener.
Ok so example your button is called button1. You will have to add an ActionListner to that button and an ActionPerformed (Which will encapasulate what happens when the button is clicked.) When the button is clicked you can create a new panel adding textboxs' in the panel.You can then add another button to proceed, which will have its ActionListner/ActionPerfromed duet storing the string inputed into the textbox into a defined String. Sample code below:
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
JPanel panel1 = new JPanel();
JTextField textbox = new JTextField(50);
JTextField textbox1 = new JTextField(50);
JTextField textbox3 = new JTextField(50);
label.setText("Please enter Something below on the textbox: ");
panel1.add(label);
panel1.add(textbox);
panel1.add(textbox1);
panel1.add(textbox2);
JButton button3 = new JButton();
button3.setText("CLICK TO PROCEED");
panel1.add(button3, BorderLayout.NORTH);
frame.setContentPane(panel1);
frame.invalidate();
frame.validate();
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String s1 = textbox.getText();
String s2 = textbox1.getText();
String s3 = textbox2.getText();}}
Hope this helps. However, Please note that the variables defined under the actionPerformed are local. s1,s2,s3 cannot be used outside. Better to create private static variables outside the ActionListner/ActionPerformed method.
Related
Currently I am calling a method (showFrames) which pops up a JFrame which contains many editable text fields. I am storing the value of these text fields in a list (editedFields) which I need to use in the calling method. My issue is that my calling method is not waiting for the user to select ok/cancel before continuing so the list is not populated when I am trying to take action on it. I tried to overcome this by using a modal dialog to no avail. the method is being called here...
...
showFrames(longToShortNameMap);
if (editedFields != null) {
for (JTextField field : editedFields) {
System.out.println(field.getText());
}
}
...
and the showFrames method is implemented as:
private static void showFrames(Map<String, String> longToShortNameMap) {
final ToolDialog frame = new ToolDialog("Data Changed");
frame.setVisible(true);
frame.setModal(true);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(400, 500);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(0, 2));
JPanel buttonPanel = new JPanel(new GridLayout(2, 0));
List<String> keys = new ArrayList(longToShortNameMap.keySet());
final List<JTextField> textFields = new ArrayList<>();
for (String key : keys) {
JLabel label = new JLabel(key);
JTextField textField = new JTextField(longToShortNameMap.get(key));
panel.add(label);
panel.add(textField);
textFields.add(textField);
}
JButton okButton = new JButton("OK"); //added for ok button
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
editedFields = textFields;
frame.setVisible(false);
frame.dispose();
}
});
JButton cancelButton = new JButton("Cancel");//added for cancel button
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
frame.dispose();
}
});
okButton.setVisible(true);//added for ok button
cancelButton.setVisible(true);//added for cancel button
buttonPanel.add(okButton);//added for ok button
buttonPanel.add(cancelButton);//added for cancel button
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setVisible(true);
scrollPane.setSize(500, 500);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
}
the current behavior I observe is that when the JFrame pops up, all the fields will immediately print out instead of waiting for the user to click "OK". Effectively this means I am receiving the default values in the text fields instead of the edited values.
Note: ToolDialog extends JDialog
The basic problem that you have is that you are instantiating the Dialog first, making it visible, and then adding fields to it.
That is essentially incorrect. All objects should be added to it while you are instantiating the Frame/Dialog, preferably in the constructor call. Then, you make it visible when everything is ready.
Of course, you can add a new field to the frame after showing it already, but that is typically done based on some event, for example, when user clicks "Add a new number", then you add new text fields, etc to it.
So, the fix for you is simple, move the logic that adds the buttons, the lists, the panels etc, to the constructor, and then make that window visible.
You have 2 different issues here :
Waiting for a dialog.
Displaying the dialog correctly.
1.- Waiting for a dialog.
You should use a JDialog instead of a JFrame to make the window modal.
The window is not modal because you are showing it before setting it to modal. See JDialog.setModal :
Note: changing modality of the visible dialog may have no effect until
it is hidden and then shown again.
You need to switch theese two lines :
frame.setVisible(true);
frame.setModal(true);
An alternate way is to synchronize with a countdown latch:
CountDownLatch latch = new CountDownLatch(1);
.......
showFrames(longToShortNameMap);
latch.await(); // suspends thread util dialog calls latch.countDown
if (editedFields != null) {
.......
/// Dialog code
latch.countDown(); // place it everywhere you are done with the dialog.
dispose();
2.- Displaying the dialog correctly.
Place frame.setVisible(true) as the last line of showFrames.
I have a JTabbedPane with 5 tabs in it. I also got 3 other buttons in same JFrame where my JTabbedPane is added. I want to make the user able move to particular tab when a particular button is clicked. Here is the image example
Now for example if user clicks Button 1 then tab One should be opened and similarly when button 2 is clicked then tab Two should be opened and so for third one.
Here is my code to add these JTabbedPane and buttons.
public class TabsAndButtons
{
public TabsAndButtons()
{
JTabbedPane tabsPane = new JTabbedPane();
tabsPane.add("One", new JPanel());
tabsPane.add("Two", new JPanel());
tabsPane.add("Three", new JPanel());
tabsPane.add("Four", new JPanel());
tabsPane.add("Five", new JPanel());
JPanel Panel = new JPanel();
Panel.add(tabsPane);
JButton Button1 = new JButton("Button 1");
Panel.add(Button1);
JButton Button2 = new JButton("Button 2");
Panel.add(Button2);
JButton Button3 = new JButton("Button 3");
Panel.add(Button3);
JFrame MainFrame = new JFrame("JTabbedPane and Buttons");
MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainFrame.getContentPane().add(Panel );
MainFrame.pack();
MainFrame.setVisible(true);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(() -> {
new TabsAndButtons();
});
}
}
The actual purpose of such action is very lengthy and has a lot details which will make the question dull so I am asking the main task where I stucked. Thanks for your kind support and time.
Use the method button.addActionListener() to execute code when a button is clicked. The code that you want to execute is probablytabsPane. setSelectedIndex(i)wherei` is the index of the tab that you want to show.
You might also want to move the JTabbedPane tabsPane into a member variable, or mark it with final, to make sure that it can be accessed from within the action listener.
Add an ActionListener to each of the buttons. Then in the ActionListener you can invoke the setSelected(...) method of the tabbed pane.
Read the section from the Swing tutorial on How to Write an ActionListener for more information and examples.
Also, variable name should NOT start with an upper case character.
Try in the EventListener for the Buttons the Method setSelectedIndex(int index) on your JTabbedPane.
The Referenz: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTabbedPane.html#setSelectedIndex%28int%29
Im trying to get it so that when i click on a menu option, the windows changes from the 'welcome text' to 4 buttons which the user can then click on. However, when i click on the simulation button, nothing happens.. the window doesnt change at all.. Ive summarized my code to the basic stuff by the way. anyone see anything i cant?
JFrame GUI = new JFrame("Graphical User Interface");
public gui()
{
JMenuBar menubar = new JMenuBar();
JMenu Simulation = new JMenu("Simulation");
theLabel = new JLabel("Welcome to the Main Menu. ",JLabel.CENTER);
GUI.add(theLabel);
menubar.add(Simulation);
Simulation.add(Simulationmenu);
Simulationmenu.addActionListener(this);
GUI.setJMenuBar(menubar);
GUI.setLocation(500,250);
GUI.setSize(300, 200);
GUI.setVisible(true);
}
public void actionPerformed(ActionEvent E){
if(E.getSource() == Simulationmenu){
// Buttons in the menu i want to output once clicked on 'simulation'
thePanel = new JPanel(new GridLayout(4,0));
Run = new JButton("Run");
Pause = new JButton("Pause");
Reset = new JButton("Reset");
DisplayMaps = new JButton("Display Maps?");
// Add the components to the panel:
thePanel.add("West", Run);
thePanel.add("Center", Pause);
thePanel.add("East", Reset);
thePanel.add("West", DisplayMaps);
// Add the panel to the contentPane of the frame:
GUI.add(thePanel);
// add this object as listener to the two buttons:
Run.addActionListener(this);
Seems your problem in next, you add a new panel(thePanel) to your JFrame(GUI) when it is showing, but in this case you must to call revalidate() method of JFrame(GUI).
Add GUI.revalidate() after GUI.add(thePanel);, it helps you.
In my program I have several JComboBoxes which display different attributes of a bike. I currently have it set up so that the user can click a button called saveBike and save the attributes to a RandomAccessFile. I made my own listener for this button and added it to the JButton. All my listener does is open a JFileChooser and allow the user to save the file with the name of their choice. What I want my program to do is after the user saves the attributes with the given name, I want saveBike to be disabled so the user cannot keep clicking it. However, I want saveBike to be enabled again if the user changes one of the attributes by selecting something different in the ComboBox. I thought I could put this code in the listener, but I don't know how to see if an item was selected in the comboboxes or not. My question is, is there a way to see whether a NEW item in a combo box was selected or not.
This example explain how you can use an ItemListener to check when an item is selected, and enable a button if it is.
public static void main(String[] args)
{
//elements to be shown in the combo box
String course[] = {"", "A", "B", "C"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
JComboBox combo = new JComboBox(course);
final JButton button = new JButton("Save");
panel.add(combo);
panel.add(button);
//disables the button at the start
button.setEnabled(false);
frame.add(panel);
combo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
//enables the button when an item is selected
button.setEnabled(true);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
how can i add components dynamically in a jpanel?
I am having add button when i click the button the components should be added to the JPanel.
my question is that adding a textfield and button to jpanel when i click on the add button the user can click on the add button any number of times according to that i have to add them to the jpanel. i have added to scrollerpane to my jpanel,and jpanel layout manager is set to null.
Just as you always do, except that you have to call:
panel.revalidate();
when you are done, since the container is already realized.
Use an ActionListener, you can use an anonymous class like this:
JPanel myJPanel = new JPanel();
...
b = new Button("Add Component");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel someLabel = new JLabel("Some new Label");
myJPanel.add(someLabel);
myJPanel.revalidate();
}
});