jcombobox popup menue - java

What I am hoping is, when typing in editable JCombobox , the Popup Menu of the JCombobox to appear autumaticaly , i did this and it worked . But, when i changed the Icon of the Arrow Button in the JCombobox it didnt worked any more as shown in the picture
before changing Arrow Button Icon
After changing Arrow Button Icon (the Popup never appears, when one writes in the JCombobox)
this is what i did :
JTextComponent editor;
/** Creates new form combo */
public combo() {
initComponents();
editor = (JTextComponent) jComboBox1.getEditor().getEditorComponent();
jComboBox1.setEditable(true);
editor.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
char keyChar = e.getKeyChar();
if (jComboBox1.isDisplayable())
{
jComboBox1.setPopupVisible(true);
}
editor.setCaretPosition(editor.getText().length());
// System.out.println("wwwweeeee"+keyChar);
}
});
jComboBox1.setUI(new SynthComboBoxUI() {
protected JButton createArrowButton() {
JButton btn = new JButton();
btn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/error3.png")));
return btn;
}
});
}
Pleeeese help because i'm really tired from searching for a solution

The technical problem here is that the editor is created/maintained by the ui. When setting a custom ui it is replaced by a new editor, so you are listening to a component that is no longer part of the container hierarchy.
After digging a bit ... I still don't have a solution :-( On face value, you'd call setUI before installing the listener on the editor - BUT calling setUI is always wrong ... so simply don't.
Seeing that the ui is synth-based, the correct way to update its visual fore/background properties is to supply custom painters, per-application or per-instance. Nimbus specifically allows to install per-instance custom UIDefaults via the "Nimbus.Overrides" client property. For changing the icon on the arrow button, the appropriate override would be
Painter core = // a custom painter which paints the icon
comboDefaults.put("ComboBox:\"ComboBox.arrowButton\"[Enabled].foregroundPainter", core);
combo.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
combo.putClientProperty("Nimbus.Overrides", comboDefaults);
All fine, except not working - looks like the overrides are not properly installed on the children.
Edit 2
... hours later ...
from all available resources, the above should work, see f.i. Jasper's initial explanation of how-to define custom properties:
ComponentA:ChildComponentB.foreground which lets you specify a ChildComponentB contained within ComponentA.
So I suspect it's really a bug. A not really satisfying hack-around is to install the override on the button itself:
JButton org = null;
for (int i = 0; i < combo.getComponentCount(); i++) {
if (combo.getComponent(i) instanceof JButton) {
org = (JButton) combo.getComponent(i);
UIDefaults buttonDefaults = new UIDefaults();
buttonDefaults.put("ComboBox:\"ComboBox.arrowButton\"[Enabled].foregroundPainter", painter);
org.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
org.putClientProperty("Nimbus.Overrides", buttonDefaults);
break;
}
}
That's not satisfying at all, as the button creation is controlled by the ui delegate, so this config will not survive a switch of LAF. Or the other way round: you'll need a install a PropertyChangeListener with the UIManager and on detecting a switch to Nimbus, manually copy the overrides from the combo to its children.

Related

Changing to color of a JToggleButton only when the button is selected, afterwards it will go back to the default color

This may end up being noted as a formerly asked question, however the other questions have yet to answer the question that I have asked properly, to what I need them to do.
I want it to be that whenever I click the ToggleButton it will set the color of the ToggleButton to black (in this case), and then when I unclick the button it will return to the default color.
Here is the code for the individual button, its possible Ill have to create a new class (I am using Eclipse) but if anyone could help id be extremely thankful. (I also have Jigloo)
jToggleButton4 = new JToggleButton();
getContentPane().add(jToggleButton4);
FlowLayout jToggleButton4Layout = new FlowLayout();
jToggleButton4.setLayout(jToggleButton4Layout);
jToggleButton4.setText("Black");
jToggleButton4.setPreferredSize(new java.awt.Dimension(133, 249));
You can take the default color/ the color you keep initially and can toggle the background color with an ActionEvent,
JToggleButton jtb = new JToggleButton("My Button");
Color defaultColor=jtb.getBackground();
jtb.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ev) {
if(jtb.getBackground()==defaultColor)
jtb.setBackground(Color.BLACK);
else
jtb.setBackground(defaultColor);
repaint();//repaint your frame
System.out.println("BackGround color changed!");
}
});

Setting Actor To Listen For Button Click In LibGDX

Background Information: I am currently working in a Dialog class I have extended for my game. Inside of this dialog's content table I have both an Image and a Table (lets call it ioTable). Inside of ioTable I have a combination of both Labels and TextFields. The idea is that the dialog becomes a sort of form for the use to fill out.
Next, inside of the Dialog's button table, I want to include a "Clear" TextButton (clearButton). The idea that clearButton will clear any values written to the TextFields of ioTable.
My Question: Is is possible to add a listener to each of the TextFields of ioTable that will trigger when clearButton is pressed. As always, any other creative solution is more than welcome.
You could just give the EventListener a reference to the table you want to clear:
// Assuming getSkin() and ioTable are defined elsewhere and ioTable is final
TextButton clearButton = new TextButton("Clear", getSkin());
clearButton.addListener(new EventListener() {
#Override
public boolean handle(Event event) {
for(Actor potentialField : table.getChildren()) {
if(potentialField instanceof TextField) {
((TextField)potentialField).setText("");
}
}
return true;
}
});
// Add clearButton to your dialog
If you see yourself creating multiple clearButtons, you could easily wrap this in a helper method or extend TextButton.

Java Swing Call Method Before Focus Change

I am working with a java swing form that contains a JTextField. The text field needs input validation , validation is performed when the field losses focus . i.e clicking anyware apart from the field itself.
The form also contains a JButton to clear(cancel) the form . Now whenever I press the cancel button and the Textfield is the currently focused component the validation function is invoked. This should not happen.
I have tried InputVerifier and Focuslistener
Is there a way I can know what component caused the focus to change ?
This is fine but the form contains a JButton to clear(cancel) the form
You can use:
clearButton.setVerifyInputWhenFocusTarget(false);
to prevent the InputVerifier from being invoked when you click on the button.
You can use a FocusListener to react to a focusLost event. There you can retrieve the destination of the focus via getOppositeComponent() from the FocusEvent. If the destination is the clear/cancel/whatever button do nothing, otherwise validate.
A very basic example for this:
JTextField textField = new JTextField(15);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
Component comp = e.getOppositeComponent();
if (comp instanceof JButton) {
JButton button = (JButton) comp;
String buttonText = button.getText();
if (buttonText.equals("Cancel")) {
return;
}
}
// do the validation
System.out.println("validate");
}
});
Actually camickr's solution is a lot simpler than mine above. I had no idea that there was built in solution for this.

performing multiple actions on one button in java swing

I am trying to create a wizard in java swing programatically.
On the wizard pane I have a next button and it has to perform multiple actions according to which panel is displayed on the wizard.
Is it possible to use java command pattern? may I know how?
thanks in advance.
the code i used for the wizard is
this.mainPanel.add(fileSelectionPane,"SELECT FILE");
this.mainPanel.add(sqlConnectionPane,"SQL CONNECTION");
this.mainPanel.add(devicePane,"PARSER");
this.mainPanel.add(detailsPane,"DISPLAY");
thisLayout.show(this.mainPanel,"SELECT FILE");
this.finishButton.setEnabled(false);
this.backButton.setEnabled(false);
if(newValue==1) {
this.thisLayout.show(this.mainPanel, "SQL CONNECTION");
this.nextButton.setEnabled(true);
this.nextButton.setText("Connect..");
this.cancelButton.setEnabled(true);
this.backButton.setEnabled(true);
}
if(newValue==2) {
this.thisLayout.show(this.mainPanel, "PARSER");
this.nextButton.setEnabled(true);
this.nextButton.setText("Parse..");
this.cancelButton.setEnabled(true);
this.backButton.setEnabled(true);
}
i want the next button to perform specific actions on SELECT FILE and SQL CONNECTION.
is it possible to use command patterns?
Ok, so, You add action listeners to buttons. These action listeners do something when an event occurs.
You want to change the functionality of the button depending on which panel is being displayed? Why not set a instance variable which reflects the state of the Wizard?
For example (roughly),
int state = 0; // home panel
change panel to help page, event listener is fire, set 'state' to 1. You are now tracking which panel is being displayed.
Now, in your original problem, when the button (the one you want multiple functionality with) fires, you can choose the action it will take based on the 'state' var.
have look at CardLayout
those cards put to the JDialog (JDialog has preimplemented by default BorderLayout) to the CENTER area
create a new JPanel and place there JButtons
JPanel with JButtons put to the SOUTH area
search here, on this forum, there are a few excelent examples for wizard or image previue based on CardLayout
try the following code for button:
JButton btn1;
btn1= new javax.swing.JButton();
btn1.setToolTipText("Submit");
btn1.setContentAreaFilled(false);
btn1.setBorderPainted(false);
btn1.setMargin(new java.awt.Insets(2, 2, 2, 2));
btn1.addActionListener(this);
btn1.setIcon(this.getIcons()[21]);
add(btn1); // add to Jpanel
btn1.setBounds(250,10, 12, 12);
public void actionPerformed(java.awt.event.ActionEvent evt) {
Object obj = evt.getSource();
if (obj == btn1) {
// your function on on click of button
return;
}

Remove "X" button in Swing JDialog

Is there a way to remove the close button ("X") from the JDialog title bar?
You can remove the whole dialog title by calling dialog.setUndecorated(true) but this means that the dialog can't be moved anymore.
You can also execute dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) to prevent that the button does anything.
Besides that, I don't think that there's a way to remove the X completely.
I believe that you can call dialog.setUndecorated(true) to remove the title bar. Not sure about just the 'X' though.
Removing the 'X' may not be a great idea, though, as you want your users to be able to close the dialog easily.
Best bet is to control what happens when the users clicks the 'X' by using dialog.setDefaultCloseOperation or a WindowListener.
As of Java 1.7 (AKA Dolphin or Java 7), you can not disable or remove the close button on a Window. You can remove/disable the maximize button with frame.setResizable(false) and you can remove the minimize and maximize buttons by using a java.awt.Dialog or a class that extends it, such as javax.swing.JDialog. You can remove the title bar, borders, and buttons with frame.setUndecorated(true), and you can have full control over the visibility of all buttons in the title bar (while losing some cross-platform compatibility and OS integration) with frame.setDefaultLookAndFeelDecorated(true) (assuming it's a JFrame or JDialog). This is all the control I see possible with the current JDK.
Here is my experience:
Tried using setUndecorated(true): Made the whole Dialog invisible.
Tried setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE): This didn't change the behavior at all. My dialog box still closed. Setting the default close operation to DO_NOTHING_ON_CLOSE delegates the close operation to the windowClosing() method of a registered WindowListener.
What worked for me was:
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
//Remove any existing WindowListeners
for (WindowListener wl : this.getWindowListeners()) {
this.removeWindowListener(wl);
}
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
if ("Optional condition") {
JOptionPane.showMessageDialog(null, "You cannot close this window");
}
}
});
At a guess, set it to be PL&F decorated and remove the component by name.
static public void removeButtons(Component c){
if (c instanceof AbstractButton){
String accn = c.getAccessibleContext().getAccessibleName();
Container p=c.getParent();
//log.debug("remove button %s from %s",accn,p.getClass().getName());
c.getParent().remove(c);
}
else if (c instanceof Container){
//log.debug("processing components of %s",c.getClass().getName());
Component[] comps = ((Container)c).getComponents();
for(int i = 0; i<comps.length; ++i)
removeButtons(comps[i]);
}
}

Categories