Actually i'm writing code. I want to display message dialogue (without pressing any button) when I left my JTextField but don't know how to do this. Please Help. Im using NetBeans.
You can use Focus Listener API to achieve that.
On focusLost event, you can show your dialog box.
Example from the documentation:
public void focusLost( FocusEvent e )
{
displayMessage( "Focus lost", e );
}
You can use FocusListener class focusLost() method.
Simple Example:
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ExampleClass {
JFrame MainFrame;
JTextField textField1;
JTextField textField2;
public ExampleClass(){
MainFrame = new JFrame("Example");
MainFrame.setLayout(new FlowLayout());
textField1 = new JTextField(10);
textFieldFocus();
textField2 = new JTextField("Dummy text");
MainFrame.add(textField1);
MainFrame.add(textField2);
MainFrame.pack();
MainFrame.setVisible(true);
}
private void textFieldFocus() {
textField1.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
JOptionPane.showMessageDialog(null, "Done!");
}
#Override
public void focusGained(FocusEvent e) {}
});
}
public static void main(String[] args) {
new ExampleClass();
}
}
Related
I am displaying a JOptionPane suppose A on a button click from JFrame, and again displaying another JOptionPane suppose B on a button click from JOptionPane A, and I have a button on JOptionPane B suppoce button1, on the click event of button1, I am using code JOptionPane.getRootFrame().dispose() for closing the JOptionPane B, but it closes both A and B, please help me how can close only B but not A.
here is my sample code
i want second JOptionPane must be open
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SampleCode extends JFrame {
public SampleCode() {
setSize(new Dimension(500, 500));
setLocation(450, 150);
but1 = new JButton("Click me");
add(but1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
but1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
but1Function();
}
});
}
public static void main(String args[]) {
new SampleCode();
}
void but1Function() {
JPanel panel1 = new JPanel();
JButton but2 = new JButton("Open new dialog");
panel1.add(but2);
but2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel pan2 = new JPanel();
JButton but3 = new JButton("click me to close");
pan2.add(but3);
but3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.getRootFrame().dispose();
}
});
JOptionPane.showMessageDialog(null, pan2);
}
});
JOptionPane jp = new JOptionPane(panel1, JOptionPane.CLOSED_OPTION,
JOptionPane.DEFAULT_OPTION, null, new Object[] {}, null);
JDialog dialog = jp.createDialog(null, "This one must be remain open");
dialog.setLocation(500, 200);
dialog.setSize(new Dimension(345, 200));
dialog.setVisible(true);
}
JButton but1;
}
You don't want to get the root frame nor dispose of it. You want to get the window that is displaying the JOptionPane, a Window that should be a modal JDialog. So instead, use SwingUtilities.getWindowAncestor(someComponentInJOptionPane), and call dispose() on that Window if you want to programmatically dispose of your JOPtionPane.
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class OptionPaneFun {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#SuppressWarnings("serial")
public void run() {
final JPanel panel1 = new JPanel();
panel1.add(new JButton(new AbstractAction("Show new option pane") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e1) {
final JPanel panel2= new JPanel();
panel2.add(new JButton(new AbstractAction("Dispose of this option pane") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_D);
}
#Override
public void actionPerformed(ActionEvent e2) {
Component comp = (Component) e2.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
if (win != null) {
win.dispose();
}
}
}));
JOptionPane.showMessageDialog(panel1, panel2);
}
}));
JOptionPane.showMessageDialog(null, panel1);
}
});
}
}
The static method "getRootFrame()" returns your root frame which is the only one and it's the same for both your components (A and B). What you need to do - you have to put two frames in your root frame (call them frameA and frameB) and put paneA to frameA and paneB to frameB. Instead of calling this static method just invoke frameB.dispose() on reference frameB which you already have.
Try to add
panel.validiate();
After the dispose command. I had the same problem once and it helped a lot when I used this trick.
Basically when you add this command, it is telling the frame to validate or actually do it.
Read the oracle docs for more info.
My problem is the following: In my application the user clicks a button which brings up a dialog box (a custom jOptionPane). This dialog contains a JTextArea in which the user will type a response, which will then be processed by the application, however I would like this JTextArea (which will hold the user's input and currently contains example text like "Write your answer here") to be automatically highlighted.
I can do this normally, by calling requestFocusInWindow() followed by selectAll() on the JTextArea however there seems to be a problem when this is done using a JOptionPane which I'm guessing is to do with the fact that the focus cannot shift to the JTextArea successfully.
I've made a SSCCE to demonstrate this clearly, and hopefully get an answer from one of you guys as to how I can make this possible. Thanks in advance!
Class 1/2 : Main
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main extends JFrame{
public static void main(String[] args) {
Main main = new Main();
main.go();
}
private void go() {
JPanel background = new JPanel();
JPanel mainPanel = new ExtraPanel();
((ExtraPanel) mainPanel).setupPanel();
JButton testButton = new JButton("Test the jOptionPane");
testButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
optionPaneTest();
}
});
background.add(mainPanel);
background.add(testButton);
getContentPane().add(background);
pack();
setVisible(true);
}
private void optionPaneTest() {
JPanel testPanel = new ExtraPanel();
((ExtraPanel) testPanel).setupPanel();
int result = JOptionPane.showConfirmDialog(null, testPanel,
"This is a test", JOptionPane.OK_CANCEL_OPTION);
}
}
----------------------------------------------------------------------------- Class 2/2 : ExtraPanel
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ExtraPanel extends JPanel{
public void setupPanel() {
JTextArea textArea = new JTextArea();
textArea.setText("Write your response here");
textArea.requestFocusInWindow();
textArea.selectAll();
add(textArea);
}
}
Just add
textArea.getCaret().setSelectionVisible(true)
After textArea.selectAll();
If you want focus in the TextArea so that the user can immediately start typing, you can trigger the selection using the ancestor added event.
public void setupPanel() {
final JTextArea textArea = new JTextArea();
textArea.setText("Write your response here");
textArea.addAncestorListener(new AncestorListener() {
public void ancestorRemoved(AncestorEvent event) { }
public void ancestorMoved(AncestorEvent event) { }
public void ancestorAdded(AncestorEvent event) {
if (event.getSource() == textArea) {
textArea.selectAll();
textArea.requestFocusInWindow();
}
}
});
add(textArea);
}
a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
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.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)
I minimized my program to include only the problem and I tried to code exactly as I understood from many examples. When I used the ActionListener, I get problem solved. But I wonder why using ItemListener, checkbox does not operate correctly.
If I run my program without ItemListener, it works correctly. With this ItemListener, checkBox doesn't change state.
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class omaJFrame extends JFrame{
private JCheckBox checkBox1;
public omaJFrame() {
super("Window Title");
TheHandler handler = new TheHandler();
setLayout(new FlowLayout());
checkBox1 = new JCheckBox("Checkbox 1");
add(checkBox1);
checkBox1.addItemListener(handler);
}
private class TheHandler implements ItemListener {
String output = "";
public void itemStateChanged(ItemEvent event) {
if (event.getItem()==checkBox1)
output = String.format("%s", checkBox1.isSelected());
JOptionPane.showMessageDialog(null, output);
}
}
}
import javax.swing.JFrame;
public class EventHandlerMain {
public static void main(String[] args) {
omaJFrame window = new omaJFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(350,200);
window.setVisible(true);
}
}
Works for me. Note also that Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class OmaJFrame extends JFrame {
private JCheckBox checkBox1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
OmaJFrame f = new OmaJFrame();
}
});
}
public OmaJFrame() {
super("Window Title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
TheHandler handler = new TheHandler();
setLayout(new FlowLayout());
checkBox1 = new JCheckBox("Checkbox 1");
add(checkBox1);
checkBox1.addItemListener(handler);
pack();
setLocationByPlatform(true);
setVisible(true);
}
private class TheHandler implements ItemListener {
String output = "";
#Override
public void itemStateChanged(ItemEvent event) {
if (event.getItem() == checkBox1) {
output = String.format("%s", checkBox1.isSelected());
}
JOptionPane.showMessageDialog(null, output);
}
}
}
i am developing an Virtual keyboard module.
KeyBoardModule.java
KeyBoardModule kbm = new KeyBoardModule("small", false, null);
is called when in Other jForm(MainFrame.java) is clickevent on textbox
then I get new JFrame with keyboard(its like popup window),
When JButton enter is pressed it saves data to variable textFieldValue from textarea of KeyBoardModule.
than frame.disponse()
the main class calls MainFrame and mainframe call on click the keyboard, and i need to return value from keyboard to mainframe..
without using actionlistener(for enter button) in mainframe
To return a value directly from GUI1 to another GUI2 , GUI1 must have a reference to the object of GUI2. So that whenever you want to pass any message from GUI1 to GUI2 , you could do it by calling the appropriate method of GUI2. For example consider the code given below. While creating the object of InputBoard in MainFrame we pass the current object of MainFrame to InputBoard's constructor so that InputBoard could pass its input to MainFrame GUI using appropriate public method of MainFrame. Here MainFrame opens the InputBoard frame on click of button. And whenever some input is passed to the JTextField in InputBoard it is reflected within the JTextArea of MainFrame.
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
class MainFrame extends JFrame implements ActionListener
{
private JButton button;
private JTextArea tArea;
private InputBoard inBoard;
public void prepareAndShowGUI()
{
setTitle("Main Frame");
tArea = new JTextArea(10,30);
button = new JButton("Click Me");
inBoard = new InputBoard(this);
inBoard.prepareGUI();
JScrollPane tFieldPane = new JScrollPane(tArea);
tArea.setLineWrap(true);
tArea.setWrapStyleWord(true);
tArea.setEditable(false);
button.addActionListener(this);
getContentPane().add(tFieldPane);
getContentPane().add(button,BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.requestFocus();
}
#Override
public void actionPerformed(ActionEvent evt)
{
if (!inBoard.isVisible())
{
inBoard.setVisible(true);
}
inBoard.toFront();
}
public void setText(final String s)
{
tArea.setText(s);
}
public static void main(String[] st)
{
SwingUtilities.invokeLater( new Runnable()
{
#Override
public void run()
{
MainFrame mf = new MainFrame();
mf.prepareAndShowGUI();
}
});
}
}
class InputBoard extends JFrame implements DocumentListener
{
MainFrame mainFrame ;
JTextField inField;
public InputBoard(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
}
public void prepareGUI()
{
setTitle("Input Board");
inField = new JTextField(40);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(inField);
inField.getDocument().addDocumentListener(this);
setLocationRelativeTo(mainFrame);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
}
#Override
public void changedUpdate(DocumentEvent evt)
{
mainFrame.setText(inField.getText());
}
#Override
public void insertUpdate(DocumentEvent evt)
{
mainFrame.setText(inField.getText());
}
#Override
public void removeUpdate(DocumentEvent evt)
{
mainFrame.setText(inField.getText());
}
}