Selecting / highlighting text in a JTextArea belonging to a JOptionPane - java

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);
}

Related

How to Display Message When i left JTextField in java

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();
}
}

unable to close JOptionPane properly in chain order

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.

Adding a panel from a method to a frame

I didn't really know how else to phrase that but essentially:
-I have a few separate "pieces" that I am trying to add onto a master frame; to keep the code from getting unwieldy I have each "piece" be its own class.
-I'm getting stuck on adding the panells onto the master frame, because the classes themselves aren't panels, rather the method of the class creates the panel, which creates issues that I don't know how to solve.
PIECE (works on its own when I have it make a dialog instead of be a panel):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PieceThing3 extends JPanel //<switched from JDialog
{
//set up variables here
private ActionListener pieceAction = new ActionListener()
{
public void actionPerformed (ActionEvent ae)
{
// Action Listener (this also works)
}
};
private void createPiece()
{
//setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//setLocationByPlatform(true);
// the above are commented out when I switch from dialog to panel
JPanel contentPane = new JPanel();
//something that uses pieceAction is here
//two buttons, b and s, with action listeners are here
contentPane.add(b);
contentPane.add(s);
add(contentPane);
//pack();
//again, commented out to switch from dialog
setVisible(true);
System.out.println("hi I'm done");
//just to check and make sure it's done
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PieceThing3().createPiece();
}
});
}
}
Sorry that is very vague, but the intricacies are not as important as the general idea - it works perfectly when I have it create its own dialog box, but now I am trying to get it to make a panel within a master code, below:
MASTER:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CollectGUI extends JFrame{
private void createDialog(){
this.setSize(2000,1000);
this.setLocation(0,0);
this.setTitle("TITLE");
PieceThing3 pt = new PieceThing3();
//HERE, if I do pt.main(null); while it is in "dialog mode" (rather than panel) it pops up a dialog box and everything is hunky dory. But I don't know how to get it to add the method as a panel.
this.add(pt.main(null));
//this gives an error
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new CollectGUI().createDialog();
}
}
As I said in the comments, if I just do pt.main(null) when pt is set to make a dialog, it does it, but if I try to add pt.main(null) as a panel it throws an error. Can anybody give me some insight on how to add a method of a class rather than a class? I'm pretty stumped.
THANK YOU!!
You are definitely on the right track working to maintain separation of concerns and implement your gui in a number of distinct components. Try something like this:
Panel1
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Panel1 extends JPanel {
public Panel1() {
this.add(new JLabel("This is panel 1"));
}
}
Panel2
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Panel2 extends JPanel {
public Panel2() {
this.add(new JLabel("This is panel 2"));
}
}
JFrame
import java.awt.BorderLayout;
import javax.swing.JFrame;
import org.yaorma.example.jframe.panel.panel1.Panel1;
import org.yaorma.example.jframe.panel.panel2.Panel2;
public class ExampleJFrame extends JFrame {
public ExampleJFrame() {
super("Example JFrame Application");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setLayout(new BorderLayout());
Panel1 pan1 = new Panel1();
Panel2 pan2 = new Panel2();
this.add(pan1, BorderLayout.NORTH);
this.add(pan2, BorderLayout.SOUTH);
this.setVisible(true);
}
}
main:
public class ExampleApplication {
public static void main(String[] args) throws Exception {
new ExampleJFrame();
}
}
EDIT:
Here's a Panel1 with a little more content.
import java.awt.BorderLayout;
import java.awt.Container;
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.JPanel;
import org.yaorma.example.action.sayhello.SayHelloAction;
public class Panel1 extends JPanel {
//
// instance variables
//
private JButton pressMeButton;
//
// constructor
//
public Panel1() {
this.setLayout(new BorderLayout());
this.add(new JLabel("This is panel 1"), BorderLayout.NORTH);
this.initPressMeButton();
}
//
// button
//
private void initPressMeButton() {
this.pressMeButton = new JButton("Press Me");
this.pressMeButton.addActionListener(new PressMeButtonActionListener());
this.add(pressMeButton, BorderLayout.SOUTH);
}
//
// method to get the parent jframe
//
private JFrame getParentJFrame() {
Container con = this;
while(con != null) {
con = con.getParent();
if(con instanceof JFrame) {
return (JFrame)con;
}
}
return null;
}
//
// action listener for Press Me button
//
private class PressMeButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFrame jFrame = getParentJFrame();
SayHelloAction action = new SayHelloAction(jFrame);
action.execute();
}
}
}
Action called by button:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SayHelloAction {
private JFrame owner;
public SayHelloAction(JFrame owner) {
this.owner = owner;
}
public void execute() {
JOptionPane.showMessageDialog(owner, "Hello World");
}
}

Needing to return value from user input

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)

How to attach a window to another window

Please have a look at the following code
Main.Java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame
{
private JButton ok;
public Main()
{
ok = new JButton("OK");
ok.addActionListener(new ButtonAction());
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(ok);
getContentPane().add(panel,"South");
this.setVisible(true);
this.setSize(new Dimension(200,200));
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Main();
}
catch(Exception e)
{
}
}
private class ButtonAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Dialog d = new Dialog();
d.setVisible(true);
}
}
}
Dialog.java
import java.awt.Event;
import java.awt.*;
import javax.swing.*;
public class Dialog extends JDialog
{
private JButton done;
public Dialog()
{
done = new JButton("Done");
this.add(done);
this.setSize(new Dimension(400,200));
}
}
In here, I want to "attach" the Dialog form to the main form. Which means, when I click the OK button in Main.Java, Dialog form will get attached to the right side of the main form. So, when I move the main form, the dialog also get moved. However, dialog form should be independent, which means, when I click "x" button in dialog form, only that form exists, not the main form.
How can I attach this dialog form, to the right side of the main form, when the button is clicked? Please help!
The answer is not MouseListener, but it is ComponentListener. I managed to do it with using that listener's "componentMoved()" method.
Main.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame implements ComponentListener, ActionListener
{
private JButton ok;
private Dialog dialog;
public Main()
{
ok = new JButton("OK");
ok.addActionListener(this);
dialog = new Dialog();
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(ok);
getContentPane().add(panel,"South");
this.addComponentListener(this);
this.setVisible(true);
this.setSize(new Dimension(200,200));
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Main();
}
catch(Exception e){}
}
public void actionPerformed(ActionEvent ae)
{
dialog.setVisible(true);
}
#Override
public void componentHidden(ComponentEvent arg0) {}
#Override
public void componentMoved(ComponentEvent arg0)
{
int x = this.getX() + this.getWidth();
int y = this.getY();
dialog.setDialogLocation(x, y);
}
#Override
public void componentResized(ComponentEvent arg0) {}
#Override
public void componentShown(ComponentEvent arg0) {}
}
Dialog.java
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JDialog;
public class Dialog extends JDialog
{
private JButton done;
public Dialog()
{
done = new JButton("Done");
this.add(done);
this.setSize(new Dimension(400,200));
}
public void setDialogLocation(int x, int y)
{
this.setLocation(x, y);
}
}
I'm not aware of any built-in function that you can just say "dialog.moveWithThisOtherWindow(otherWindow)" or some such and it just happens. You would have to write code to do this yourself.
Create a mouse listener or mouse adapter on the parent form. In the "mouse moved" event in the mouse listener, move the child form. Of course the parent would have to have a handle to the child. Depending how you create the windows, you may need some sort of "register" function that the child can call to identify himself to the parent.

Categories

Resources