JButton + AbstractAction to reset a bunch of JCheckBox(s) - Swing - java

I'm creating a ToolBar with one JButton and some JCheckBoxs to hide or show columns from a JTable.
The JButton main purpose is to once clicked reset all the other JCheckBox in the ToolBar to either all checked or all unchecked. Actually I pretend to once reset is clicked to check all of them.
I can create them and place them, no problems here.
My problem is how to make the JButton once clicked to reset all the JCheckBox in the ToolBar.
Here is my code, where I create them and add the Action.
final JToolBar toolBarTop = new JToolBar();
// The Reset Button
toolBarTop.add(new JButton(new AbstractAction("Reset") {
#Override
public void actionPerformed(ActionEvent e) {
columnModel.setAllColumnsVisible();
}
}));
// Create a JCheckBox for each column
for(int i = 0; i < labelsCheckBox.size(); i++)
{
final int index = i;
toolBarTop.add(new JCheckBox(new AbstractAction(labelsCheckBox.get(i)) {
#Override
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(index);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
}

Create an ArrayList<JCheckBox> class field.
Fill it in the for(int i = 0; i < labelsCheckBox.size(); i++) for loop with the JCheckBoxes that you are creating.
Iterate through this collection setting the state of the JCheckBoxes in your Button's Action.
I wonder if you should be using a JToggleButton for your button.

My problem is how to make the JButton once clicked to reset all the
JCheckBox in the ToolBar.[...] Actually I pretend to once reset is clicked to check all of them.
Try iterating over toolBarTop components asking each one if it's an instance of JCheckBox. If so, set selected to true:
JButton reset = new JButton("Reset");
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Component c : toolBarTop.getComponents()){
if(c instanceof JCheckBox){
JCheckBox checkBox = (JCheckBox) c;
checkBox.setSelected(true);
}
}
}
});
Here's a complete SSCCE to test it:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class Demo {
private void initGUI(){
final JToolBar toolBarTop = new JToolBar();
toolBarTop.add(new JCheckBox("Check 1"));
toolBarTop.add(new JCheckBox("Check 2"));
toolBarTop.add(new JCheckBox("Check 3"));
JButton reset = new JButton("Reset");
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Component c : toolBarTop.getComponents()){
if(c instanceof JCheckBox){
JCheckBox checkBox = (JCheckBox) c;
checkBox.setSelected(true);
}
}
}
});
toolBarTop.add(reset);
JPanel content = new JPanel(new FlowLayout());
content.setPreferredSize(new Dimension(300, 200));
content.add(toolBarTop);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().initGUI();
}
});
}
}

Related

Different value of components from JPanel when coming through different event types

There is one panel which contains 4 components; 1 JLabel, 1 JButton, 1 JTextField and 1 JPopupMenu
There is a method "testMethod()" in which first I get the number of components from the panel and then the type of component(JButton, JLabel etc).
Now there are 2 scenarios occurring when the control flow goes to testMethod():
When coming through JButton click event, it shows 4 components on panel and after get all 4 components
When coming through JMenuItem click event, it shows 3 components on panel(not getting JPopupMenu) and after only 3 components(not getting JPopupMenu)
I don't get it what is causing this behavior. I searched a lot on the internet and also read JPopupMenu documents but found nothing about this.
Following is the code:
(it is a part of very big code so I put here only that code which is showing the scenario)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestProject extends JFrame {
JPanel panel;
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestProject frame = new TestProject();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestProject() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
JLabel lblNewLabel = new JLabel("New label");
panel.add(lblNewLabel);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
testMethod();
}
});
panel.add(btnNewButton);
textField = new JTextField();
panel.add(textField);
textField.setColumns(10);
// Creating upper level container
JPopupMenu editMenu = new JPopupMenu("Edit");
JMenuItem item1 = new JMenuItem("Item 1");
item1.setBackground(Color.WHITE);
JMenuItem item2 = new JMenuItem("Item 2");
item2.setBackground(Color.WHITE);
item2.setBackground(Color.WHITE);
// Setting Copy action listener
item2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
testMethod();
}
});
// Adding the menu items on the popup menu
editMenu.add(item1);
editMenu.add(item2);
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Added check to open menu only on left click
if (e.getButton() == MouseEvent.BUTTON3)
editMenu.show(panel, e.getX(), e.getY());
}
});
// Adding popup menu to the logAreaPanel
panel.add(editMenu);
}
void testMethod()
{
// Here getting number of components of panel
// When coming through JButton click event, it shows 4 components on panel and after get all 4 components
int items = panel.getComponentCount();
Component c;
// Getting all the trees one by one and storing their data into StringBuilder
for(int loopCounter = 0; loopCounter < items; loopCounter++)
{
// here getting different component types
// When coming through JMenuItem click event, it shows 3 components on panel(not getting JPopupMenu) and after only 3 components(not getting JPopupMenu)
c = panel.getComponent(loopCounter);
}
}
}
Any help would be appreciated. :-)
You don't need to add the popup to the component. The preferred way is to just use
panel.setComponentPopupMenu(editMenu);
As per the tutorial, You could use a MouseListener.
//panel.add(editMenu);
panel.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
editMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
That way the component count will always be three, because it is never added to the panel.

Displaying text from selected JRadioButton to JTextArea

I am working on my HOMEWORK (please don't do my work for me). I have 95% of it completed already. I am having trouble with this last bit though. I need to display the selected gender in the JTextArea. I must use the JRadioButton for gender selection.
I understand that JRadioButtons work different. I set up the action listener and the Mnemonic. I think I am messing up here. It would seem that I might need to use the entire group to set and action lister maybe.
Any help is greatly appreciated.
Here is what I have for my code (minus parts that I don't think are needed so others can't copy paste schoolwork):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;
public class LuisRamosHW3 extends JFrame {
private JLabel WelcomeMessage;
private JRadioButton jrbMale = new JRadioButton("Male");
private JRadioButton jrbFemale = new JRadioButton("Female");
public LuisRamosHW3(){
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 30));
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(2,1));
jpRadioButtons.add(jrbMale);
jpRadioButtons.add(jrbFemale);
add(jpRadioButtons, BorderLayout.AFTER_LAST_LINE);
ButtonGroup gender = new ButtonGroup();
gender.add(jrbMale);
jrbMale.setMnemonic(KeyEvent.VK_B);
jrbMale.setActionCommand("Male");
gender.add(jrbFemale);
jrbFemale.setMnemonic(KeyEvent.VK_B);
jrbFemale.setActionCommand("Female");
//Set defaulted selection to "male"
jrbMale.setSelected(true);
//Create Welcome button
JButton Welcome = new JButton("Submit");
add(Welcome);
Welcome.addActionListener(new SubmitListener());
WelcomeMessage = (new JLabel(" "));
add(WelcomeMessage);
}
class SubmitListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
String FirstName = jtfFirstName.getText();
String FamName = jtfLastName.getText();
Object StateBirth = jcbStates.getSelectedItem();
String Gender = gender.getActionCommand(); /*I have tried different
variations the best I do is get one selection to print to the text area*/
WelcomeMessage.setText("Welcome, " + FirstName + " " + FamName + " a "
+ gender.getActionCommmand + " born in " + StateBirth);
}
}
} /*Same thing with the printing, I have tried different combinations and just can't seem to figure it out*/
I have done a similar kind of a problem on JTable where we get the selection from the radio group and then act accordingly. Thought of sharing the solution.
Here, I have grouped the radio buttons using the action listener and each radio button will have an action command associated with it. When the user clicks on a radio button then an action will be fired subsequently an event is generated where we deselect other radio button selection and refresh the text area with the new selection.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class RadioBtnToTextArea {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new RadioBtnToTextArea().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JPanel radioPnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel textPnl = new JPanel();
JRadioButton radioMale = new JRadioButton();
JRadioButton radioFemale = new JRadioButton();
JTextArea textArea = new JTextArea(10, 30);
ActionListener listener = new RadioBtnAction(radioMale, radioFemale, textArea);
radioPnl.add(new JLabel("Male"));
radioPnl.add(radioMale);
radioMale.addActionListener(listener);
radioMale.setActionCommand("1");
radioPnl.add(new JLabel("Female"));
radioPnl.add(radioFemale);
radioFemale.addActionListener(listener);
radioFemale.setActionCommand("2");
textPnl.add(textArea);
panel.add(radioPnl, BorderLayout.NORTH);
panel.add(textPnl, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class RadioBtnAction implements ActionListener {
JRadioButton maleBtn;
JRadioButton femaleBtn;
JTextArea textArea;
public RadioBtnAction(JRadioButton maleBtn,
JRadioButton femaleBtn,
JTextArea textArea) {
this.maleBtn = maleBtn;
this.femaleBtn = femaleBtn;
this.textArea = textArea;
}
#Override
public void actionPerformed(ActionEvent e) {
int actionCode = Integer.parseInt(e.getActionCommand());
switch (actionCode) {
case 1:
maleBtn.setSelected(true);
femaleBtn.setSelected(false);
textArea.setText("Male");
break;
case 2:
maleBtn.setSelected(false);
femaleBtn.setSelected(true);
textArea.setText("Female");
break;
default:
break;
}
}
}
Suggestions:
Make your ButtonGroup variable, gender, a field (declared in the class) and don't declare it in the constructor which will limit its scope to the constructor only. It must be visible throughout the class.
Make sure that you give your JRadioButton's actionCommands. JRadioButtons are not like JButtons in that if you pass a String into their constructor, this does not automatically set the JRadioButton's text, so you will have to do this yourself in your code.
You must first get the selected ButtonModel from the ButtonGroup object via getSelection()
Then check that the selected model is not null before getting its actionCommand text.
For example
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class RadioButtonEg extends JPanel {
public static final String[] RADIO_TEXTS = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
// *** again declare this in the class.
private ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textfield = new JTextField(20);
public RadioButtonEg() {
textfield.setFocusable(false);
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
for (String radioText : RADIO_TEXTS) {
JRadioButton radioButton = new JRadioButton(radioText);
radioButton.setActionCommand(radioText); // **** don't forget this
buttonGroup.add(radioButton);
radioButtonPanel.add(radioButton);
}
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ButtonAction("Press Me", KeyEvent.VK_P)));
setLayout(new BorderLayout());
add(radioButtonPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
add(textfield, BorderLayout.PAGE_START);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
textfield.setText("No radio button has been selected");
} else {
textfield.setText("Selection: " + model.getActionCommand());
}
}
}
private static void createAndShowGui() {
RadioButtonEg mainPanel = new RadioButtonEg();
JFrame frame = new JFrame("RadioButtonEg");
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();
}
});
}
}

modifying addMouseListener()

This is my button Code onclick i want my program to wait for the user to click one JPanel and as the user clicks the JPanel it should print its name on console.
This button code is not showing the output
JPopupMenu popupMenu_1 = new JPopupMenu();
JMenuItem mntmOneToOne = new JMenuItem("One to One");
mntmOneToOne.setIcon(new ImageIcon("C:\\Users\\Ashad\\Desktop\\oneToone.png"));
popupMenu_1.add(mntmOneToOne);
OneToOne.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
MouseListener Listen= new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
String name=new String();
JPanel panel = (JPanel) me.getSource();
// name = panel.getName();
System.out.println(panel.getName());
}
};
}
});
for better help sooner post an SSCCE, short,
runnable, compilable,
because works in my SSCCE, and the answer to
This is my button Code onclick i want my program to wait for the user
to click one JPanel and as the user clicks the JPanel it should print
its name on console.
issue must be in rest of your code,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class MyGridLayout {
public MyGridLayout() {
JPanel bPanel = new JPanel();
bPanel.setLayout(new GridLayout(10, 10, 2, 2));
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
JPanel b = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
};
b.putClientProperty("column", row);
b.putClientProperty("row", col);
b.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JPanel btn = (JPanel) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
});
b.setBorder(new LineBorder(Color.blue, 1));
bPanel.add(b);
}
}
JFrame frame = new JFrame("PutClientProperty Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(bPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyGridLayout myGridLayout = new MyGridLayout();
}
});
}
}
You declared a MouseAdapter in your MouseListener mouseClicked method which just sits there and does exactly nothing because nothing is done with it. If you want to add a MouseListener to a panel do the following:
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
JPanel panel = (JPanel) arg0.getSource();
System.out.println(panel.getName());
}
});

Nothing happens when button is clicked

I'm writing a program in Java where I'm using JTabbedPane. Each tab is associated with a different panel with labels, textfields and a button. I have used GridBagLayout in the panels.
I have added an actionlistener to the button, but when I click it nothing happens.
EDIT: I also have other buttons outside the JTabbedPane which works perfectly fine.
I can see that nothing is happening because I do this:
public void actionPerformed( ActionEvent e ) {
if ( e.getSource() == button ) {
System.out.println("blablabla");
}
and nothing is printed out.
Is there any common problems with using buttons and GridBagLayout/JTabbedPane?
EDIT with SSCCE
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class Hjelp extends JFrame {
private FlowLayout layout;
private JButton button1;
private JButton button2;
private JPanel menu, frontpage;
private JPanel present, previous, something;
public Hjelp() {
layout = new FlowLayout(FlowLayout.CENTER, 10, 20);
setLayout(layout);
setSize(900, 900);
setLocationRelativeTo(null);
setVisible(true);
setPanels();
something = something();
add(something, BorderLayout.CENTER);
something.setVisible(false);
button1 = new JButton("CLICK ME");
add(button1);
buttonListener();
}
private void buttonListener() {
Buttonlistener listener = new Buttonlistener();
button1.addActionListener(listener);
button2.addActionListener(listener);
}
private void setPanels() {
menu = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
frontpage = new JPanel();
previous = frontpage;
present = frontpage;
add(menu);
}
public void visiblePanel() {
previous.setVisible(false);
present.setVisible(true);
}
private JPanel something() {
visiblePanel();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
JComponent panel1 = tab();
tabbedPane.addTab("Click me", panel1);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
panel.add(tabbedPane);
return panel;
}
private JComponent tab() {
JPanel panel = new JPanel(false);
panel.setPreferredSize(new Dimension(870, 300));
panel.setLayout(new GridBagLayout());
GridBagConstraints cs = new GridBagConstraints();
cs.fill = GridBagConstraints.HORIZONTAL;
button2 = new JButton("Click me");
cs.gridx = 1;
cs.gridy = 6;
cs.gridwidth = 1;
panel.add(button2, cs);
return panel;
}
private class Buttonlistener implements ActionListener {
#Override
public void actionPerformed( ActionEvent e ) {
if ( e.getSource() == button1 ) {
present = something;
button1.setVisible(false);
something();
previous = something;
}
else if (e.getSource() == button2) {
System.out.println("Blablabla");
}
}
}
public static void main(String [] args) {
final Hjelp vindu = new Hjelp();
vindu.addWindowListener(
new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
}
}
SOLVED
Solution
You don't need the getSource check at all—your listener is (hopefully) attached to just one button, so if it was invoked, that already means the button was clicked. Remove the check and unconditionally print your string. If you still don't see anything, then you have a problem.
You may not have attached a handler to the actual button, and therefore the event will never get called.
Part 1:
ButtonHandler handler = new ButtonHandler();
button.addActionListener( handler );
Part 2:
public class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event) {
}
}
ALSO: Java GUI can be finicky, rather than using "e.getSource() == button" you could try "button..isFocusOwner()"

How to configure JComboBox not to select FIRST element when created?

Problem:
Update:
From the Java SE 6 API:
public JComboBox() Creates a JComboBox
with a default data model. The default
data model is an empty list of
objects. Use addItem to add items. By
default the first item in the data
model becomes selected.
So I changed to JComboBox(model) as the API says:
public JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes its
items from an existing ComboBoxModel.
Since the ComboBoxModel is provided, a
combo box created using this
constructor does not create a default
combo box model and may impact how the
insert, remove and add methods behave.
I tried the following:
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.setSelectedItem(null);
suggestionComboBox = new JComboBox(model);
suggestionComboBox.setModel(model);
But could not get it to work, the first item is still being selected.
Anyone that can come up with a working example would be very much appreciated.
Old part of the post:
I am using JComboBox, and tried using setSelectionIndex(-1) in my code (this code is placed in caretInvoke())
suggestionComboBox.removeAllItems();
for (int i = 0; i < suggestions.length; i++) {
suggestionComboBox.addItem(suggestions[i]);
}
suggestionComboBox.setSelectedIndex(-1);
suggestionComboBox.setEnabled(true);
This is the initial setting when it was added to a pane:
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
suggestionComboBox.addActionListener(new SuggestionComboBoxListener());
When the caretInvoke triggers the ComboBox initialisation, even before the user selects an element, the actionPerformed is already triggered (I tried a JOptionPane here):
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo1.png
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo2.png
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo3.png
The problem is: My program autoinserts the selected text when the user selects an element from the ComboBox. So without the user selecting anything, it is automatically inserted already.
How can I overcome the problem in this situation? Thanks.
Here is my SSCCE: (finally)
package components;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
public class Temp extends JFrame {
JTextPane textPane;
AbstractDocument doc;
JTextArea changeLog;
String newline = "\n";
private JComboBox suggestionComboBox;
private JPanel suggestionPanel;
private JLabel suggestionLabel;
private JButton openButton, saveButton, aboutButton;
public Temp() {
super("Snort Ruleset IDE");
//Create the text pane and configure it.
textPane = new JTextPane();
textPane.setCaretPosition(0);
textPane.setMargin(new Insets(5, 5, 5, 5));
StyledDocument styledDoc = textPane.getStyledDocument();
if (styledDoc instanceof AbstractDocument) {
doc = (AbstractDocument) styledDoc;
//doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));
} else {
System.err.println("Text pane's document isn't an AbstractDocument!");
System.exit(-1);
}
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(700, 350));
//Create the text area for the status log and configure it.
//changeLog = new JTextArea(10, 30);
//changeLog.setEditable(false);
//JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
//Create a JPanel for the suggestion area
suggestionPanel = new JPanel(new BorderLayout());
suggestionPanel.setVisible(true);
suggestionLabel = new JLabel("Suggestion is not active at the moment.");
suggestionLabel.setPreferredSize(new Dimension(100, 50));
suggestionLabel.setMaximumSize(new Dimension(100, 50));
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
//suggestionComboBox.addActionListener(new SuggestionComboBoxListener());
suggestionComboBox.addItemListener(new SuggestionComboBoxListener());
//suggestionComboBox.setSelectedIndex(-1);
//add the suggestionLabel and suggestionComboBox to pane
suggestionPanel.add(suggestionLabel, BorderLayout.CENTER);
suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);
JScrollPane sp = new JScrollPane(suggestionPanel);
JScrollPane scrollPaneForSuggestion = new JScrollPane(suggestionPanel);
//Create a split pane for the change log and the text area.
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
scrollPane, scrollPaneForSuggestion);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(1.0);
//Disables the moving of divider
splitPane.setEnabled(false);
//splitPane.setDividerLocation(splitPane.getHeight());
//splitPane.setPreferredSize(new Dimension(640,400));
//Create the status area.
JPanel statusPane = new JPanel(new GridLayout(1, 1));
CaretListenerLabel caretListenerLabel =
new CaretListenerLabel("Status: Ready");
statusPane.add(caretListenerLabel);
//Create the toolbar
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
openButton = new JButton("Open Snort Ruleset");
toolBar.add(openButton);
saveButton = new JButton("Save Ruleset");
toolBar.add(saveButton);
toolBar.addSeparator();
aboutButton = new JButton("About");
toolBar.add(aboutButton);
//Add the components.
getContentPane().add(toolBar, BorderLayout.PAGE_START);
getContentPane().add(splitPane, BorderLayout.CENTER);
getContentPane().add(statusPane, BorderLayout.PAGE_END);
JMenu editMenu = createEditMenu();
JMenu styleMenu = createStyleMenu();
JMenuBar mb = new JMenuBar();
mb.add(editMenu);
mb.add(styleMenu);
setJMenuBar(mb);
//Put the initial text into the text pane.
//initDocument();
textPane.setCaretPosition(0);
//Start watching for undoable edits and caret changes.
textPane.addCaretListener(caretListenerLabel);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textPane.requestFocusInWindow();
}
});
}
//This listens for and reports caret movements.
protected class CaretListenerLabel extends JLabel
implements CaretListener {
public CaretListenerLabel(String label) {
super(label);
}
//Might not be invoked from the event dispatch thread.
public void caretUpdate(CaretEvent e) {
caretInvoke(e.getDot(), e.getMark());
}
protected void caretInvoke(final int dot, final int mark) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Rectangle caretCoords = textPane.modelToView(dot);
//Find suggestion
suggestionComboBox.removeAllItems();
for (int i = 0; i < 5; i++) {
suggestionComboBox.addItem(Integer.toString(i));
}
//suggestionComboBox.setSelectedItem(null);
suggestionComboBox.setEnabled(true);
suggestionLabel.setText("The following keywords are normally used as well. Click to use keyword(s). ");
//changeLog.setText("The following keywords are suggested to be used together: " + str);
} catch (BadLocationException ble) {
setText("caret: text position: " + dot + newline);
System.out.println("Bad Location Exception");
}
}
});
}
}
public class SuggestionComboBoxListener implements ItemListener {
//public void actionPerformed(ActionEvent e) {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox cb = (JComboBox)e.getSource();
String selection = (String) cb.getSelectedItem();
JOptionPane.showMessageDialog(null, "Item is selected", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
}
/*
* Menu Creation
*/
//Create the edit menu.
protected JMenu createEditMenu() {
JMenu menu = new JMenu("Edit");
return menu;
}
protected JMenu createStyleMenu() {
JMenu menu = new JMenu("Style");
return menu;
}
private static void createAndShowGUI() {
//Create and set up the window.
final Temp frame = new Temp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//The standard main method.
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
You need to remove the ItemListener before you make any changes to the combo-box and add it back when you are done.
Something like this:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Suggestions {
private JFrame frame;
private JTextPane textPane;
private JComboBox suggestionComboBox;
private SuggestionComboBoxListener selectionListener;
public Suggestions() {
frame = new JFrame("Snort Ruleset IDE");
textPane = new JTextPane();
textPane.setCaretPosition(0);
textPane.setMargin(new Insets(5, 5, 5, 5));
textPane.addCaretListener(new SuggestionCaretListener());
JScrollPane textEntryScrollPane = new JScrollPane(textPane);
textEntryScrollPane.setPreferredSize(new Dimension(300, 400));
selectionListener = new SuggestionComboBoxListener(frame);
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
suggestionComboBox.addItemListener(selectionListener);
JPanel suggestionPanel = new JPanel(new BorderLayout());
suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);
frame.getContentPane().add(textEntryScrollPane, BorderLayout.NORTH);
frame.getContentPane().add(suggestionPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private final class SuggestionCaretListener implements CaretListener {
#Override
public void caretUpdate(CaretEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generateSuggestions();
}
});
}
}
public static final class SuggestionComboBoxListener implements ItemListener {
Component parent;
public SuggestionComboBoxListener(Component parent) {
this.parent = parent;
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox cb = (JComboBox) e.getSource();
String selection = (String) cb.getSelectedItem();
JOptionPane.showMessageDialog(parent, "The selected item is: " + selection, "Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
void generateSuggestions() {
suggestionComboBox.removeItemListener(selectionListener);
suggestionComboBox.removeAllItems();
for (int i = 0; i < 5; i++) {
suggestionComboBox.addItem(Integer.toString(i));
}
suggestionComboBox.setEnabled(true);
suggestionComboBox.addItemListener(selectionListener);
}
public static void main(String[] args) {
new Suggestions();
}
}
BTW, what you posted is not an SSCCE it is a dump of your code. An SSCCE should only have enough code to reproduce the issue you are experiencing.
use
setSelectedItem(null);
Please try with ItemListener instead of ActionListener.
if You want that after 1st entry you made and immediately you combox is empty then just write down the under mentioned code which is:
jComboBox1.setSelectedIndex(0);
and your combox will reset Automatically

Categories

Resources