Checking whether the selected item in a combobox has been changed java - java

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);
}

Related

How to edit a JComboBox with text selected in JEditorPane

I have a UI with two components - a JEditorPane and a JComboBox. My goal is to be able to type something into the JEditorPane, select a portion of the text, and while it is still selected type and/or select a value in an editable JComboBox.
This is for a text editor type of program where I want to change the font size of just the selected text in the editor pane. Where the font size is coming from the editable combo box. To clarify, I'm not asking how to apply styles to the text, I'm asking how to select a value in the combo box without losing the focus/selection in the JEditorPane.
Here's the code for the UI, but I wasn't sure where to begin doing anything with the focus...
public static void main(String [] args)
{
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
JComboBox<String> combo = new JComboBox(new String [] {"Hello", "World"});
contentPane.add(combo);
JEditorPane editor = new JEditorPane();
contentPane.add(editor);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
I'm asking how to select a value in the combo box without losing the focus/selection in the JEditorPane.
You don't lose the selection of the text in the editor pane when you select an item from the combo box. The selection remains, but it is just not painted until the editor pane regains focus.
So the easiest way to do this is to use a JMenuItem. Read the section from the Swing tutorial on Text Component Features for an example that does this.
If you still want to use the combo box then you can add Integer values to the combo box then the code in your ActionListener for the combo box would look something like:
#Override
public void actionPerformed(ActionEvent e)
{
Integer value = (Integer)comboBox.getSelectedItem();
Action action = new StyledEditorKit.FontSizeAction("Font size", value);
action.actionPerformed(null);
}
The StyledEditorKit actions extend from TextAction. The TextAction knows the last text component that had focus and therefore the font change is applied to that text component.
If you really want the text field to show the selection then you need to create a custom Caret and override the focusLost method to NOT invoke setSelectionVisible(false) (which is the default behaviour.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class DefaultCaretTest extends JFrame
{
public DefaultCaretTest()
{
JTextField textField1 = new JTextField("Text Field1 ");
JTextField textField2 = new JTextField("Text Field2 ");
textField1.setCaret(new SelectionCaret());
textField2.setCaret(new SelectionCaret());
textField1.select(5, 11);
textField2.select(5, 11);
((DefaultCaret)textField2.getCaret()).setSelectionVisible(true);
add(textField1, BorderLayout.WEST);
add(textField2, BorderLayout.EAST);
}
static class SelectionCaret extends DefaultCaret
{
public SelectionCaret()
{
setBlinkRate( UIManager.getInt("TextField.caretBlinkRate") );
}
public void focusGained(FocusEvent e)
{
setVisible(true);
setSelectionVisible(true);
}
public void focusLost(FocusEvent e)
{
setVisible(false);
}
}
public static void main(String[] args)
{
DefaultCaretTest frame = new DefaultCaretTest();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
Of course the selection will remain when focus is on any other component, not just the combo box.
You can also use:
comboBox.setFocusable(false);
Since the combo box can't gain focus the focus will remain on the text component, but the problem with this is that the user won't be able to use the keyboard to select a font size from the combo box. A proper GUI design always allows the user to use either the keyboard or the mouse to perform an action.

Java GUI button, dialog window and input

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.

Returning result from the first clicked Jbutton from multiple JButtons java swing

Basically I have n JButtons. If any of them is clicked, they return a certain number.
I have a menu with each of the buttons and when the user clicks one, my menu method returns the number returned by the Button handler. Is it possible?
Something like:
frame.add(button1..)
frame.add(button2..)
frame.add(button3..)
if (button1.isClicked()) {
return button1ActionHandler();
} else if (button2.isClicked()) {
return button2ActionHandler();
} else if (button3.isClicked()) {
return button3ActionHandler();
}
The problem is, the code is not waiting for me to click a button so it won't enter in any of those if's. What can I do for the program to wait for click and how can I check if a button is clicked?
Start by having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners.
Remember, a GUI is an event driven environment, that is, something and then you respond to it.
You need to register an ActionListener against each button, when the button is triggered, you need to take appropriate action.
There are a number of ways you could achieve this, you could set the actionCommand of the buttons with appropriate information that you can use to ascertain what should be done when the button is clicked. You could use the source property of the ActionEvent to determine the source of the event and take appropriate action, as exampels
It sounds like you want to present the user with several options, let him choose one of the options, and then have him press a "submit" button to submit that option to the program. If so, then I think that your best bet is to use JRadioButtons, all added to a ButtonGroup -- this allows only one of the radio buttons to be selected at any time, or use a JComboBox. Either way, it would be easy to extract the information regarding which selection the user made. If you use the first option, use of JRadioButtons, ButtonGroup and a "submit" button, you simply get the selected ButtonModel from the ButtonGroup by calling its getSelection() method, and then extract the actionCommand String from this model by calling getActionCommand(). If you decide on the second option, use of a JComboBox together with a "submit" button, then simply call getSelectedItem() on the JComboBox within your submit button's ActionListener.
Below I show you both options. Note that my submit button doesn't use an ActionListener but rather an AbstractAction, which is kind of like an ActionListener on steroids.
import java.awt.event.ActionEvent;
import javax.swing.*;
public class SelectionEg extends JPanel {
private static final String[] SELECTIONS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
private JComboBox<String> selectionComboBox = new JComboBox<>(SELECTIONS);
public SelectionEg() {
for (String selection : SELECTIONS) {
JRadioButton radioButton = new JRadioButton(selection);
radioButton.setActionCommand(selection);
add(radioButton);
buttonGroup.add(radioButton);
}
add(selectionComboBox);
add(new JButton(new SubmitAction("Submit")));
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name) {
super(name);
putValue(MNEMONIC_KEY, (int) name.charAt(0));
}
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
// nothing selected yet, ignore this
return;
}
String message = "The selected radio button is: " + model.getActionCommand();
System.out.println(message);
message = "The selection from the combo box is: " + selectionComboBox.getSelectedItem();
System.out.println(message);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Selelection Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SelectionEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Auto Click to particular tab when button is clicked in java

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

Open new JFrame when clicking/selecting an item from the combo-box (Java)

I want to create a GUI in which the combo-box allows me to open a new JFrame by pressing an item from the combo-box. Any ideas on how could I dot that?
Instead of that, how about you use an appropriate layout manager (e.g. CardLayout)? This will enable you to easily toggle views within the same container.
Add an ActionListener to the JComboBox:
JComboBox combo = new ...
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// This code runs when an item is selected in the combo.
JFrame frm = new ...
frm.setVisible(true);
}
});
Add an event listener to the comboBox and just handle the event to generate a new JFrame

Categories