How to select a component on jframe? - jframe

How to select a JTextArea on JButton click?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.setEditable(true);
jTextArea1.setForeground(Color.BLACK);
//*******************************************************
jframe.setselected(jTextArea1); // I need such function!
//*******************************************************
}

By select I assume you mean transfer focus to the JTextArea. If so you can request focus of you text area with the following.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.setEditable(true);
jTextArea1.setForeground(Color.BLACK);
/*******************************************************
jTextArea1.requestFocusInWindow();
/*******************************************************
}

Related

Focuslost event on Jcombobox in netbeans

I am trying to have a bind a focuslost event on my combobox but it's not happening.
Here is my code-:
jComboBox1.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e){
}
public void focusLost(FocusEvent e){
JOptionPane.showConfirmDialog(null,"focuslost");
}
});
I also tried this-:
JComboBox default editor has an internal class BasicComboBoxEditor$BorderlessTextField that is the component that gets and loses focus.
It can be accessed simply by-:
Component component = comboBox.getEditor().getEditorComponent();
if (component instanceof JTextField)
JTextField borderlesstextfield = (JTextField) borderless;
But i am getting error on this line-
JTextField borderlesstextfield = (JTextField) borderless;
I am new to netbeans. Kindly guide me.Thank you in advance.
I tested this(Adding the JComboBox inside a JPanel ). If there are more elements inside the panel the focuslost is triggered when pressing tab or clicking on another element.
Considering that you do not have any other elements or you want the focus lost event to trigger also when you click somewhere on the window:
Keep your focus listener as is and add the following after the auto-generated initComponents():
jPanel1.setFocusable(true);
jPanel1.setRequestFocusEnabled(true);
jPanel1.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
jPanel1.requestFocusInWindow();
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
});

Why do I get MouseDown events from a position outside of the control's boundary?

I have a Composite containing a number of Text controls. I have attached MouseListeners to each control.
What surprises me is that sometimes, when I click on a control, I get a MouseDown event from its neighbour. The Event position is outside of the control's boundary and I get no event from the other control which I thought I had clicked on.
What can cause this to happen?
SNIPPET
Run. Press Esc to close the MessageBox. Click in field BBBB. Press Esc to close MessageBox. Click in field AAAA. The event is generated from field BBBB.
public class Test
{
public class MyListener implements MouseListener, FocusListener
{
private boolean active;
#Override
public void focusGained(FocusEvent e)
{
System.out.println(e);
message((Text) e.widget, "FocusGained");
}
#Override
public void focusLost(FocusEvent e)
{
System.out.println(e);
}
#Override
public void mouseDoubleClick(MouseEvent e)
{
}
#Override
public void mouseDown(MouseEvent e)
{
System.out.println(e);
}
private void message(final Text t, final String m)
{
if (active == false)
{
active = true;
MessageBox mb = new MessageBox(t.getShell());
mb.setText(m);
mb.setMessage(t.getMessage() + "\n\n" + m);
mb.open();
active = false;
}
}
#Override
public void mouseUp(MouseEvent e)
{
System.out.println(e);
message((Text) e.widget, e.toString());
}
}
private MyListener listener = null;
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
new Test(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public Test(Composite parent)
{
listener = new MyListener();
create(parent);
}
private void create(Composite parent)
{
parent.setLayout(new GridLayout(2, true));
createText(parent, "AAAA");
createText(parent, "BBBB");
parent.layout(true);
}
private Text createText(Composite parent, String message)
{
Text t = new Text(parent, SWT.NONE);
t.setMessage(message);
GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
t.setLayoutData(gd);
t.addFocusListener(listener);
t.addMouseListener(listener);
return t;
}
}
This is indeed strange. When traversing from B to A, the MouseUp event is marked as sent from field B.
If you replace the MessageBox with something non-interrupting i.e. System.out, the mouse event senders are the right ones.
To me, this seems more of a theoretical corner case. Decent applications would not interrupt the users field traversal with a modal window. However, if this is relevant for your, I'd report a bug to SWT.
I managed to get this working by de-coupling the pop-up window from the events. The message method now looks like this:
private void message(final Text t, final String m)
{
//NB active is declared as 'volatile'
if (active == false)
{
active = true;
t.getDisplay().asyncExec(new Runnable()
{
#Override
public void run()
{
MessageBox mb = new MessageBox(t.getShell());
mb.setText(m);
mb.setMessage(t.getMessage() + "\n\n" + m);
mb.open();
active = false;
}
});
}
else
{
System.out.println("Already active: " + t.getMessage());
}
}
This seems to give the events the opportunity to continue uninterrupted by the pop-up window. The pop-up will be activated a short while later. So far it works ok.

Drag and drop from javaFX scene to windows explorer

Is there any way to Drag and drop from javaFX scene to windows explorer?
Yes there is
You should use the onDragDetected function to start your dragEvent and the onDragDone function for doing whatever you want after finishing the drag & drop.
Here an example:
final Text source = new Text(50, 100, "DRAG ME");
source.setOnDragDetected(new EventHandler <MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture*/
System.out.println("onDragDetected");
/* allow any transfer mode */
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
event.consume();
}
source.setOnDragDone(new EventHandler <DragEvent>() {
public void handle(DragEvent event) {
/* the drag-and-drop gesture ended */
System.out.println("onDragDone");
/* if the data was successfully moved, clear it */
if (event.getTransferMode() == TransferMode.MOVE) {
source.setText("");
}
event.consume();
}
});

Generating check boxes dynamically, Netbeans

I am developing a desktop application in which I want Admin have option to delete users, for which I planned that whenever Admin clicks on 'delete users' button a new tab will open in which check boxes with the name of all existing users in my database should appear(so that he can delete multiple users simultaneously); so basically I need to generate dynamic check boxes as per my database.
I am using Netbeans 7.0.1, jdk 1.6, sqlite3.
After searching on google I got two links which match to my problem:
http://www.coderanch.com/t/345949/GUI/java/create-dynamic-checkboxes#2805277
Creating dcheckbox dynamically in Java-NetBeans
I have tried to follow the code from above first link but it does not working for me properly. What I does is just created new JFrame in netbeans and called a method inside constructor which create checkboxes as per needed, method's code is as below:
public class Work extends javax.swing.JFrame {
/** Creates new form Work */
public Work() {
initComponents();
checks = new java.util.ArrayList<>();
createCheckboxes();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void createCheckboxes(){
panel = new javax.swing.JPanel();
this.add(panel);
for(int i = 0; i<4; i++){
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
panel.add(box);
checks.add(box);
panel.revalidate();
panel.repaint();
}
panel.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
private java.util.ArrayList <javax.swing.JCheckBox> checks;
private javax.swing.JPanel panel;
}
The output is just a blank frame. Please help me to know where I am wrong!!
And yes this code is not connected to database yet, once it will work then I can modify it to work with database.
Also is their any other betterway to accomplish my task or am on right path?`
I think it might help if u call the following function whenever to wanna create a new checkbox..
public class CheckBox extends JFrame{
//private static final long serialVersionUID = 1L;
public CheckBox() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout(FlowLayout.TRAILING, 50, 20)); //(default) centered alignment and a default 5-unit horizontal and vertical gap.
JCheckBox checkBox1 = new JCheckBox("Checkbox 1");
checkBox1.setSelected(true);
JCheckBox checkBox2 = new JCheckBox("Checkbox 2", true);
JCheckBox checkBox3 = new JCheckBox("Checkbox 3");
// add checkboxes to frame
add(checkBox1);
add(checkBox2);
add(checkBox3);
}
private static void createAndShowGUI() {
//Create and set up the window.
//JFrame frame = new CreateCheckedUncheckedJCheckBox();
CheckBox cb = new CheckBox();
//Display the window.
cb.pack();
cb.setVisible(true);
cb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You add the new checkboxes as if your frame was using some simple layout such as FlowLayout, but it is not - it is using GroupLayout - see the generated initComponents() method.
If you want to handle ALL components in the frame dynamically, you can do this (it is better to create an empty class file and then paste the code below; do not ask NB to create a JFrame as it would again create a form to be designed in the visual designer; if you still do it then r-click it and change the layout to something simpler):
public class Work extends javax.swing.JFrame {
private java.util.List <javax.swing.JCheckBox> checks = new java.util.ArrayList<>();;
public Work() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new java.awt.FlowLayout()); // simply put the components next to each other
createCheckboxes();
}
private void createCheckboxes(){
for(int i=0; i<4; i++) {
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
add(box);
checks.add(box);
}
pack(); // this will tell the JFrame's panel to layout all the components
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
}
Or you can design part of your frame with the visual designer and then add the checkboxes. In that case add an empty panel in the designer, set the panel's layout to something like flow or grid layout and then add the checkboxes to that panel from your code in the same way as above.
You validate needs to be called only if the panel/frame is already visible. Calling pack works even then, but might change the size of the frame. Also validating can be done after all components were added not after adding each one.
To add check boxes or any other component dynamically in Netbeans JFrame one need to manage Layout Managers, by default netbeans frames use Free Design Layout, follow steps below:
Create blank JFrame -->Add Jpanel to it-->right click to the panel, select setLayout and change it to GridLayout.
Now we are free to add ant components on this panel.
Also don't forgate to add revalidate() and repaint() methods.
This worked for me.

gwt get array button value

My gwt project have flexTable show data of image and button on each row and coll.
But my button won't work properly. this is my current code:
private Button[] b = new Button[]{new Button("a"),...,new Button("j")};
private int z=0;
...
public void UpdateTabelGallery(JsArray str){
for(int i=0; i str.length(); i++){
b[i].setText(str.gettitle());
UpdateTabelGallery(str.get(i));
}
}
public void UpdateTabelGallery(GalleryData str){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[z] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[z].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan to show the clicked button text" + b[z].getText());
}
});
z++;
}
I'm still confuse where I should put my button handler. With this current code seems the clickhandler didn't work inside a looping. And if I put it outside loop its not working because I need to know which button clicked. I need to get my index button.but how? Is there any option than array button?
thanks
I was using this method me too, then I've created a new Button with an additional argument.
When I add the ButtonArg I set also the argument:
Panel.add(new ButtonArg("B1", i));
...
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
ButtonArg btn=(ButtonArg) e.getSource();
Window.alert("Button Text="+btn.getArgument());
}
}
public class ButtonArg extends Button {
int argument;
public ButtonArg(String html, int arg) {
super(html);
setArgument(arg);
}
public int getArgument() {
return argument;
}
public void setArgument(int argument) {
this.argument = argument;
}
[...]
The problem is that you refer to 'z' in your click handler, but the value of z changes, so that when your click handler is actually called the value of z is wrong.
You need a local final variable in UpdateTabelGallery which you assign the current value of z to to allow it to be captured by the handler you create. Even better, get rid of z entirely and pass i to UpdateTableGallery:
public void updateTableGallery(GalleryData str, final int i){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[i].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan't to show the clicked button text" + b[i].getText());
}
});
}
But what do you expect:
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
to do? Aside from the incorrect HTML syntax, I don't think adding ypur button to the string will work.
I know this is old, but it didn't look answered and I was looking to do the same thing. Here's one solution:
public void onModuleLoad() {
Button[] b=new Button[26];
RootPanel rp=RootPanel.get("body");
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
Button btn=(Button) e.getSource();
Window.alert("Button Text="+btn.getText());
}
}
MyHandler handler = new MyHandler();
for(int i=0;i<26;i++) {
b[i] = new Button(String.valueOf((char)(65+i)));
b[i].addStyleName("sendButton");
rp.add(b[i]);
b[i].addClickHandler(handler);
}
SimplePanel sPanel = new SimplePanel();
}