Dialog that returns an Object - java

Is it possible to create a JDialog in swing that would return an object when OK button is clicked?
For example the Dialog box has text fields that have components that make up an adress ( street name, country etc.)
When the OK button is clicked an Address object is returned.
Why I thought this to be possible was because of this. But what I want is something like I mentioned above.
Any pointers on how to get this done would be very helpful.

Like the previous people suggested: JOptionPane can help you do what you want. But if you're determined to implement this from scratch, here is an SSCCE that does exactly what you want (well, it returns a String, but it can be easily modified to suit your needs):
import java.awt.Font;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class MyDialog
{
private JFrame parent;
private JDialog dialog;
private String information;
MyDialog (JFrame parent)
{
this.parent = parent;
}
private JPanel createEditBox ()
{
JPanel panel = new JPanel ();
JLabel dialogtitlelabel = new JLabel ("Enter Info");
panel.add (dialogtitlelabel);
dialogtitlelabel.setFont (new Font ("Arial", Font.BOLD, 20));
final JTextArea informationtxt = new JTextArea ();
informationtxt.setEditable (true);
informationtxt.setLineWrap (true);
informationtxt.setWrapStyleWord (true);
JScrollPane jsp = new JScrollPane (informationtxt);
jsp.setVerticalScrollBarPolicy (ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
jsp.setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setPreferredSize (new Dimension (180, 120));
panel.add (jsp);
JButton btnok = new JButton ("OK");
panel.add (btnok);
JButton btncancel = new JButton ("Cancel");
panel.add (btncancel);
btnok.addActionListener (new ActionListener ()
{
#Override public void actionPerformed (ActionEvent a)
{
if (informationtxt.getText () == null || informationtxt.getText ().isEmpty ())
{
return;
}
information = informationtxt.getText ();
dialog.dispose ();
}
});
btncancel.addActionListener (new ActionListener ()
{
#Override public void actionPerformed (ActionEvent a)
{
dialog.dispose ();
}
});
return panel;
}
void display ()
{
final int DWIDTH = 200;
final int DHEIGHT = 240;
dialog = new JDialog (parent, "Information", true);
dialog.setSize (DWIDTH, DHEIGHT);
dialog.setResizable (false);
dialog.setDefaultCloseOperation (JDialog.DISPOSE_ON_CLOSE);
dialog.setContentPane (createEditBox ());
dialog.setLocationRelativeTo (parent);
dialog.setVisible (true);
}
String getInformation ()
{
return information;
}
}
public class ReturningDialogTest
{
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
final JFrame frame = new JFrame ();
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
final JPanel panel = new JPanel ();
JButton btn = new JButton ("show dialog");
panel.add (btn);
final JLabel lab = new JLabel ("");
panel.add (lab);
frame.add (panel);
btn.addActionListener (new ActionListener ()
{
public void actionPerformed (ActionEvent e)
{
MyDialog diag = new MyDialog (frame);
diag.display ();
String info = diag.getInformation ();
lab.setText (info);
frame.pack ();
}
});
frame.setLocationRelativeTo (null);
frame.pack ();
frame.setVisible (true);
}
});
}
}
What you enter in that text-area is displayed on the main window when you press OK, just to prove it works :) .

Put GUI components to hold the address, into a panel. Provide the panel to the dialog. Once the dialog is closed, read the values from the components on the panel to construct the Address object.

Is it possible to create a JDialog in swing that would return an object when OK button is clicked?
this is reason why JOptionPane exist
When the OK button is clicked an Address object is returned.
please see JOptionPane Features

Related

Can't get my ComboBox and Button to work. Problem implementing the box with the button

I am trying to get a JComboBox and a JButton to work in tandem by changing the background colour of the JPanel. I am not sure where I am messing up so any help would be much appreciated!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Lab6Part2 extends JFrame implements ActionListener {
private String[] BackgroundColours = new String[]{"Green", "Red", "Blue"};
private JPanel panel = new JPanel ();
private JComboBox<String> colourSelector = new JComboBox<> (BackgroundColours);
private JButton changeColour = new JButton ("Change Colour");
private Lab6Part2() {
panel.add (colourSelector);
panel.add (changeColour);
getContentPane ().add (panel);
setSize (450, 450);
setResizable (false);
setResizable (false);
setVisible (true);
}
public static void main(String[] args) {
Lab6Part2 GUI = new Lab6Part2 ();
GUI.setTitle ("JComboBox and JButton");
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand ().equals ("changeColour")){
if (colourSelector.getSelectedIndex () == 0) {
panel.setBackground (Color.GREEN);
}
else if (colourSelector.getSelectedIndex () == 1) {
panel.setBackground (Color.RED);
}
else if (colourSelector.getSelectedIndex () == 2) {
panel.setBackground (Color.BLUE);
}
}
}
}
I am trying to get a JComboBox and a JButton to work in tandem by changing the background colour of the JPanel
A couple of problems:
You never add the ActionListener to the button.
changeColour.addActionListener(this);
Even if you add the ActionListener the if condition is wrong:
private JButton changeColour = new JButton ("Change Colour");
if (e.getActionCommand ().equals ("changeColour")){
Did you verify the if condition is ever true?
The "actionCommand" defaults to the text of the button.
Also, why do you you even use the button. Just add the ActionListener to the combo box so the background changes when you select the item instead of forcing the user to also click the button.
Is there some reason you want to implement ActionListener? I usually find it easier to associate one button with its action.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame {
private String[] BackgroundColours = new String[]{"Green", "Red", "Blue"};
private JPanel panel = new JPanel ();
private JComboBox<String> colourSelector = new JComboBox<String>(BackgroundColours);
private JButton changeColour = new JButton("changeColour");
private Test() {
changeColour.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeTheColor();
}
});
panel.add(colourSelector);
panel.add(changeColour);
getContentPane().add(panel);
setSize (450, 450);
setResizable (false);
setResizable (false);
setVisible (true);
}
public static void main(String[] args) {
Test GUI = new Test ();
GUI.setTitle ("JComboBox and JButton");
}
public void changeTheColor() {
if (colourSelector.getSelectedIndex () == 0) {
panel.setBackground (Color.GREEN);
System.out.println("g");
}
else if (colourSelector.getSelectedIndex () == 1) {
panel.setBackground (Color.RED);
}
else if (colourSelector.getSelectedIndex () == 2) {
panel.setBackground (Color.BLUE);
}
}
}

Java syntax for separating action listeners

Please help me out to separate these ActionListeners in a periodic table that I am attempting to complete. When I execute the program and click on 'H', it opens all the other elements and when the others are clicked, it does not work. So I need a way to separate these using any method...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PeriodicTable
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Elements");
frame.setVisible(true);
frame.setSize(1000,1500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("H");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("He");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Li");
panel.add(button3);
button3.addActionListener (new Action2());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("H");
frame2.setVisible(true);
frame2.setSize(1000,1500);
JLabel label = new JLabel("Hydrogen");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("He");
frame3.setVisible(true);
frame3.setSize(1000,1500);
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Li");
frame4.setVisible(true);
frame4.setSize(1000,1500);
JLabel label = new JLabel("Lithium");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
}
Thanks in advance.
(note: only the first 3 elements are coded for...)
When I execute the program and click on 'H', it opens all other elements
Only one frame opens for me.
and when the others are clicked, it does not work.
Each button opens a single frame for me.
However, button 3 opens the wrong frame because you add the wrong listener to the button:
//button3.addActionListener (new Action2());
button3.addActionListener (new Action3());
Other issues:
You should add the components to the frame BEFORE making the frame visible.
Don't hardcode screen sizes, you never know what size screen other users will be using
So the order of your code might be something like:
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame("He");
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
And of course you really don't want to create dozens of separate ActionListeners. You want to make the listener more generic so it can be shared.
Something like:
static class Action implements ActionListener
{
public Action(String element, String description)
{
this.element = element;
this.description = description;
}
public void actionPerformed (ActionEvent e)
{
JLabel label = new JLabel(description);
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame(element);
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
Then when you create the listener you use:
button3.addActionListener (new Action("HE", "Helium"));

Clear current FocusOwner (jTextfield)

Developing an application in swing, just a little query :-
I want to clear the current focus owner textfield using a button. It is possible to determine whether a textfield is the current focus owner or not using isFocusOwner() but how to clear the textfield which is currently on focus?
Thanks!!!
You might be able use a TextAction. A TextAction has access to the last text component that had focus. So then in the text action you just clear the text in the component. All the logic is fully contained in the one place.
Here is an example that demonstrates the concept of using a TextAction. In this case the number represented by the button is appended to the text field with focus:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class NumpadPanel extends JPanel
{
public NumpadPanel()
{
setLayout( new BorderLayout() );
JTextField textField1 = new JTextField(4);
JTextField textField2 = new JTextField(2);
JTextField textField3 = new JTextField(2);
JPanel panel = new JPanel();
panel.add( textField1 );
panel.add( textField2 );
panel.add( textField3 );
add(panel, BorderLayout.PAGE_START);
Action numberAction = new TextAction("")
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent textComponent = getFocusedComponent();
if (textComponent != null)
textComponent.replaceSelection(e.getActionCommand());
}
};
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setMargin( new Insets(20, 20, 20, 20) );
button.setFocusable( false );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Numpad Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new NumpadPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
In your case instead of using the replaceSelection() method you would just use the setText() method.
If you want to clear a textfield using the clicking of a button, you have to write the code to clear the textfield in the the ActionListener class's ActionPerformed method. This method is called when the button is pressed. But in order to press the button you have to get the focus from other component to this button. So in the method ActionPerformed you would get false to textField.isFocusOwner().
My suggestion to overcome this problem is:
add focus listeners to these 6 text fields.
declare a variable say lastFocused as type JTextField in initialise it to null in the Class that you are implementing all these.
write the following code to the focusListerners Overridden methods
void focusGained(FocusEvent e){
lastFocused = (JTextField) e.getComponent();
}
void focusLost(FocusEvent e){
lastFocused = null;
}
now in the ActionListener overridden method write the following:
void actionPerformed(ActionEvent e){
if(lastFocused != null){
lastFocused.setText("");
}
}
I feel this should solve your problem.

jbutton changes text of text field

I am simply trying to make an employee clock. I have a keypad of numbers 0-9 and a text field. I want to be able to click the numbers and the numbers will appear on the text field. This seems so easy but I can't find any answers for it.
I'm using netbeans and I created the design of the Jframe in the Design.
I added action events to all of the buttons.
I'm calling each button like Btn0 (the button with 0 on it, Btn1, etc etc.
You need to retrieve the JButton on which ActionEvent is fired and then append the text retrieved from the JButton to the JTextField. Here is the short Demo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class EClock extends JFrame
{
JTextField tf;
public void createAndShowGUI()
{
setTitle("Eclock");
Container c = getContentPane();
tf = new JTextField(10);
JPanel cPanel = new JPanel();
JPanel nPanel = new JPanel();
nPanel.setLayout(new BorderLayout());
nPanel.add(tf);
cPanel.setLayout(new GridLayout(4,4));
for (int i =0 ; i < 10 ; i++)
{
JButton button = new JButton(String.valueOf(i));
cPanel.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
String val = ((JButton)evt.getSource()).getText();
tf.setText(tf.getText()+val);
}
});
}
c.add(cPanel);
c.add(nPanel,BorderLayout.NORTH);
setSize(200,250);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
EClock ec = new EClock();
ec.createAndShowGUI();
}
});
}
}
Add action listener on your button first (double click on button in GUI Designer :) ):
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set text by calling setText() method for your textfield
textfield.setText("Desired text");
}
});
Regards.
Create an Action that can be shared by all the buttons. Something like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ButtonCalculator extends JFrame implements ActionListener
{
private JButton[] buttons;
private JTextField display;
public ButtonCalculator()
{
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( this );
button.setMnemonic( text.charAt(0) );
button.setBorder( new LineBorder(Color.BLACK) );
buttons[i] = button;
buttonPanel.add( button );
}
getContentPane().add(display, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setResizable( false );
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
display.replaceSelection( source.getActionCommand() );
}
public static void main(String[] args)
{
ButtonCalculator frame = new ButtonCalculator();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
I know nothing of netbeans, however, a search on google gave me this
Netbeans GUI Functionality
it seems to have the data needed, give it a read and no doubt you can figure out what needs to be amended for it to suit your purposes

Java: "Add Tab Button" for a JTabbedPane

Is it possible to add a button to a tabbed pane like in firefox.
The plus-button is what I want.
Thanks
I think you should be able to manage it by building your own JTabbedPaneUI and setting it on the JTabbedPane using setUI.
Your ComponentUI has methods to get a hold of the accessible children. If you specify a JButton and a JLabel then you may be in business.
I haven't attempted this myself though. This is "at your own risk" :)
You can try this:
public static void main (String[] args) {
JFrame parent = new JFrame ();
final JTabbedPane pane = new JTabbedPane ();
pane.addTab ("test", null);
FlowLayout f = new FlowLayout (FlowLayout.CENTER, 5, 0);
// Make a small JPanel with the layout and make it non-opaque
JPanel pnlTab = new JPanel (f);
pnlTab.setOpaque (false);
// Create a JButton for adding the tabs
JButton addTab = new JButton ("+");
addTab.setOpaque (false); //
addTab.setBorder (null);
addTab.setContentAreaFilled (false);
addTab.setFocusPainted (false);
addTab.setFocusable (false);
pnlTab.add (addTab);
pane.setTabComponentAt (pane.getTabCount () - 1, pnlTab);
ActionListener listener = new ActionListener () {
#Override
public void actionPerformed (ActionEvent e) {
String title = "Tab " + String.valueOf (pane.getTabCount () - 1);
pane.addTab (title, new JLabel (title));
}
};
addTab.setFocusable (false);
addTab.addActionListener (listener);
pane.setVisible (true);
parent.add (pane);
parent.setSize (new Dimension (400, 200));
parent.setVisible (true);
}
Write Following Code in Default Constructor Of Class
JPanel panel = new JPanel();
tabbedPane.addTab("Welcome", null, panel, null);
tabbedPane.addTab(" + ", null, panel1, null);
tabbedPane.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent evt)
{
JTabbedPane tabbedPane = (JTabbedPane)evt.getSource();
if(tabbedPane.getSelectedIndex() == tabbedPane.indexOfTab(" + "))
{
createTab();
}
}
});
And Create Method to declare and initialized int tab2 = 2; at Starting of main class. Its Worked.
private void createTab()
{
tabbedPane.addTab("New Tab",new Panel());
tabbedPane.addTab(" + ",null,panel1,null);
tabbedPane.setSelectedIndex(tab2);
tab2++;
}
I have tried several solutions and came with this one:
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class TestTab {
public static void main(String[] args) {
JFrame parent = new JFrame();
final JTabbedPane tabEntity = new JTabbedPane();
tabEntity.addTab("Details", null, new JScrollPane());
tabEntity.addTab("Context", null, new JScrollPane());
tabEntity.addTab("", null, new JScrollPane());
addButtonToTab(tabEntity);
parent.add(tabEntity);
parent.setSize(new Dimension(400, 200));
parent.setVisible(true);
}
public static void addButtonToTab(final JTabbedPane tabEntity) {
tabEntity.setTabComponentAt(tabEntity.getTabCount() - 1, new JButton(
"+"));
}
}
So you have:

Categories

Resources