I am working on my HOMEWORK (please don't do my work for me). I have 95% of it completed already. I am having trouble with this last bit though. I need to display the selected gender in the JTextArea. I must use the JRadioButton for gender selection.
I understand that JRadioButtons work different. I set up the action listener and the Mnemonic. I think I am messing up here. It would seem that I might need to use the entire group to set and action lister maybe.
Any help is greatly appreciated.
Here is what I have for my code (minus parts that I don't think are needed so others can't copy paste schoolwork):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;
public class LuisRamosHW3 extends JFrame {
private JLabel WelcomeMessage;
private JRadioButton jrbMale = new JRadioButton("Male");
private JRadioButton jrbFemale = new JRadioButton("Female");
public LuisRamosHW3(){
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 30));
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(2,1));
jpRadioButtons.add(jrbMale);
jpRadioButtons.add(jrbFemale);
add(jpRadioButtons, BorderLayout.AFTER_LAST_LINE);
ButtonGroup gender = new ButtonGroup();
gender.add(jrbMale);
jrbMale.setMnemonic(KeyEvent.VK_B);
jrbMale.setActionCommand("Male");
gender.add(jrbFemale);
jrbFemale.setMnemonic(KeyEvent.VK_B);
jrbFemale.setActionCommand("Female");
//Set defaulted selection to "male"
jrbMale.setSelected(true);
//Create Welcome button
JButton Welcome = new JButton("Submit");
add(Welcome);
Welcome.addActionListener(new SubmitListener());
WelcomeMessage = (new JLabel(" "));
add(WelcomeMessage);
}
class SubmitListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
String FirstName = jtfFirstName.getText();
String FamName = jtfLastName.getText();
Object StateBirth = jcbStates.getSelectedItem();
String Gender = gender.getActionCommand(); /*I have tried different
variations the best I do is get one selection to print to the text area*/
WelcomeMessage.setText("Welcome, " + FirstName + " " + FamName + " a "
+ gender.getActionCommmand + " born in " + StateBirth);
}
}
} /*Same thing with the printing, I have tried different combinations and just can't seem to figure it out*/
I have done a similar kind of a problem on JTable where we get the selection from the radio group and then act accordingly. Thought of sharing the solution.
Here, I have grouped the radio buttons using the action listener and each radio button will have an action command associated with it. When the user clicks on a radio button then an action will be fired subsequently an event is generated where we deselect other radio button selection and refresh the text area with the new selection.
import java.awt.BorderLayout;
import java.awt.EventQueue;
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.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class RadioBtnToTextArea {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new RadioBtnToTextArea().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JPanel radioPnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel textPnl = new JPanel();
JRadioButton radioMale = new JRadioButton();
JRadioButton radioFemale = new JRadioButton();
JTextArea textArea = new JTextArea(10, 30);
ActionListener listener = new RadioBtnAction(radioMale, radioFemale, textArea);
radioPnl.add(new JLabel("Male"));
radioPnl.add(radioMale);
radioMale.addActionListener(listener);
radioMale.setActionCommand("1");
radioPnl.add(new JLabel("Female"));
radioPnl.add(radioFemale);
radioFemale.addActionListener(listener);
radioFemale.setActionCommand("2");
textPnl.add(textArea);
panel.add(radioPnl, BorderLayout.NORTH);
panel.add(textPnl, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class RadioBtnAction implements ActionListener {
JRadioButton maleBtn;
JRadioButton femaleBtn;
JTextArea textArea;
public RadioBtnAction(JRadioButton maleBtn,
JRadioButton femaleBtn,
JTextArea textArea) {
this.maleBtn = maleBtn;
this.femaleBtn = femaleBtn;
this.textArea = textArea;
}
#Override
public void actionPerformed(ActionEvent e) {
int actionCode = Integer.parseInt(e.getActionCommand());
switch (actionCode) {
case 1:
maleBtn.setSelected(true);
femaleBtn.setSelected(false);
textArea.setText("Male");
break;
case 2:
maleBtn.setSelected(false);
femaleBtn.setSelected(true);
textArea.setText("Female");
break;
default:
break;
}
}
}
Suggestions:
Make your ButtonGroup variable, gender, a field (declared in the class) and don't declare it in the constructor which will limit its scope to the constructor only. It must be visible throughout the class.
Make sure that you give your JRadioButton's actionCommands. JRadioButtons are not like JButtons in that if you pass a String into their constructor, this does not automatically set the JRadioButton's text, so you will have to do this yourself in your code.
You must first get the selected ButtonModel from the ButtonGroup object via getSelection()
Then check that the selected model is not null before getting its actionCommand text.
For example
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class RadioButtonEg extends JPanel {
public static final String[] RADIO_TEXTS = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
// *** again declare this in the class.
private ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textfield = new JTextField(20);
public RadioButtonEg() {
textfield.setFocusable(false);
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
for (String radioText : RADIO_TEXTS) {
JRadioButton radioButton = new JRadioButton(radioText);
radioButton.setActionCommand(radioText); // **** don't forget this
buttonGroup.add(radioButton);
radioButtonPanel.add(radioButton);
}
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ButtonAction("Press Me", KeyEvent.VK_P)));
setLayout(new BorderLayout());
add(radioButtonPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
add(textfield, BorderLayout.PAGE_START);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
textfield.setText("No radio button has been selected");
} else {
textfield.setText("Selection: " + model.getActionCommand());
}
}
}
private static void createAndShowGui() {
RadioButtonEg mainPanel = new RadioButtonEg();
JFrame frame = new JFrame("RadioButtonEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Related
ParentFrame shows ArrayList and one "ADD" Button. Once I click "ADD" Button on ParentFrame, then ChildFrame shows up.
On ChildFrame, I type in a String and click "OK" Button then it should transfer its String to ParentFrame. Finally ParentFrame should be repainted with newly added String.
I'm having trouble with repainting but also I might failed to send String from Child to Parent since Parent didn't get repainted.
I tried several things in two or three other points of view but following code seems like to work but......
I need your help!!
ParentFrame
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
#SuppressWarnings("serial")
public class parentFrame extends JFrame {
ArrayList<String> list = new ArrayList<>(){{add("test1"); add("test2");}};
JButton add;
JPanel big, small;
JLabel content;
childFrame addFrame;
public parentFrame() {
super("parent frame");
super.setLayout(new BorderLayout());
super.setSize(600,600);
big = new JPanel();
for(int i=0; i<list.size(); i++) {
content = new JLabel();
content.setText(list.get(i));
big.add(content);
}
super.add(big, BorderLayout.CENTER);
add = new JButton("ADD");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addFrame = new childFrame();
/* By next 3 lines, I'm trying to transfer the value of childFrame's test to this parentFrame's list. */
list.add(addFrame.getTestString());
big.revalidate();
big.repaint();
}
});
super.add(add, BorderLayout.SOUTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new parentFrame();
}
}
2.ChildFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class childFrame extends JFrame {
String test;
JTextField name;
JButton ok, cancel;
public childFrame() {
super("child frame");
super.setLayout(new BorderLayout());
super.setSize(400,200);
JPanel centerPanel = new JPanel(new GridLayout(1,1));
centerPanel.setSize(150, 100);
name = new JTextField();
centerPanel.add(name);
JPanel bottomPanel = new JPanel(new FlowLayout());
ok = new JButton("OK");
ok.addActionListener(new OKListener());
super.add(ok);
cancel = new JButton("CANCEL");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
bottomPanel.add(cancel);
bottomPanel.add(ok);
super.add(centerPanel, BorderLayout.CENTER);
super.add(bottomPanel, BorderLayout.SOUTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class OKListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
test = name.getText();
dispose();
}
}
public String getTestString() {
return test;
}
}
Your problem is here:
public void actionPerformed(ActionEvent e) {
addFrame = new childFrame();
list.add(addFrame.getTestString());
big.revalidate();
big.repaint();
}
Since your child frame is not a modal window (for example, a JOptionPane is a modal dialog window), it does not halt program flow in the calling window. You call .getTestString() immediately on creation of the child frame but before the user has had any chance to enter in any data (again, because program flow in the calling window is not halted).
The solution is to make your child "frame" in fact a modal JDialog. This will pretty much solve the whole issue. So, don't have the child frame extend from JFrame, but rather extend JDialog, and use the JDialog constructor that makes it modal (see the JDialog API).
e.g.,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
// note that class names should begin with an upper-case letter
public class ChildFrame extends JDialog {
String test;
JTextField name;
JButton ok, cancel;
public ChildFrame(JFrame parentFrame) {
// the true parameter makes this modal
super(parentFrame, "child frame", true);
Now this dialog window will freeze program flow from the calling code as soon as the dialog is set visible, and the calling code flow won't resume until this dialog is no longer visible.
Also, please have a look at The Use of Multiple JFrames, Good/Bad Practice?
An alternative to this is to continue to use multiple JFrames (not recommended!!), and add a WindowListener to the "child" window, listening for windows closing events, and then getting the information from your dialog in call-back method that is activated when the windows closing event occurs.
For a working example:
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ParentGuiPanel extends JPanel {
private DefaultListModel<String> listModel = new DefaultListModel<>();
private JList<String> jList = new JList<>(listModel);
private JButton addButton = new JButton("Add");
private JDialog childDialog;
private ChildGuiPanel childPanel = new ChildGuiPanel();
public ParentGuiPanel() {
listModel.addElement("Test 1");
listModel.addElement("Test 2");
jList.setPrototypeCellValue("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
jList.setVisibleRowCount(8);
JScrollPane scrollPane = new JScrollPane(jList);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
addButton.addActionListener(e -> addActionPerformed(e));
addButton.setMnemonic(KeyEvent.VK_A);
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
setLayout(new BorderLayout());
add(scrollPane);
add(buttonPanel, BorderLayout.PAGE_END);
}
private void addActionPerformed(ActionEvent e) {
Window window = null;
if (childDialog == null) {
window = SwingUtilities.getWindowAncestor(this);
if (window == null) {
return;
}
childDialog = new JDialog(window, "Child GUI", ModalityType.APPLICATION_MODAL);
childDialog.add(childPanel);
childDialog.pack();
childDialog.setLocationRelativeTo(window);
}
if (childDialog != null) {
childDialog.setVisible(true);
String text = childPanel.getText();
if (!text.trim().isEmpty()) {
listModel.addElement(text);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainGui = new JFrame("Main GUI");
mainGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ParentGuiPanel mainPanel = new ParentGuiPanel();
mainGui.add(mainPanel);
mainGui.pack();
mainGui.setLocationRelativeTo(null);
mainGui.setVisible(true);
});
}
}
#SuppressWarnings("serial")
class ChildGuiPanel extends JPanel {
private JTextField textField = new JTextField(15);
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public ChildGuiPanel() {
okButton.addActionListener(e -> okActionPerformed(e));
cancelButton.addActionListener(e -> cancelActionPerformed(e));
textField.addActionListener(e -> okActionPerformed(e));
okButton.setMnemonic(KeyEvent.VK_O);
cancelButton.setMnemonic(KeyEvent.VK_C);
add(new JLabel("Text: "));
add(textField);
add(okButton);
add(cancelButton);
}
public String getText() {
return textField.getText();
}
private void disposeWindow() {
textField.selectAll();
Window window = SwingUtilities.getWindowAncestor(this);
if (window != null) {
window.dispose();
}
}
private void okActionPerformed(ActionEvent e) {
disposeWindow();
}
private void cancelActionPerformed(ActionEvent e) {
textField.setText("");
disposeWindow();
}
}
I am creating a basic GUI frame. The frame has 10 radio buttons and a Submit button. The user selects one option(JRadioButtons) and clicks on the Submit(JButton) button. On clicking the Submit button, the option selected by the user appears on a different frame.
I want the Submit button to recognize the JRadioButton selected by the user.
I have put my bit of code here for reference.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame2 extends JFrame{
private JFrame frame2;
private JLabel label2;
private JButton button2;
private JRadioButton r1;
private JRadioButton r2;
private JRadioButton r3;
private JRadioButton r4;
private JRadioButton r5;
private JRadioButton r6;
private JRadioButton r7;
private JRadioButton r8;
private JRadioButton r9;
private JRadioButton r10;
public ButtonGroup group;
Frame2(){
setLayout(new BorderLayout());
setSize(new Dimension(1304,690));
getContentPane().setBackground(Color.DARK_GRAY);
label2= new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff",Font.BOLD, 14));
label2.setForeground(Color.WHITE);
button2=new JButton("Submit");
add(label2, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new GridLayout(2, 5));
centerPanel.add(r1=new JRadioButton("Introduction"));
centerPanel.add(r2=new JRadioButton("Class and Objects"));
centerPanel.add(r3=new JRadioButton("Object Oriented Programming Concepts"));
centerPanel.add(r4=new JRadioButton("JAVA literals, constants, variables"));
centerPanel.add(r5=new JRadioButton("Loops"));
centerPanel.add(r6=new JRadioButton("Functions/Methods"));
centerPanel.add(r7=new JRadioButton("Strings"));
centerPanel.add(r8=new JRadioButton("Arrays"));
centerPanel.add(r9=new JRadioButton("Time Complexity"));
centerPanel.add(r10=new JRadioButton("Data Structures"));
add(centerPanel, BorderLayout.CENTER);
group= new ButtonGroup();
group.add(r1);
group.add(r2);
group.add(r3);
group.add(r4);
group.add(r5);
group.add(r6);
group.add(r7);
group.add(r8);
group.add(r9);
group.add(r10);
add(button2, BorderLayout.SOUTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button2) {
Layouts l=new Layouts();
l.main(null);
dispose();
}
}
});
}
public static void main(String[] args) {
Frame2 fr2=new Frame2();
}
}`
Thanks in advance.
It's a lot easier if you put the JRadioButtons in an array.
Here are the changes I made to your code to make it easier to modify and understand.
I added a call to the SwingUtilities invokeLater method to ensure the creation and execution of the Swing components happens on the Event Dispatch Thread.
I created the individual JPanels in methods. By separating the JPanel code, I could more easily focus on one part of the GUI at a time.
The methods to construct a JFrame must be called in the proper order. You have to create all the Swing components before you make the JFrame visible.
Here's one way to connect a JButton with a group of JRadioButtons.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioButtonTest {
private JButton button2;
private JRadioButton[] rb;
private ButtonGroup group;
public RadioButtonTest() {
JFrame frame = new JFrame("Java Tutorials");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.DARK_GRAY);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JLabel label2 = new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff", Font.BOLD, 14));
label2.setForeground(Color.WHITE);
panel.add(label2, BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
button2 = new JButton("Submit");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button2) {
for (int i = 0; i < rb.length; i++) {
if (rb[i].isSelected()) {
String text = rb[i].getText();
System.out.println(text);
// Do your second JFrame
}
}
}
}
});
panel.add(button2, BorderLayout.SOUTH);
return panel;
}
private JPanel createButtonPanel() {
JPanel centerPanel = new JPanel(new GridLayout(0, 2));
String[] titles = { "Introduction", "Class and Objects",
"Object Oriented Programming Concepts",
"JAVA literals, constants, variables", "Loops",
"Functions/Methods", "Strings", "Arrays",
"Time Complexity", "Data Structures" };
rb = new JRadioButton[titles.length];
group = new ButtonGroup();
for (int i = 0; i < titles.length; i++) {
rb[i] = new JRadioButton(titles[i]);
group.add(rb[i]);
centerPanel.add(rb[i]);
}
return centerPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RadioButtonTest();
}
});
}
}
I am making a dating game in the style of the Japanese dating game with pictures and responses for fun and practice. I am trying to have a JOptionPane message dialog show up for each button in a grid layout as a response to each option. In this way it's like a logic tree. I am not used to using action listener as I am somewhat of a beginner. Here is my code. I am just not used to the syntax of doing this.
Can anyone help me?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.*;
//Implementations of packages
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
private static final int TITLE_POINTS = 3; //number of objects in text box
public NestedPanels() { //implemeted class
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
for (String btnText : BTN_TEXTS) { //BTN TEXT button titles linked to string btnText label
southBtnPanel.add(new JButton(btnText)); //add btnText label
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Review the following to get an idea of how to add action listener to buttons.
Please note the comments:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
//never used : private static final int TITLE_POINTS = 3;
public NestedPanels() {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1));
for (String btnText : BTN_TEXTS) {
JButton b = new JButton(btnText);
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonClicked(e);//when button clicked, invoke method
}
});
//alternative much shorter way to add action listener:
//b.addActionListener(e -> buttonClicked());
southBtnPanel.add(b);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
//this adds Box to the default BorderLayout.CENTER position
add(Box.createRigidArea(new Dimension(600, 600)));
add(southBtnPanel, BorderLayout.SOUTH);
}
//respond to button clicked
private void buttonClicked(ActionEvent e) {
String msg = ((JButton)e.getSource()).getActionCommand()+" pressed" ;
JOptionPane.showMessageDialog(this, msg ); //display button Action
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Date Sim 1.0");
//no need to invoke twice frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//no need to invoke twice frame.pack();
//no need to invoke twice frame.setVisible(true);
frame.getContentPane().add(mainPanel);
/*
* when posting images, use web resources that anyone can access
*
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
*this adds label to the default BorderLayout.CENTER position, which is already taken by
*the Box. Only one (last) component will be added
mainPanel.add(label);
*
*/
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//remove all code which is not essential to the question
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
but I have already instantiated a parent class of extending the jpanel
Did you look at the example code provided in the tutorial???
The example there "
... extends JFrame implements ActionListener
So all you need is:
... extends JPanel implements ActionListener
Or in case you need multiple ActionListeners the more flexible approach to create a custom class.
You can use an "annonymous inner class" for the ActionListener. Something like:
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String text = button.getText();
Window window = SwingUtilities.windowForComponent(button);
JOptionPane.showMessageDialog(window, text);
}
};
Then when you create the button you would do:
for (String btnText : BTN_TEXTS)
{
JButton button = new JButton( btnText );
button.addActionListener( al );
southBtnPanel.add( button );
}
I'm new to programming with Java.
I have these two small projects.
import javax.swing.*;
public class tutorial {
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("hello");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(label);
JButton button = new JButton("Hello again");
panel.add(button);
}
}
and this one:
import java.util.*;
public class Test {
public static void main(String[] args){
int age;
Scanner keyboard = new Scanner(System.in);
System.out.println("How old are you?");
age = keyboard.nextInt();
if (age<18)
{
System.out.println("Hi youngster!");
}
else
{
System.out.println("Hello mature!");
}
}
}
How can I add the second code to the first one, so that the user will see a window that says 'How old are you' and they can type their age.
Thanks in advance!
I'm not sure of all the things you wanted because it was undefined, but as I far as I understand, you wanted a JFrame containing an input field, in which you will be able to input values and display the appropriate answer.
I also suggest you read tutorial , but don't hesitate if you have question.
I hope it's a bit close to what you wanted.
package example.tutorial;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
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 javax.swing.JTextField;
public class Tutorial extends JPanel {
private static final String YOUNG_RESPONSE = "Hi youngster!";
private static final String ADULT_RESPONSE = "Hello mature!";
private static final String INVALID_AGE = "Invalid age!";
private static final int MIN_AGE = 0;
private static final int MAX_AGE = 100;
private static JTextField ageField;
private static JLabel res;
private Tutorial() {
setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
JLabel label = new JLabel("How old are you ? ");
northPanel.add(label);
ageField = new JTextField(15);
northPanel.add(ageField);
add(northPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
JButton btn = new JButton("Hello again");
btn.addActionListener(new BtnListener());
centerPanel.add(btn);
res = new JLabel();
res.setVisible(false);
centerPanel.add(res);
add(centerPanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.add(new Tutorial());
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String content = ageField.getText();
int age = -1;
try{
age = Integer.parseInt(content);
if(isValid(age)) {
res.setText(age < 18 ? YOUNG_RESPONSE : ADULT_RESPONSE);
} else {
res.setText(INVALID_AGE);
}
if(!res.isVisible())
res.setVisible(true);
} catch(NumberFormatException ex) {
res.setText("Wrong input");
}
}
private boolean isValid(int age) {
return age > MIN_AGE && age < MAX_AGE;
}
}
}
so that the user will see a window that says 'How old are you' and they can type their age.
The easiest way to start would be to use a JOptionPane. Check out the section from the Swing tutorial on How to Use Dialogs for examples and explanation.
Don't forget to look at the table of contents for other Swing related topics for basic information about Swing.
You will need an input field to get the text and then add an ActionListener to the button which contains the logic that is performed when the button is pressed.
I modified your code to implement what you described:
import javax.swing.*;
import java.awt.event.*;
public class tutorial {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("hello");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(label);
final JTextField input = new JTextField(5); // The input field with a width of 5 columns
panel.add(input);
JButton button = new JButton("Hello again");
panel.add(button);
final JLabel output = new JLabel(); // A label for your output
panel.add(output);
button.addActionListener(new ActionListener() { // The action listener which notices when the button is pressed
public void actionPerformed(ActionEvent e) {
String inputText = input.getText();
int age = Integer.parseInt(inputText);
if (age < 18) {
output.setText("Hi youngster!");
} else {
output.setText("Hello mature!");
}
}
});
}
}
In that example we don't validate the input. So if the input is not an Integer Integer.parseInt will throw an exception. Also the components are not arranged nicely. But to keep it simple for the start that should do it. :)
it's not an easy question since you are working on command line in one example, and in a Swing GUI in the other.
Here's a working example, i've commented here and there.
This is no where near java best practises and it misses a lot of validation (just see what happens when you enter a few letters or nothing in the textfield.
Also please ignore the setLayout(null) and setBounds() statements, it's just a simple example not using any layout managers.
I hope my comments will help you discovering java!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//You'll need to implement the ActionListener to listen to buttonclicks
public class Age implements ActionListener{
//Declare class variables so you can use them in different functions
JLabel label;
JTextField textfield;
//Don't do al your code in the static main function, instead create an instance
public static void main(String[] args){
new Age();
}
// this constructor is called when you create a new Age(); like in the main function above.
public Age()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0,0,300,300);
panel.setLayout(null);
label = new JLabel("hello");
label.setBounds(5,5,100,20);
// a JTextfield allows the user to edit the text in the field.
textfield = new JTextField();
textfield.setBounds(5,30,100,20);
JButton button = new JButton("Hello again");
button.setBounds(130,30,100,20);
// Add this instance as the actionlistener, when the button is clicked, function actionPerformed will be called.
button.addActionListener(this);
panel.add(label);
panel.add(textfield);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
//Required function actionPerformed for ActionListener. When the button is clicked, this function is called.
#Override
public void actionPerformed(ActionEvent e)
{
// get the text from the input.
String text = textfield.getText();
// parse the integer value from the string (! needs validation for wrong inputs !)
int age = Integer.parseInt(text);
if (age<18)
{
//instead of writing out, update the text of the label.
label.setText("Hi youngster!");
}
else
{
label.setText("Hello mature!");
}
}
}
I am trying to create a way to update a JComboBox so that when the user enters something into the text field, some code will process the entry and update the JComboBox accordingly.The one issue that I am having is I can update the JComboBox, but the first time it is opened, the box has not refresh the length of the options in it and as seen in the code below it displays extra white space. I do not know if there is a better different way to do this, but this is what I came up with.
Thanks for the help,
Dan
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Catch{
public static JComboBox dropDown;
public static String dropDownOptions[] = {
"Choose",
"1",
"2",
"3"};
public static void main(String[] args) {
dropDown = new JComboBox(dropDownOptions);
final JTextField Update = new JTextField("Update", 10);
final JFrame frame = new JFrame("Subnet Calculator");
final JPanel panel = new JPanel();
frame.setSize(315,430);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Update.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent arg0) {
}
public void focusLost(FocusEvent arg0) {
dropDown.removeAllItems();
dropDown.insertItemAt("0", 0);
dropDown.insertItemAt("1", 1);
dropDown.setSelectedIndex(0);
}
});
panel.add(Update);
panel.add(dropDown);
frame.getContentPane().add(panel);
frame.setVisible(true);
Update.requestFocus();
Update.selectAll();
}
}
1) JTextField listening for ENTER key from ActionListener
2) remove FocusListener
3) example about add new Item as last Item from JTextField to the JList, only you have to modify for JComboBox and add method insertItemAt() correctly
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListBottom2 {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JTextField textField = new JTextField("Use Enter to Add");
private JPanel panel = new JPanel(new BorderLayout());
public ListBottom2() {
model.addElement("First");
list.setVisibleRowCount(5);
panel.setBackground(list.getBackground());
panel.add(list, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(new Dimension(200, 100));
frame.add(scrollPane);
frame.add(textField, BorderLayout.NORTH);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField textField = (JTextField) e.getSource();
DefaultListModel model = (DefaultListModel) list.getModel();
model.addElement(textField.getText());
int size = model.getSize() - 1;
list.scrollRectToVisible(list.getCellBounds(size, size));
textField.setText("");
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ListBottom2 frame = new ListBottom2();
}
});
}
}