I am trying to toggle visibility of a JTextField with a checkbox. If the checkbox is selected I want the JTextField to be displayed and vice-versa. My program works fine until I add the line that initializes the JTextField to be invisible at the start. If I remove this the segment works fine! Can you help me?
final JCheckBox chckbxNewCheckBox_1 = new JCheckBox("New Folder");
panel_3.add(chckbxNewCheckBox_1);
final JTextField textField_3 = new JTextField();
panel_3.add(textField_3);
textField_3.setColumns(20);
//textField_3.setVisible(false); if a comment it in.. it never becomes visible
chckbxNewCheckBox_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(chckbxNewCheckBox_1.isSelected()){
textField_3.setVisible(true);
}
else
textField_3.setVisible(false);
}
});
Try with ActionListener instead of MouseListener
checkBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
textField_3.setVisible(checkBox.isSelected());
}
});
--EDIT--
call panel_3.revalidate(); after changing its visibility.
When an element is invisible during container initialization, it never gets its dimensions initialized. You can check it by calling getWidth() and getHeight() on the text area after you set it to visible. They're both zero. So follow #Braj edit and call panel.revalidate() after you change element visibility to let layout manager know that it's time to reposition/recalculate some elements and give them proper size.
You will do better with ItemListener
chckbxNewCheckBox_1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.DESELECTED))
textField_3.setVisible(false);
else if (e.getStateChange() == ItemEvent.SELECTED))
textField_3.setVisible(true);
textField_3.revalidate();
}
});
Note: pelase follow naming conventions and use underscores only for constants.
Consider calling pack() method
Below is the complete code I experimented with:
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
final JCheckBox chckbxNewCheckBox_1 = new JCheckBox("New Folder");
final JPanel panel_3 = new JPanel();
frame.add(panel_3);
panel_3.add(chckbxNewCheckBox_1);
final JTextField textField_3 = new JTextField();
panel_3.add(textField_3);
textField_3.setColumns(20);
textField_3.setVisible(false); //if a comment it in.. it never becomes visible
chckbxNewCheckBox_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if (chckbxNewCheckBox_1.isSelected()) {
textField_3.setVisible(true);
} else
textField_3.setVisible(false);
frame.pack();
}
});
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Related
I have a frame, on this frame I have a Menu with About MenuItem. When we select it the program opens a new JPanel with texts and with OK button and the enabled status of parent panel is set to false.
And now comes a problem. When we click on OK, then I want to close this About panel, and I want to turn to parent panel, and I want to enable it!
Please tell me, how?
Consider using a WindowListener that reacts to the closing event of the about-dialog. You can add this in your frame or in the constructor of your dialog, just set the variables accordingly.
myDialog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
parentFrame.setEnabled(true);
}
});
If you really only have a switching JPanel, use a ButtonListener.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
frame.setEnabled(true);
}
});
As mentioned in the comments, using a modal JDialog would be a more elegant way of solving the problem of disabling a parent frame while a dialog is active. Here is a tutorial.
Why don't you use simply a JOptionPane (particularly the showMessageDialog method)? You can specify there an Object (for example a JPanel) which will be presented in a modal dialog. Take a look at this sample code I've written for you (I've used a JButton, but it will be the same for JMenuItem):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class AboutDialogDemo extends JFrame {
private final JButton btnAbout = new JButton("About...");
public AboutDialogDemo() {
final JFrame thisFrame = this;
btnAbout.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(thisFrame, new AboutPanel());
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(btnAbout, BorderLayout.PAGE_END);
pack();
}
public static void main(String[] args) {
AboutDialogDemo frame = new AboutDialogDemo();
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class AboutPanel extends JPanel {
private final JLabel lblAbout = new JLabel("Sample about text");
public AboutPanel() {
setLayout(new BorderLayout());
add(lblAbout, BorderLayout.PAGE_START);
}
}
I hope you'll find it useful
I have a program that is designed simply to make and test a user interface. The current setup is that it displays a large black screen with text, and a box for user input at the bottom, and a scrollbar on the right side. I've got everything working the way I want it except that the scrollbar absolutely will not scroll. It is there, but doesn't seem connected at all to the textarea. You can press the buttons on the bar, but they don't do anything. Any help would be appreciated!
Here is the code I have so far:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class RandomTest extends JFrame implements KeyListener{
JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JFrame frame = new JFrame();
static JTextArea txt;
static JTextField inputField;
static String text;
static String choice;
static boolean enter = false;
Container positioner = frame.getContentPane();
RandomTest(){
text = "";
txt = new JTextArea(text);
txt.setEditable(false);
inputField = new JTextField("");
txt.setBackground(Color.black);
txt.setFont(new Font("Courier New", Font.PLAIN, 18));
txt.setForeground(Color.lightGray);
inputField.setBackground(Color.black);
inputField.setFont(new Font("Courier New", Font.PLAIN, 18));
inputField.setForeground(Color.lightGray);
panel.add(txt);
panel.add(inputField);
//Dimension d = new Dimension(500,500);
//scrollPane.setPreferredSize(d);
panel.add(scrollPane);
frame.add(panel);
frame.setSize(500,500);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
positioner.setLayout(new BorderLayout());
positioner.add(inputField, BorderLayout.PAGE_END);
positioner.add(scrollPane, BorderLayout.EAST);
positioner.add(txt, BorderLayout.CENTER);
positioner.setBackground(Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
inputField.addKeyListener(this);
}
public static void main(String[] arg){
new RandomTest();
println("Please enter the letter 'm'");
for(;;){
println("/\n/\n/\n/\n/\n/\n/\n/\n");
if(input().equals("m")){
println("Thank you.");
}else{
println("Try again.");
}
}
}
public static void println(String line){
text += line + "\n";
txt.setText(text);
}
public static String input(){
for(;;){
if(enter == true){
enter = false;
return choice;
}else{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
if(enter == true){
enter = false;
return choice;
}
}
}
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
choice = inputField.getText();
inputField.setText("");
enter = true;
try{
Thread.currentThread().interrupt();
}catch(Exception E){
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
There's nothing attached to the scroll pane's view, so there is nothing for it to scroll...
You need to supply a component view for the scroll, using something like scrollPane.setViewportView(...);
You may want to take a look at How to use scroll panes for some more details
There's a lot of things in you code that worry me...
Thread.sleep in a GUI environment is always of concern, given that this could actually cause your application to become unresponsive. The use of infinite loops, for the same reason.
The use of KeyListener which is simply performing the same function of an ActionListener
The fact that you are adding txt and inputField and scrollPane to two different containers and txt is actually supplementing panel...
You may like to spend some time reading through
Creating a GUI With JFC/Swing
Using Text Components
How to Write an Action Listener
Concurrency in Swing
I need to display a swing popup with my custom component. The popup should stay visible, until I hide it myself, but shouldn't get focus.
I have a code written by some other developer that does it in the following way:
popupMenu = new JPopupMenu();
popupMenu.add(myCustomComponent, BorderLayout.CENTER);
popupMenu.setFocusable(false);
popupMenu.setVisible(true);
popupMenu.show(parentComponent, x, y);
This seems to work, but has a bug - when the popup is visible, first mouse click outside the component is consumed by the popup. So I need to click twice to set focus to another component.
How can I fix it? Or what is correct way to make the popup?
UPDATE
At last I've managed to reproduce my problem in short code fragment. Thanks to Guillaume Polet for giving me a starting point.
Here's the code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class TestJPopup {
protected void initUI() {
JFrame frame = new JFrame(TestJPopup.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField("Some text field");
frame.add(textField, BorderLayout.WEST);
final JButton buttonToHit = new JButton("Hit me");
buttonToHit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(buttonToHit, "You hit the button successfully");
}
});
frame.add(buttonToHit);
frame.setSize(200, 100);
frame.setVisible(true);
final JPopupMenu popup = new JPopupMenu();
popup.add(new JLabel("<html>Hey!<br>I'm the popup window!</html>"),
BorderLayout.NORTH);
popup.setFocusable(false);
popup.setVisible(true);
popup.show(textField, 60, 60);
// I want to activate popup when user clicks in the text field
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (popup != null) {
popup.show(textField, 60, 60);
}
}
});
}
public static void main(String[] args) throws Exception {
Class lnfClass = Class.forName("com.sun.java.swing.plaf.windows.WindowsLookAndFeel", true,
Thread.currentThread().getContextClassLoader());
LookAndFeel feel = (LookAndFeel) lnfClass.newInstance();
UIManager.setLookAndFeel(feel);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestJPopup().initUI();
}
});
}
}
Two critical moments:
Windows look and feel used (with default not reproducible)
Mouse listener attached to text field in main frame
Not an answer, but just an example SSCCE in which I can't currently reproduce the behaviour you described. Maybe start from this code, try to reproduce the error and the edit your post with modified non-working code.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestJPopup {
protected void initUI() {
JFrame frame = new JFrame(TestJPopup.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel leftLabel = new JLabel("Left");
frame.add(leftLabel, BorderLayout.WEST);
final JButton buttonToHit = new JButton("Hit me");
buttonToHit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(buttonToHit, "You hit the button successfully");
}
});
frame.add(buttonToHit);
frame.setSize(500, 400);
frame.setVisible(true);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(new JLabel("<html>A Custom<br>component<br>made to<br> simulate <br>your custom component</html>"),
BorderLayout.NORTH);
JTextField textfield = new JTextField(30);
popupMenu.add(textfield);
popupMenu.setFocusable(false);
popupMenu.setVisible(true);
popupMenu.show(leftLabel, 20, 20);
// Let's force the focus to be in a component in the popupMenu
textfield.requestFocusInWindow();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestJPopup().initUI();
}
});
}
}
Not a solution, but:
Looks like a bug to me, even a plain componentPopup exhibits the same mis-behaviour (in winLAF and Nimbus, not in Metal):
JTextField field = new JTextField("some popup owner");
JPopupMenu menu = new JPopupMenu();
menu.add("dummy");
field.setComponentPopupMenu(menu);
Action action = new AbstractAction("hit me!") {
#Override
public void actionPerformed(ActionEvent e) {
LOG.info("got hit!");
}
};
JComponent content = new JPanel();
content.add(new JButton(action));
content.add(field);
for quick research and/or for future readers,
this issue is reproducible and presented for,
a) JPopup
b) JMenu
tested on jdk1.6.0_25 and jdk1.7.0_04,
same issue on WinXp and Win7,
for Look and Feel to SystemLookAndFeel / WindowsLookAndFeel,
Here's a possible workaround with JWindow instead of JPopupMenu, that was proposed by mKorbel in comments:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestJPopup {
protected void initUI() {
final JFrame frame = new JFrame(TestJPopup.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField("Some text field");
frame.add(textField, BorderLayout.WEST);
final JButton buttonToHit = new JButton("Hit me");
buttonToHit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(buttonToHit, "You hit the button successfully");
}
});
frame.add(buttonToHit);
frame.setSize(200, 70);
frame.setVisible(true);
final JWindow popup = new JWindow();
popup.getContentPane().add(new JLabel("<html>Hey!<br>I'm the popup window!</html>"),
BorderLayout.NORTH);
popup.setLocation(frame.getLocation().x + 60, frame.getLocation().y + 60);
popup.pack();
popup.setFocusable(false);
popup.setVisible(true);
// I want to activate popup when user clicks in the text field
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
if (popup != null) {
popup.setVisible(true);
popup.setLocation(frame.getLocation().x + 60, frame.getLocation().y + 60);
popup.toFront();
}
}
});
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
if (popup != null) {
popup.setVisible(false);
}
}
});
}
public static void main(String[] args) throws Exception {
Class lnfClass = Class.forName("com.sun.java.swing.plaf.windows.WindowsLookAndFeel", true,
Thread.currentThread().getContextClassLoader());
LookAndFeel feel = (LookAndFeel) lnfClass.newInstance();
UIManager.setLookAndFeel(feel);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestJPopup().initUI();
}
});
}
}
Here is the magic line that fixes the problem:
UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE);
I found this after looking into the source code for the BasicPopupMenuUI class. Apparently this behaviour is a deliberate design choice according to the following comments in the code, but it sure feels like a bug to me.
// Ask UIManager about should we consume event that closes
// popup. This made to match native apps behaviour.
By the way, it happens in Java 5 and 6 too.
I was making a simple text editor where you can set font style,font size, clear all etc. To set font size I added JComboBox and implemented ItemListener. Here is my MainWindow class:
import javax.swing.*;
public class MainWindow extends JFrame{
Editor e = new Editor();
public MainWindow(){
super(".:My Text Editor:.");
getContentPane().add(e);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new MainWindow();
}
});
}
}
Here is my Editor class:
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Editor extends JPanel{
JPanel optionPanel = new JPanel();
JTextArea editArea = new JTextArea();
JButton boldBtn = new JButton("Bold");
JButton italicBtn = new JButton("Italic");
JButton plainBtn = new JButton("Plain");
JButton clearBtn = new JButton("Clear all");
String [] fontSizes = {"10","11","12","13","14","15","16","17","18","19","20"};
int fontSize;
JComboBox combo = new JComboBox(fontSizes);
public Editor(){
createUI();
addEvents();
}
public void createUI(){
optionPanel.add(boldBtn);
optionPanel.add(italicBtn);
optionPanel.add(plainBtn);
optionPanel.add(combo);
optionPanel.add(clearBtn);
setLayout(new BorderLayout());
add(optionPanel,BorderLayout.NORTH);
add(new JScrollPane(editArea),BorderLayout.CENTER);
setPreferredSize(new Dimension(640,480));
}
public void addEvents(){
boldBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setFont(new Font("Sans Serif",Font.BOLD,fontSize));
}
});
italicBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setFont(new Font("Sans Serif",Font.ITALIC,fontSize));
}
});
plainBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setFont(new Font("Sans Serif",Font.PLAIN,fontSize));
}
});
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
int ind = combo.getSelectedIndex();
System.out.println(ind);
fontSize = Integer.parseInt(fontSizes[ind]);
editArea.setFont(new Font("Sans Serif",Font.PLAIN,fontSize));
}
});
clearBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
editArea.setText("");
}
});
}
}
Now, weird thing what happened is when I put System.out.println(ind); line just to see what index the getSelectedIndex() method returns me. Depending on which item I click, it returns me this:
1
1
0
0
2
2
3
3
Why is this happening? Shouldn't return me just 1 0 2 3? Thanks in advance.
JCombobox fire itemStateChanged twice for SELECTED and DESELECTED that you differentiate with ItemEvent.getStateChanged(). So wrap your code in an if like this:
public void itemStateChanged( ItemEvent event ) {
if( event.getStateChanged() == ItemEvent.SELECTED ) {
// code here
}
}
Whenever you change the selection in a JComboBox, the itemStateChanged event is triggered twice, once for DESELECT of the old selected item and once for SELECT for the new selected item.
If you only want your code to be executed once, just do:
if (e.getStateChange() == ItemEvent.SELECTED) {
...
}
Seems that itemStateChanged is triggered twice. I think that the ItemEvent parameter is not the same each time. Perhaps you should check the event type before doing something.
Sorry I can't check now, but I will do it later if you still need help.
I have a JComboBox shown in the code below. When the program starts its actionPerformed event fires up immediately causing some null pointer exceptions so I want to start with none of the elements selected. However, for some reason it does not work (it always start with displaying "USD/TRY" whatever I do). Anyone has any idea ?
JComboBox comboBox = new JComboBox(new String[]{"USD/TRY", "EUR/TRY", "GBP/TRY"});
comboBox.setSelectedIndex(-1); // doesnt change anything
comboBox.setSelectedIndex(2); // doesnt change anything
comboBox.setSelectedItem(null); // doesnt change anything
UPDATE: Building the combo box like below doesnt change anything either
JComboBox comboBox = new JComboBox();
comboBox.addItem("USD/TRY");
comboBox.addItem("EUR/TRY");
comboBox.addItem("GBP/TRY");
Here is the SSCCE:
public class MainFrame {
private final JTextArea textArea = new JTextArea();
private IExchangeSource s;
public MainFrame(final IExchangeSource s) {
//build gui
final JComboBox comboBox = new JComboBox();
comboBox.addItem("USD/TRY");
comboBox.addItem("EUR/TRY");
comboBox.addItem("GBP/TRY");
comboBox.setSelectedIndex(-1); // doesnt change anything
//comboBox.setSelectedIndex(2); // doesnt change anything
JFrame f = new JFrame("Currency Converter");
JPanel p = new JPanel(new BorderLayout());
textArea.setName("textarea");
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
this.s = s;
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String exchange = (String) comboBox.getSelectedItem();
s.getData(exchange);
}
});
p.add(comboBox, BorderLayout.NORTH);
p.add(textArea, BorderLayout.CENTER);
f.setPreferredSize(new Dimension(300, 300));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.add(p);
comboBox.setSelectedIndex(0);
f.setVisible(true);
}
}
Your (incomplete) example invokes
comboBox.setSelectedIndex(0);
right before becoming visible, canceling any previous setting. Set the desired initial index before adding the listener, and don't neglect to start on the EDT, as shown in the sscce below.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MainFrame {
private final JTextArea textArea = new JTextArea();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
public MainFrame() {
//build gui
final JComboBox comboBox = new JComboBox();
comboBox.addItem("USD/TRY");
comboBox.addItem("EUR/TRY");
comboBox.addItem("GBP/TRY");
JFrame f = new JFrame("Currency Converter");
JPanel p = new JPanel(new BorderLayout());
textArea.setName("textarea");
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
comboBox.setSelectedIndex(-1);
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(comboBox.getSelectedItem() + ": " + e);
}
});
p.add(comboBox, BorderLayout.NORTH);
p.add(textArea, BorderLayout.CENTER);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setSize(new Dimension(300, 300));
f.add(p);
f.setVisible(true);
}
}
1) add ItemListener instead of ActionListener, but this ItemListener always fired twice events SELECTED and DESELECTED,
myComboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
//some stuff
}
}
});
2) your GUI maybe is or isn't created on EventDispashThread, but in this case doesn't matter, you have to delay this method by wraping into invokeLater(), for example
public class MainFrame {
.
.
.
f.setPreferredSize(new Dimension(300, 300));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.add(p);
comboBox.setSelectedIndex(0);
f.setVisible(true);
selectDesiredItem();
}
private void selectDesiredItem() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
comboBox.setSelectedIndex(-1);
}
});
}
3) better would be implements AutoCompete JComboBox / JTextField for Currency Pairs
4) maybe not important but CcyPairs have got four sides by default
Buy BaseCcy
Sell BaseCcy
Buy VariableCcy
Sell VariableCcy
The suggestions so far are good. But sometimes, when things are really convoluted on how Components get constructed, a more direct fix is needed:
subclass the JComboBox (or whatever Swing class is firing the events, JList, etc...)
add a field, private boolean fireEvents = false; Consider making it volatile.
override the relevant fireXXX() methods to check the status of fireEvents
only set fireEvents = true after all construction and initialization is complete
if a "major overhaul" is later called for, such as on loading a new file, new settings, you can set fireEvents back to false while rebuilding everything.