How can I switch JFrames by clicking a JButton in Java? - java

I am writing a program and am unable to figure this out but I have a JButton called nextDay and I need it set up so once I click it, it switches to the JFrame day2 as the program starts out on day1. Any help is appreciated.
Here is my code. I have a separate Main method which I wont include as it shouldn't need to be changed
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SoldierSimTest extends JFrame {
private final JButton decision1;
private final JButton decision2;
private final JButton decision3;
private final JButton decision4;
private final JTextField situation;
private JFrame day1;
private JFrame day2;
private JFrame day3;
private JFrame day4;
private JFrame day5;
private JFrame day6;
private JFrame day7;
private final JButton nextDay;
private final JButton exitGame;
private final JButton newGame;
public SoldierSimTest() {
decision1 = new JButton("Storm it");
decision2 = new JButton("Sneak around the flank");
decision3 = new JButton("Sneak up and grenade spam 'em");
decision4 = new JButton("Just dont");
situation = new JTextField("You and your squad are ordered to take
an enemy fort. How will you do so?");
situation.setEditable(false);
nextDay = new JButton("Next Day");
exitGame = new JButton("Exit Game");
newGame = new JButton("New Game");
JPanel decisionsPanel = new JPanel();
decisionsPanel.setLayout(new GridLayout(2, 2));
decisionsPanel.add(decision1);
decisionsPanel.add(decision2);
decisionsPanel.add(decision3);
decisionsPanel.add(decision4);
JPanel optionsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 3));
optionsPanel.add(newGame);
optionsPanel.add(exitGame);
optionsPanel.add(nextDay);
JPanel situationsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 1));
situationsPanel.add(situation);
Container contentPane = getContentPane();
contentPane.add(decisionsPanel, "South");
contentPane.add(optionsPanel, "North");
contentPane.add(situationsPanel, "Center");
}
}

You can use card layout to switch panels. I used Jpanels as it seems to be the best option to use. For this example I used 2 panels.
public class SoldierSimTest extends JFrame
{
private final JButton decision1;
private final JButton decision2;
private final JButton decision3;
private final JButton decision4;
private final JTextField situation;
private JPanel day1Panel = new JPanel();
private JPanel day2Panel = new JPanel();
private final JButton nextDay;
private final JButton exitGame;
private final JButton newGame;
final static String DAY1 = "Day1";
final static String DAY2 = "Day2";
public SoldierSimTest()
{
decision1 = new JButton("Storm it");
decision2 = new JButton("Sneak around the flank");
decision3 = new JButton("Sneak up and grenade spam 'em");
decision4 = new JButton("Just dont");
situation = new JTextField("You and your squad are ordered to take an enemy fort. How will you do so?");
situation.setEditable(false);
JPanel decisionsPanel = new JPanel();
decisionsPanel.setLayout(new GridLayout(2, 2));
decisionsPanel.add(decision1);
decisionsPanel.add(decision2);
decisionsPanel.add(decision3);
decisionsPanel.add(decision4);
JPanel situationsPanel = new JPanel();
situationsPanel.add(situation);
day1Panel.setLayout(new GridLayout(2, 1));
day1Panel.add(situationsPanel);
day1Panel.add(decisionsPanel);
JPanel cards = new JPanel(new CardLayout());
cards.add(day1Panel, DAY1);
cards.add(day2Panel, DAY2);
nextDay = new JButton("Next Day");
exitGame = new JButton("Exit Game");
newGame = new JButton("New Game");
nextDay.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, DAY2);
}
});
JPanel optionsPanel = new JPanel();
optionsPanel.setLayout(new GridLayout(1, 3));
optionsPanel.add(newGame);
optionsPanel.add(exitGame);
optionsPanel.add(nextDay);
Container contentPane = getContentPane();
contentPane.add(optionsPanel, "North");
contentPane.add(cards, "Center");
}
}

The best way to do this if you don't necessarily need a new JFrame is the way #pavithraCS described. What I want to add is that normally, when you want a new "window" with different components to appear, you don't use a new JFrame because that opens a new window. Instead, using a new JPanel is more useful because you can stack them without having to switch to another window.
I hope this helps for the future.

Related

GUI Calculator using JFrames and layouts

I'm currently working on a calculator which should perform basic calculations such as addition, subtraction, multiplication, and division. To achieve the final outcome, I've to follow a certain design for the calculator. The design of the calculator is provided with this question. I've given my best on how to match the official design of the calculator but it's not matching it.
This is the OFFICIAL design of the calculator. This is how it should look.
This is WHAT I'm getting when I run the code.
The CODE:
package patel.Jainam;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class CalculatorFrame extends JFrame {
/**
* All the buttons that will be used in the calculator have been initialized
*/
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
private JButton button7;
private JButton button8;
private JButton button9;
private JButton button0;
private JButton buttonEqual;
private JButton buttonDot;
private JButton buttonClearLast;
private JButton buttonClearAll;
private JButton buttonAdd;
private JButton buttonSub;
private JButton buttonMul;
private JButton buttonDiv;
private JTextArea textArea;
public CalculatorFrame(){
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,1));
panel2.add(buttonClearLast = new JButton ("Clear Last"));
panel2.add(buttonClearAll = new JButton ("Clear All"));
add(panel2, BorderLayout.PAGE_START);
JPanel panel3 = new JPanel();
textArea = new JTextArea(2,10);
// textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel3.add(scrollPane);
add(panel3, BorderLayout.LINE_START);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(4,4));
panel1.add(button7 = new JButton ("7"));
panel1.add(button8 = new JButton ("8"));
panel1.add(button9 = new JButton ("9"));
panel1.add(buttonAdd = new JButton ("+"));
panel1.add(button4 = new JButton ("4"));
panel1.add(button5 = new JButton ("5"));
panel1.add(button6 = new JButton ("6"));
panel1.add(buttonSub = new JButton ("-"));
panel1.add(button1 = new JButton ("1"));
panel1.add(button2 = new JButton ("2"));
panel1.add(button3 = new JButton ("3"));
panel1.add(buttonMul = new JButton ("*"));
panel1.add(button0 = new JButton ("0"));
panel1.add(buttonDot = new JButton ("."));
panel1.add(buttonEqual = new JButton ("="));
panel1.add(buttonDiv = new JButton ("/"));
add(panel1, BorderLayout.PAGE_END);
}
}
Thank you.
The problem is you are over using the GridLayout.
I would suggest you want to keep using the default layout manager of the frame which is a BorderLayout.
Then you would do the following:
Create a panel using a GridLayout for the two buttons. Add this panel to the BorderLayout.PAGE_START of the frame.
Add your scroll pane containing the text area to the BorderLayout.CENTER of the frame.
Create a panel using the GridLayout for the buttons on the bottom. Add this panel to the BorderLayout.PAGE_END of the frame.
Read the section from the Swing tutorial on Using Layout Managers for more information and working examples of the Borderlayout and GridLayout.
camickr's answer is optimal here.
Here is an SSCCE:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class CalculatorFrame extends JFrame {
public CalculatorFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(createClearPanel(), BorderLayout.PAGE_START);
getContentPane().add(createTextArea(), BorderLayout.CENTER);
getContentPane().add(createNumberPanels(), BorderLayout.PAGE_END);
setSize(300, 300);
pack();
}
private JPanel createNumberPanels() {
JPanel main = new JPanel();
main.setLayout(new GridLayout(4, 0));
for (int i = 0; i < 16; i++) {
JButton button = new JButton("" + i);
main.add(button);
}
return main;
}
private JScrollPane createTextArea() {
JTextArea area = new JTextArea(5, 10);
JScrollPane sp = new JScrollPane(area);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
return sp;
}
private JPanel createClearPanel() {
JButton clearAll = new JButton("clear all");
JButton clearLast = new JButton("Clear last");
JPanel panel = new JPanel(new GridLayout(1, 0));
panel.add(clearLast);
panel.add(clearAll);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CalculatorFrame().setVisible(true));
}
}
Preview:
P.S: Ignore the fact i used only numbers instead of operators like *,?,+,= etc.

How to display form in a dialog window?

I have a simple form consisting of 3 text fields and a cancel/ok button. This is in a GroupLayout. I'd like to know how to make this form pop up in a new window similar to a dialog? Can I pass my GroupLayout to a JDialog? I also need to validate the input before the form window closes. I currently have this working but it uses a new frame to do so and I've read that this is not the way to do it so I am asking here.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.*;
public class AddStockPromptTest {
private JFrame frame;
private JPanel mainPanel;
private JPanel formPanel;
private JPanel buttonPanel;
//private GroupLayout layout;
private JLabel lblItem;
private JLabel lblPrice;
private JLabel lblQuantity;
private JTextField itemField;
private JTextField priceField;
private JTextField quantityField;
private JButton okBtn;
private JButton cancelBtn;
public AddStockPromptTest() {
frame = new JFrame("Add New Stock Item");
//Container contentPane = frame.getContentPane();
mainPanel = new JPanel(new BorderLayout());
buttonPanel = new JPanel(new FlowLayout());
formPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(formPanel);
formPanel.setLayout(groupLayout);
groupLayout.setAutoCreateGaps(true);
lblItem = new JLabel("Item:");
lblPrice = new JLabel("Price:");
lblQuantity = new JLabel("Quantity:");
itemField = new JTextField();
priceField = new JTextField();
quantityField = new JTextField();
groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup()
.addComponent(lblItem)
.addComponent(lblPrice)
.addComponent(lblQuantity))
.addGroup(groupLayout.createParallelGroup()
.addComponent(itemField)
.addComponent(priceField)
.addComponent(quantityField))
);
groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblItem)
.addComponent(itemField))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblPrice)
.addComponent(priceField))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblQuantity)
.addComponent(quantityField))
);
cancelBtn = new JButton("Cancel");
buttonPanel.add(cancelBtn);
okBtn = new JButton("OK");
buttonPanel.add(okBtn);
mainPanel.add(formPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
frame.add(mainPanel);
frame.setTitle("Basil's Pizza Ordering System");
frame.setSize(800, 600);
frame.pack();
frame.setVisible(true);
//addStockPrompt();
}
private void addStockPrompt() {
}
}
JOptionPane will give you a dialog box. Use this in actionperformed event of your okay button.
JOptionPane.showMessageDialog(null, message);

Java: Layout Button/Label Placement

I'm trying to make a GUI pizza menu but I'm having trouble with the placements of the buttons/labels
public class PizzaGUI extends JFrame {
private JRadioButton rdoSmall;
private JRadioButton rdoMedium;
private JRadioButton rdoLarge;
private JRadioButton rdoExtraLarge;
private JLabel lblSize;
private ButtonGroup grpSize;
JPanel panelSize;
private JCheckBox chkPepperoni;
private JCheckBox chkMushrooms;
private JCheckBox chkOlives;
private JCheckBox chkPineapple;
private JLabel lblToppings;
JPanel panelToppings;
private JRadioButton rdoSoda;
private JRadioButton rdoTea;
private JRadioButton rdoBottledWater;
private JRadioButton rdoTapWater;
private JLabel lblDrinks;
private ButtonGroup grpDrinks;
JPanel panelDrinks;
JPanel container;
JButton calculateTotal;
JLabel order;
PizzaGUI()
{
super("Pizza Menu");
setSize(600,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createPanel();
add(container);
setVisible(true);
}
public void createPanel()
{
panelSize = new JPanel(new GridLayout(5, 1));
panelToppings = new JPanel(new GridLayout(5, 1));
panelDrinks = new JPanel(new GridLayout(5, 1));
container = new JPanel();
//Calculate Total
calculateTotal = new JButton("Calculate");
calculateTotal.setPreferredSize(new Dimension(95,45));
order = new JLabel("Your Order:");
//Pizza Sizes
lblSize = new JLabel("Choose a size:");
rdoSmall = new JRadioButton("Small ($7)");
rdoMedium = new JRadioButton("Medium ($9)");
rdoLarge = new JRadioButton("Large ($11)");
rdoExtraLarge = new JRadioButton("Extra Large ($14)");
//Toppings
lblToppings = new JLabel("Choose toppings ($1 Each):");
chkPepperoni = new JCheckBox("Pepperoni");
chkMushrooms = new JCheckBox("Mushrooms");
chkOlives = new JCheckBox("Olives");
chkPineapple = new JCheckBox("Pineapple");
//Drinks
lblDrinks = new JLabel("Choose a drink:");
rdoSoda = new JRadioButton("Soda ($2.00)");
rdoTea = new JRadioButton("Tea ($1.50)");
rdoBottledWater = new JRadioButton("Bottled Water ($1.25)");
rdoTapWater = new JRadioButton("Tap Water (No charge)");
//Add pizza sizes to button group
grpSize = new ButtonGroup();
grpSize.add(rdoSmall);
grpSize.add(rdoMedium);
grpSize.add(rdoLarge);
grpSize.add(rdoExtraLarge);
//Add drinks to button group
grpDrinks = new ButtonGroup();
grpDrinks.add(rdoSoda);
grpDrinks.add(rdoTea);
grpDrinks.add(rdoBottledWater);
grpDrinks.add(rdoTapWater);
//Add to panel
panelSize.add(lblSize);
panelSize.add(rdoSmall);
panelSize.add(rdoMedium);
panelSize.add(rdoLarge);
panelSize.add(rdoExtraLarge);
panelToppings.add(lblToppings);
panelToppings.add(chkPepperoni);
panelToppings.add(chkMushrooms);
panelToppings.add(chkOlives);
panelToppings.add(chkPineapple);
panelDrinks.add(lblDrinks);
panelDrinks.add(rdoSoda);
panelDrinks.add(rdoTea);
panelDrinks.add(rdoBottledWater);
panelDrinks.add(rdoTapWater);
container.add(panelSize);
container.add(Box.createHorizontalStrut(40));
container.add(panelToppings);
container.add(Box.createHorizontalStrut(40));
container.add(panelDrinks);
container.add(calculateTotal);
container.add(Box.createVerticalStrut(100));
container.add(order);
}
}
This the output
Menu
I have three separate grid layout panels for each type of menu and then I add it into one main panel which gets added to the frame. I would like to get the "Your Order:" placed in the middle left like the red one shown in the image. I know I can set the layout to null which would allow me to enter coordinates and it would solve my issue, however I read that it is bad practice to do it like that and I'm trying to effectively learn how to use layouts correctly. I don't even know if I'm on the right track, any examples would help. Thanks
May be this can help you.
You can add a seperate panel and then create a empty border for that panel.
container.add(panelSize);
container.add(Box.createHorizontalStrut(40));
container.add(panelToppings);
container.add(Box.createHorizontalStrut(40));
container.add(panelDrinks);
container.add(calculateTotal);
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 200, 10, 700));
panel.add(order, BorderLayout.EAST);
container.add(panel);
Your modified code it do what you want :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class PizzaGUI extends JFrame {
private JRadioButton rdoSmall;
private JRadioButton rdoMedium;
private JRadioButton rdoLarge;
private JRadioButton rdoExtraLarge;
private JLabel lblSize;
private ButtonGroup grpSize;
JPanel panelSize;
private JCheckBox chkPepperoni;
private JCheckBox chkMushrooms;
private JCheckBox chkOlives;
private JCheckBox chkPineapple;
private JLabel lblToppings;
JPanel panelToppings;
private JRadioButton rdoSoda;
private JRadioButton rdoTea;
private JRadioButton rdoBottledWater;
private JRadioButton rdoTapWater;
private JLabel lblDrinks;
private ButtonGroup grpDrinks;
JPanel panelDrinks;
JPanel container;
JButton calculateTotal;
JLabel order;
PizzaGUI()
{
super("Pizza Menu");
setSize(600,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createPanel();
add(container);
setVisible(true);
}
public void createPanel()
{
panelSize = new JPanel(new GridLayout(5, 1));
panelToppings = new JPanel(new GridLayout(5, 1));
panelDrinks = new JPanel(new GridLayout(5, 1));
container = new JPanel(new GridLayout(2,1));
JPanel container2 = new JPanel();
JPanel placedOrderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
//Calculate Total
calculateTotal = new JButton("Calculate");
calculateTotal.setPreferredSize(new Dimension(95,45));
order = new JLabel("Your Order:");
placedOrderPanel.add(new JLabel("Your Order placed"));
//Pizza Sizes
lblSize = new JLabel("Choose a size:");
rdoSmall = new JRadioButton("Small ($7)");
rdoMedium = new JRadioButton("Medium ($9)");
rdoLarge = new JRadioButton("Large ($11)");
rdoExtraLarge = new JRadioButton("Extra Large ($14)");
//Toppings
lblToppings = new JLabel("Choose toppings ($1 Each):");
chkPepperoni = new JCheckBox("Pepperoni");
chkMushrooms = new JCheckBox("Mushrooms");
chkOlives = new JCheckBox("Olives");
chkPineapple = new JCheckBox("Pineapple");
//Drinks
lblDrinks = new JLabel("Choose a drink:");
rdoSoda = new JRadioButton("Soda ($2.00)");
rdoTea = new JRadioButton("Tea ($1.50)");
rdoBottledWater = new JRadioButton("Bottled Water ($1.25)");
rdoTapWater = new JRadioButton("Tap Water (No charge)");
//Add pizza sizes to button group
grpSize = new ButtonGroup();
grpSize.add(rdoSmall);
grpSize.add(rdoMedium);
grpSize.add(rdoLarge);
grpSize.add(rdoExtraLarge);
//Add drinks to button group
grpDrinks = new ButtonGroup();
grpDrinks.add(rdoSoda);
grpDrinks.add(rdoTea);
grpDrinks.add(rdoBottledWater);
grpDrinks.add(rdoTapWater);
//Add to panel
panelSize.add(lblSize);
panelSize.add(rdoSmall);
panelSize.add(rdoMedium);
panelSize.add(rdoLarge);
panelSize.add(rdoExtraLarge);
panelToppings.add(lblToppings);
panelToppings.add(chkPepperoni);
panelToppings.add(chkMushrooms);
panelToppings.add(chkOlives);
panelToppings.add(chkPineapple);
panelDrinks.add(lblDrinks);
panelDrinks.add(rdoSoda);
panelDrinks.add(rdoTea);
panelDrinks.add(rdoBottledWater);
panelDrinks.add(rdoTapWater);
container2.add(panelSize);
container2.add(Box.createHorizontalStrut(40));
container2.add(panelToppings);
container2.add(Box.createHorizontalStrut(40));
container2.add(panelDrinks);
container2.add(calculateTotal);
container2.add(Box.createVerticalStrut(100));
container2.add(order);
container.add(container2);
container.add(placedOrderPanel);
}
public static void main(String args[]) {
new PizzaGUI();
}
}

Java GUI JScrollBar How to set the length?

I have the following GUI codded up but I would like to increase the length of the scroll bar on the right side.
Any Idea How to do this?
// test class that implements the gui stuff.
public class testing
{
//variables
private JFrame f = new JFrame("GUI TEST");
private JPanel p = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p3 = new JPanel();
private JPanel p4 = new JPanel();
private JPanel p5 = new JPanel();
private JPanel p6 = new JPanel();
private JPanel p7 = new JPanel();
private JPanel p8 = new JPanel();
private JPanel p9 = new JPanel();
private JPanel p10 = new JPanel();
private JPanel p11 = new JPanel();
private JButton b1 = new JButton("Button");
private JTextField tf1 = new JTextField(" ");
private JTextField tf2 = new JTextField(" ");
private JTextField tf3 = new JTextField(" ");
private JTextArea ta1 = new JTextArea(10,45);
private JLabel label1 = new JLabel("Label 1");
private JLabel label2 = new JLabel("Label 2");
private JLabel label3 = new JLabel("Label 3");
private JLabel label4 = new JLabel("Label 4");
private JScrollBar sb1 = new JScrollBar();
//class constructor
public testing()
{
gui();
}
public void gui()
{
//change length of scroll bar
f.setVisible(true);
f.setSize(600,300);
p.add(label1);
p.add(tf1);
p2.add(label2);
p2.add(tf2);
p3.add(label3);
p3.add(tf3);
p4.add(sb1);
p4.add(label4);
p5.add(ta1);
p6.add(b1);
p4.setBackground(Color.GRAY);
p9.setBackground(Color.GRAY);
p10.setBackground(Color.GRAY);
p11.setBackground(Color.GRAY);
p9.add(p);
p9.add(p2);
p9.add(p3);
p10.add(p5);
p11.add(p6);
//adds panels to frames
f.add(p4, BorderLayout.EAST);
f.add(p9, BorderLayout.NORTH);
f.add(p10, BorderLayout.CENTER);
f.add(p11, BorderLayout.PAGE_END);
}
public static void main(String[] args)
{
new testing();
}
Ordinarilly, you'd simply add your JTextArea to a JScrollPane, which handles the resizing behavior for you.
f.add(new JScrollPane(ta1), BorderLayout.CENTER);
For demonstration purposes, you can override the getPreferredSize() method of the JScrollBar to see the effect.
private JScrollBar sb1 = new JScrollBar(){
#Override
public Dimension getPreferredSize() {
return new Dimension(
super.getPreferredSize().width, ta1.getPreferredSize().height);
}
};
In addition,
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
Use the appropriate constructor to establish the desired initial size of text components.
Use an appropriate layout to get the desired resizing behavior.
As tested:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Testing {
//variables
private JFrame f = new JFrame("GUI TEST");
private JPanel p = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p3 = new JPanel();
private JPanel p4 = new JPanel();
private JPanel p5 = new JPanel();
private JPanel p6 = new JPanel();
private JPanel p9 = new JPanel();
private JPanel p10 = new JPanel();
private JPanel p11 = new JPanel();
private JButton b1 = new JButton("Button");
private JTextField tf1 = new JTextField(12);
private JTextField tf2 = new JTextField(12);
private JTextField tf3 = new JTextField(12);
private JTextArea ta1 = new JTextArea(10, 45);
private JLabel label1 = new JLabel("Label 1");
private JLabel label2 = new JLabel("Label 2");
private JLabel label3 = new JLabel("Label 3");
private JLabel label4 = new JLabel("Label 4");
private JScrollBar sb1 = new JScrollBar(){
#Override
public Dimension getPreferredSize() {
return new Dimension(super.getPreferredSize().width, ta1.getPreferredSize().height);
}
};
//class constructor
public Testing() {
gui();
}
public void gui() {
p.add(label1);
p.add(tf1);
p2.add(label2);
p2.add(tf2);
p3.add(label3);
p3.add(tf3);
p4.add(sb1);
p4.add(label4);
p5.add(ta1);
p6.add(b1);
p4.setBackground(Color.GRAY);
p9.setBackground(Color.GRAY);
p10.setBackground(Color.GRAY);
p11.setBackground(Color.GRAY);
p9.add(p);
p9.add(p2);
p9.add(p3);
p10.add(p5);
p11.add(p6);
//adds panels to frames
f.add(p4, BorderLayout.EAST);
f.add(p9, BorderLayout.NORTH);
f.add(p10, BorderLayout.CENTER);
f.add(p11, BorderLayout.PAGE_END);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Testing();
});
}
}

how to select JRadioButton depending on button

see my problem start form this piece of code i add all the addActionListener for the button
but when it come to the Radio button it use addItemListenet but i implements ActionListener only how i will implements ItemListener so i can set Law when ever the user Select sw form the radio button and click on add item~ it will add the item to the right array i made before
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
full code
package item;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* #author isslam
*/
public class MyFrameMain extends JFrame{
Equipment newq = new Equipment();
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
public MyFrameMain(String title){
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(MyFrameMain.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15,20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5,1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2,2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5,1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
}
}
}
I'm not sure what array you want to fill but get the text with getText()
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
String s1 = iJTextField.getText();
String s2 = nJTextField.getText();
String s3 = swTextField.getText();
String s4 = hwTextField.getText();
// something with these strings
}
If any of the inputs are numbers and you want the numerical value, you need to parse.
Also, these need to be declared as class memebers. You have them declared in the constructor
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
Declared in the constructor, they are not within the scope of the listener class
public class MyFrameMain extends JFrame{
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
public MyFrameMain(String title){
Also, doesn't really look like you need a listener for the radio button, since an event is not necessary. The JButton listens for an event, and in the actionPerformed, it checks if the radio button is selected. Therefore no need for the radio button to listen for any event, the JButton does that.
Try following code. I ahve added a List item and adding values from swTextField TextFiled to item when user select rButton1 and click on addButton button
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
/**
*
* #author isslam
*/
public class Test extends JFrame {
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1;
java.util.List<String> item = new ArrayList<String>();
public Test(String title) {
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15, 20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
rButton1 = new JRadioButton("SW Version", false);
JRadioButton rButton2 = new JRadioButton("HW Type", false);
JRadioButton rButton3 = new JRadioButton("General", true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5, 1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2, 2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5, 1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener {
public void actionPerformed(ActionEvent a) {
Object buttonPressed = a.getSource();
if (buttonPressed.equals(exitButton)) {
System.exit(0);
}
if (buttonPressed.equals(addButton) && rButton1.isSelected()) {
item.add(swTextField.getText());
System.out.println(item);
}
}
}
public static void main(String args[]) {
Test t = new Test("Test");
t.setVisible(true);
}
}
Use ButtonGroup with the JRadioButton of your context.
Use jRadioButton.setActionCommand(String) to set their corresponding action name: for your context "SW Version" and anything such.
Make use of an ArrayList to add the item of your context. Try mapping each such array list using a HashMap<Key, Val> i.e., HashMap<String, ArrayList<Equipment>> where the "SW Version" or anything such name will be the key
Try adding listeners to each action button in-line using the means of anonymous class.
So a sample coding for add action would become depicting the usage(usefulness) of ButtonGroup:
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = buttonGroup1.getSelection()
.getActionCommand();
// actionCommand = "SW Version"
map.get(actionCmmand).add(equipment);
}
});
Tutorial and reference:
How to use Radio Button, check the demo for ButtonGroup
ButtonGroup class
HashMap

Categories