I am wanting to get a return from a gui instance
The code i run to create the GUI:
JFrame frame = new JFrame();
frame.getContentPane().add(new ChatPopup());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
My GUI (ChatPopUp code is as follows:
public class ChatPopup extends javax.swing.JPanel {
private JButton cancelButton;
private JTextField textFieldchatRoomName;
private JLabel jLabel1;
private JButton okButton;
public ChatPopup() {
super();
initGUI();
}
private void initGUI() {
try {
this.setPreferredSize(new java.awt.Dimension(294, 85));
{
jLabel1 = new JLabel();
this.add(jLabel1);
jLabel1.setText("Please enter the new chat room name:");
}
{
textFieldchatRoomName = new JTextField();
this.add(textFieldchatRoomName);
textFieldchatRoomName.setPreferredSize(new java.awt.Dimension(263, 22));
}
{
cancelButton = new JButton();
this.add(cancelButton);
cancelButton.setText("Cancel");
cancelButton.setPreferredSize(new java.awt.Dimension(84, 22));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Cancel PRESSED");
}
});
}
{
okButton = new JButton();
this.add(okButton);
okButton.setText("Ok");
okButton.setPreferredSize(new java.awt.Dimension(60, 22));
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("OK PRESSED");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is a pretty simple GUI which has a text field and 2 buttons one "Ok" one "Chancel".
When i click "Ok" i want the textField value to be sent to the class where the GUI instance is originally run.
Any ideas how to do this??
The JPanel you posted should be added to a modal JDialog content pane. In the same class, you can provide some methods to return the values the user entered into the text fields.
In the original window, you open the dialog.
SomeDialog dialog = new SomeDialog(parent);
dialog.setVisible(true);
The code after setVisible() will only be executed after the modal dialog is closed. At this point you can call the methods I mentioned above for getting the text field values.
Related
I am trying to build a JFrame with four manual input JTextFields: description, hours, minutes, ID
and two JButtons: Submit and Reset
I need to disable the "Submit" button until all text fields have some data. To achieve this, I have used the DocumentListener and that is working fine, that is, initially the "Submit" button is disabled and gets enabled only when all text fields have some input.
PROBLEM: After "Submit" button is enabled, I need to hit the submit button twice to get the actual action trigger (probably first time is to restore focus after getting enabled, second time to do actual work). This issue does not happen with the "Reset" button.
TRIED AND DIDN'T WORK: I tried restoring focus using submit.requestFocusInWindow() and it brought focus to the "Submit" button but the last modified text field lost focus and I had to click it again to restore focus on that field.
Please assist. I am quite new to StackOverflow, so kindly don't close the thread.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel titlePanel = new JPanel();
JPanel descPanel = new JPanel();
JPanel timeWorkedPanel = new JPanel();
JPanel iDPanel = new JPanel();
titlePanel.add(title);
mainPanel.add(titlePanel);
descPanel.add(desc);
mainPanel.add(descPanel);
timeWorkedPanel.add(hour);
timeWorkedPanel.add(minute);
mainPanel.add(timeWorkedPanel);
iDPanel.add(iD);
mainPanel.add(iDPanel);
JTextArea reqList = new JTextArea();
reqList.setLineWrap(false);
reqList.setEditable(false);
JScrollPane reqListScroll = new JScrollPane (reqList);
reqListScroll.setPreferredSize(new Dimension(400,400));
reqListScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setColumnHeaderView(new JLabel(" REQUEST CREATED TIME WORKED"));
mainPanel.add(reqListScroll);
List<JTextField> textFieldList = new ArrayList<>();
textFieldList.add(desc);
textFieldList.add(hour);
textFieldList.add(minute);
textFieldList.add(csiID);
JButton submit = new JButton("SUBMIT");
JButton reset = new JButton("RESET");
buttonPanel.add(submit);
buttonPanel.add(reset);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createVerticalStrut(20)); // a spacer
JFrame mainFrame = new JFrame("Test Frame");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setSize(new Dimension(500,600));
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
submit.setEnabled(false);
DocumentListener docListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
boolean isEnabled = true;
for(JTextField tf : textFieldList) {
if(tf.getText().isEmpty())
isEnabled = false;
}
submit.setEnabled(isEnabled);
}
};
for(JTextField tf : textFieldList) {
tf.getDocument().addDocumentListener(docListener);
}
final WebDriver newDriver = driver;
final ChromeOptions newOptions = options;
//Click on "SUBMIT" button
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("submitting");
mainFrame.setVisible(false);
createTicket(newDriver, newOptions, subportfolio, title, desc , hour, minute, csiID);
mainFrame.setVisible(true);
} catch (InterruptedException e1) {
}
}
});
//Click on "RESET" button
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
desc.setText(null);
hour.setText(null);
minute.setText(null);
csiID.setText(null);
}
});
I am trying to create a simple program where when I press a button, new text will appear but I have no idea how to do it (I imagine it is very simple).
The code I have right now is:
import java.awt.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button ("Terminate Program");
Button b2 = new Button ("Start");
b1.setBounds(50,50,50,50);
b2.setBounds(50,50,50,50);
b1.addActionListener(e-> System.exit(0));
Label txt = new Label ("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500,300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[]){
ConsumptionGUI frame1= new ConsumptionGUI();
} //end main
Basically after this point I managed to create a frame with 2 buttons and some text in the middle.
I am really struggling to continue from here.
I need the program to first start by the press of a button then print some new text (something like "please enter your car's speed") and then save this information (to be used in a simple formula).
Afterwards the program needs to display the formula used and print what is the value calculated.
Can anyone please help?
Thanks
To get user input, you can implement a Dialog like in below code. You can use another similar dialog to show the formula and result as well.
import java.awt.*;
import java.awt.event.*;
public class ConsumptionGUI extends Frame
{
public ConsumptionGUI()
{
Frame fr = new Frame();
Button b1 = new Button("Terminate Program");
Button b2 = new Button("Start");
//b1.setBounds(50, 50, 50, 50); // Unnecessary
//b2.setBounds(50, 50, 50, 50); // Unnecessary
b1.addActionListener(e -> System.exit(0));
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
InputDialog dialog = new InputDialog(fr);
dialog.setVisible(true);
System.out.println("User inputted speed = " + dialog.getSpeed());
}
});
Label txt = new Label("This is my first GUI");
//add to frame (after all buttons and text was added)
fr.add(b2);
fr.add(txt);
fr.add(b1);
fr.setSize(500, 300);
fr.setTitle("Vehicles Information System");
fr.setLayout(new FlowLayout());
fr.setVisible(true);
} //end constructor
public static void main(String args[])
{
ConsumptionGUI frame1 = new ConsumptionGUI();
} //end main
}
class InputDialog extends Dialog
{
private int speed;
InputDialog(Frame owner)
{
super(owner, "Input", true);
addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
dispose();
}
});
TextField textField = new TextField(20);
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
String speedString = textField.getText();
speed = !speedString.isEmpty() ? Integer.parseInt(speedString) : 0;
dispose();
}
});
setLayout(new GridLayout(3, 1));
add(new Label("Please enter your car's speed"));
add(textField);
add(okButton);
pack();
}
int getSpeed()
{
return speed;
}
}
Basically im trying to make a program that needs a barcode which you should enter through the GUI, it works with nextLine() since it pauses and waits for an input ,and i was wondering if there is anything like that but waiting for a input in a gui?
You can add a button to press after entering the input and listen to the button event. Check below example
public static void main(String[] args) {
JFrame frame = new JFrame("Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JTextField textField = new JTextField("enter input");
JButton button = new JButton();
button.setText("Ok");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame,
textField.getText());
}
});
panel.add(textField);
panel.add(button);
frame.add(panel);
frame.setSize(150, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
The other option is adding a document listener to your text field.
public static void main(String args[]) {
final JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
DocumentListener documentListener = new DocumentListener() {
public void changedUpdate(DocumentEvent documentEvent) {
JOptionPane.showMessageDialog(frame,
textField.getText());
}
public void insertUpdate(DocumentEvent documentEvent) {
JOptionPane.showMessageDialog(frame,
textField.getText());
}
public void removeUpdate(DocumentEvent documentEvent) {
JOptionPane.showMessageDialog(frame,
textField.getText());
}
};
textField.getDocument().addDocumentListener(documentListener);
frame.setSize(250, 150);
frame.setVisible(true);
}
I would like to set editable option of a text box based on the selection of a radio button? How to code the action listener on the radio button?
This is the solution that I would use in this case.
//The text field
JTextField textField = new JTextField();
//The buttons
JRadioButton rdbtnAllowEdit = new JRadioButton();
JRadioButton rdbtnDisallowEdit = new JRadioButton();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup editableGroup = new ButtonGroup();
editableGroup.add(rdbtnAllowEdit);
editableGroup.add(rdbtnDisallowEdit);
//add allow listener
rdbtnAllowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(true);
}
});
//add disallow listener
rdbtnDisallowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(false);
}
});
My Java is a little rusty, but this should be what you're looking for.
Here is your listener:
private RadioListener implements ActionListener{
private JTextField textField;
public RadioListener(JTextField textField){
this.textField = textField;
}
public void actionPerformed(ActionEvent e){
JRadioButton button = (JRadioButton) e.getSource();
// Set enabled based on button text (you can use whatever text you prefer)
if (button.getText().equals("Enable")){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
}
And here is the code that sets it up.
JRadioButton enableButton = new JRadioButton("Enable");
JRadioButton disableButton = new JRadioButton("Disable");
JTextField field = new JTextField();
RadioListener listener = new RadioListener(field);
enableButton.addActionListener(listener);
disableButton.addActionListener(listener);
Another answer for this question. Modify a little code from zalpha314 's answer.
You could know which radio button is selected by the text of this button, and you could also know it by Action Command. In the oracle's radio button demo code http://docs.oracle.com/javase/tutorial/uiswing/examples/components/RadioButtonDemoProject/src/components/RadioButtonDemo.java , I learnt how to use action command.
First, define two action command
final static String ON = "on"
final static String OFF = "off"
Then add action command to buttons
JRadioButton enableButton = new JRadioButton("Enable");
enableButton.setActionCommand(ON);
JRadioButton disableButton = new JRadioButton("Disable");
disableButton.setActionCommand(OFF);
So in actionPerformed, you could get the action command.
public void actionPerformed(ActionEvent e){
String ac = e.getActionCommand();
if (ac.equals(ON)){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
Action command maybe better when the button.getText() is a very long string.
Try this:
JRadioButton myRadioButton = new JRadioButton("");
myRadioButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// Do something here...
}
});
Try this:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NewStudent {
public static void main(String[] args){
NewStudent st=new NewStudent();
}
public NewStudent(){
JFrame frame=new JFrame("STUDENT REGISTRATION FORM");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
JPanel p1=new JPanel();
p1.setLayout(null);
p1.setBackground(Color.CYAN);
frame.add(p1);
ButtonGroup buttonGroup=new ButtonGroup();
JRadioButton male=new JRadioButton("MALE");
male.setBounds(100,170,100,20);
buttonGroup.add(male);
p1.add(male);
JRadioButton female=new JRadioButton("FEMALE");
female.setBounds(250,170,100,20);
buttonGroup.add(female);
p1.add(female);
JLabel sex =new JLabel("SEX:");
sex.setBounds(10,200,100,20);
p1.add(sex);
final JTextField gender= new JTextField();
gender.setBounds(100,200,300,20);
p1.add(gender);
male.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("MALE");
}
});
female.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("FEMALE");
}
});
}
I'm having problems getting my JPanel to display properly. I want to use different extended JPanels to display what I want the user to do with this program (which is ultimately to display photographs). Below is the code for the only two classes that exist at this point. Unfortunately, I'm having problems just getting this to work right out of the gate with the first panel which was to present the user with the ability to select different graphic images.
What's happening is, I can't get my JPanel to display until I click the "Open" menu item in the File menu. Once that JOptionPane shows, so does my JPanel (NewAlbum).
class PhotoGallery {
static JPanel transientPanel = null;
static final JFrame mainFrame = new JFrame("Photo Gallery");
public static void main(String[] args) {
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem open = new JMenuItem("Open");
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame, "Hello World");
}
});
fileMenu.add(open);
JMenuItem newAlbum = new JMenuItem("New Album");
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AssignToTransientPanel((JPanel) new NewAlbum());
Container content = mainFrame.getContentPane();
content.removeAll();
content.add(transientPanel);
content.validate();
content.repaint();
}
});
fileMenu.add(newAlbum);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
fileMenu.add(exit);
JMenuBar pgMenu = new JMenuBar();
pgMenu.add(fileMenu);
mainFrame.setJMenuBar(pgMenu);
mainFrame.setSize(640, 480);
mainFrame.setLocation(20, 45);
mainFrame.validate();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public static void AssignToTransientPanel(JPanel jp) {
if(transientPanel != null)
mainFrame.remove(transientPanel);
transientPanel = jp;
}
}
}
class NewAlbum extends JPanel {
JButton selectImages = new JButton("Select Images");
JFileChooser jfc;
File[] selectedFiles;
public NewAlbum() {
selectImages.setLocation(25, 25);
add(selectImages);
selectImages.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent ae) {
jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(true);
jfc.showOpenDialog(getParent());
selectedFiles = jfc.getSelectedFiles();
}
});
this.validate();
}
public int getHeight() {
return getParent().getSize().height - 20;
}
public int getWidth() {
return getParent().getSize().width - 20;
}
public Dimension getPreferredSize() {
return new Dimension(this.getWidth(), this.getHeight());
}
}
You have not added any components to the mainFrame's content pane in the main method. The only time a panel gets added is in this ActionListener:
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AssignToTransientPanel((JPanel) new NewAlbum());
Container content = mainFrame.getContentPane();
content.removeAll();
content.add(transientPanel);
content.validate();
content.repaint();
}
});
This is only getting called when "Open" is clicked as you have, I assume accidentally, added the ActionListener to the open JMenuItem rather than the newAlbum JMenuItem. To add content on startup you need to add something like this before the mainFrame.setVisible(true) line:
mainFrame.add(new NewAlbum());
BTW, the convention is for all methods in Java source code to start with a lower case letter. assignToTransientPanel would be a better name for your method.