I have some problems with adding JRadioButton to ButtonGroup and then to JPanel, here is some code:
void modelsRadio () throws SQLException {
JPanel modelsRadioPanel = new JPanel();
Statement statement = db.setConnection();
ResultSet rs = statement.executeQuery("SELECT * FROM МОДЕЛИ");
ButtonGroup modelRadioGroup = new ButtonGroup();
while (rs.next()) {
modelsRadioPanel.add(new JRadioButton(rs.getString("НАЗВАНИЕ")));
//modelRadioGroup.add(new JRadioButton(rs.getString("НАЗВАНИЕ")));
}
frame.add(modelsRadioPanel);
}
The idea is to get data from Oracle SQL Table and create radio's and put data to them, so, I can add them to ButtonGroup but can't add to JPanel. Or, if I don't add them to group and add them to JPanel I can't switch between them normally, they(radio buttons) works like a checkboxes.
You need to add each radio button to the panel and button group as:
void modelsRadio () throws SQLException {
JPanel modelsRadioPanel = new JPanel();
Statement statement = db.setConnection();
ResultSet rs = statement.executeQuery("SELECT * FROM МОДЕЛИ");
ButtonGroup modelRadioGroup = new ButtonGroup();
while (rs.next()) {
JRadioButton jRadioButton =new JRadioButton(rs.getString("НАЗВАНИЕ")));
//Add radio button to the panel
modelsRadioPanel.add(jRadioButton);
//Add radio button to the button group
modelRadioGroup.add(jRadioButton);
//Same for the remaining JRadioButton's
}
// No need to add the button group to the panel
frame.add(modelsRadioPanel);
}
As you create buttons add them both to the ButtonGroup and to the panel. Make sure the same instance of a radio button goes both into the panel and the button group. In your code you create one instance for the panel and one instance for the group. Here is a basic example:
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class TestRadio {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("TestRadio");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
ButtonGroup modelRadioGroup = new ButtonGroup();
for (int i = 0; i < 5; i++) {
JRadioButton b1 = new JRadioButton("Radio" + i);
modelRadioGroup.add(b1);
panel.add(b1);
}
f.add(panel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
See How to Use the ButtonGroup Component for details.
Hmm, I solve it like this:
void modelsRadio () throws SQLException {
JPanel modelsRadioPanel = new JPanel();
Statement statement = db.setConnection();
ResultSet rs = statement.executeQuery("SELECT * FROM МОДЕЛИ");
ButtonGroup modelRadioGroup = new ButtonGroup();
while (rs.next()) {
JRadioButton jr = new JRadioButton(rs.getString("НАЗВАНИЕ"));
//modelRadioGroup.add(new JRadioButton(rs.getString("НАЗВАНИЕ")));
modelRadioGroup.add(jr);
modelsRadioPanel.add(jr);
}
frame.add(modelsRadioPanel);
}
Related
This project revolves around a game that is a variation of TicTacToe called SOS. One of the requirements is that the game grid needs to have two size options. The smaller grid is 5x5 and the larger is 8x8.
My goal is to have the grid size change based off which radio button is selected. In my code below I have a commented out method to change the GRID_SIZE variable based off which radio button is selected. But it does not work where it is currently and I am struggling to come up with the solution. The other problem related to the grid size changing that I think I'll have is, I do not believe the way I create the grid now will allow for it to change live as the radio buttons are pushed.
I will need to be keeping track of what gets played in each cell of the grid (whether a player is placing an S or an O) So my thought is maybe there is a better way to create the grid for both the GUI and as a storage method for the moves played.
This project is my first java project and first GUI project of this depth. It is also the major project for one of my last classes to graduate so I'm taking this seriously and could really use the help. I know my code is probably not great, I'm here to improve so any help is welcomed.
package practice;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings({ "serial", "unused"})
public class SOS_GUI extends JFrame {
public int GRID_SIZE = 8;
public Grid grid;
public SOS_GUI() {
GameBoard();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setTitle("SOS Practice");
this.setLocationRelativeTo(null);
setVisible(true);
}
public void GameBoard(){
// CONTENT PANE FOR HOLDING ALL GUI COMPONENTS
Container ContentPane = getContentPane();
// PANEL FOR GAME GRID
JPanel gameBoardCanvas = new JPanel();
gameBoardCanvas.setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
final Grid cell = new Grid(x, y);
gameBoardCanvas.add(cell);
}
}
// FOUR PANELS SURROUNDING GAME GRID
JPanel TopPanel = new JPanel();
JPanel BottomPanel = new JPanel();
JPanel LeftPanel = new JPanel();
JPanel RightPanel = new JPanel();
JLabel SpacerLabel = new JLabel(" || ");
// GAME MODE OOPTIONS - SIMPLE OR GENERAL
JLabel GameModeLabel = new JLabel("Game Mode :");
JRadioButton SimpleGameButton = new JRadioButton("Simple", true);
JRadioButton GeneralGameButton = new JRadioButton("General");
ButtonGroup GameModeButtons = new ButtonGroup();
GameModeButtons.add(SimpleGameButton);
GameModeButtons.add(GeneralGameButton);
// BOARD SIZE BUTTONS - SMALL(5X5) OR LARGE(8X8)
JLabel SizeOptionLabel = new JLabel("Board Size :");
JRadioButton SmallGridButton = new JRadioButton("Small", true);
JRadioButton LargeGridButton = new JRadioButton("Large");
ButtonGroup GridSizeButtons = new ButtonGroup();
GridSizeButtons.add(SmallGridButton);
GridSizeButtons.add(LargeGridButton);
// PLAY LETTER SETTINGS
JRadioButton PlayS_Button = new JRadioButton("S", true);
JRadioButton PlayO_Button = new JRadioButton("O");
ButtonGroup PlayLetterButtons = new ButtonGroup();
PlayLetterButtons.add(PlayS_Button);
PlayLetterButtons.add(PlayO_Button);
// BLUE PLAYER SETTINGS
JLabel BluePlayerLabel = new JLabel("Blue Player");
JRadioButton BlueHumanButton = new JRadioButton("Human", true);
JRadioButton BlueComputerButton = new JRadioButton("Computer");
ButtonGroup BluePlayerButtons = new ButtonGroup();
BluePlayerButtons.add(BlueHumanButton);
BluePlayerButtons.add(BlueComputerButton);
// RED PLAYER SETTINGS
JLabel RedPlayerLabel = new JLabel("Red Player");
JRadioButton RedHumanButton = new JRadioButton("Human");
JRadioButton RedComputerButton = new JRadioButton("Computer", true);
ButtonGroup RedPlayerButtons = new ButtonGroup();
RedPlayerButtons.add(RedHumanButton);
RedPlayerButtons.add(RedComputerButton);
// ADDING COMPONENTS TO TOP PANEL
TopPanel.add(GameModeLabel);
TopPanel.add(SimpleGameButton);
TopPanel.add(GeneralGameButton);
TopPanel.add(SpacerLabel);
TopPanel.add(SizeOptionLabel);
TopPanel.add(SmallGridButton);
TopPanel.add(LargeGridButton);
// ADDING COMPONENTS TO BOTTOM PANEL
BottomPanel.add(PlayS_Button);
BottomPanel.add(PlayO_Button);
// ADDING COMPONENTS TO LEFT PANEL
LeftPanel.add(BluePlayerLabel);
LeftPanel.add(BlueHumanButton);
LeftPanel.add(BlueComputerButton);
// ADDING COMPONENTS TO RIGHT PANEL
RightPanel.add(RedPlayerLabel);
RightPanel.add(RedHumanButton);
RightPanel.add(RedComputerButton);
// ADDING PANELS TO CONTENT PANE
ContentPane.setLayout(new BorderLayout());
ContentPane.add(TopPanel, BorderLayout.NORTH);
ContentPane.add(BottomPanel, BorderLayout.SOUTH);
ContentPane.add(LeftPanel, BorderLayout.WEST);
ContentPane.add(RightPanel, BorderLayout.EAST);
ContentPane.add(gameBoardCanvas, BorderLayout.CENTER);
TopPanel.setPreferredSize(new Dimension(50, 50));
BottomPanel.setPreferredSize(new Dimension(50, 50));
LeftPanel.setPreferredSize(new Dimension(100, 100));
RightPanel.setPreferredSize(new Dimension(100, 100));
ContentPane.setPreferredSize(new Dimension(550, 500));
}
// CLASS SETTING UP HOW THE GRID WILL BE CREATED
class Grid extends JPanel {
public static final int CELL_SIZE = 1;
private int xPos;
private int yPos;
public JLabel gridLabel;
public Grid (int x, int y) {
xPos = x;
yPos = y;
gridLabel = new JLabel("");
gridLabel.setFont(new Font("Serif", Font.BOLD, 40));
add(gridLabel);
setOpaque(true);
setLayout(new FlowLayout());
setBorder(BorderFactory.createBevelBorder(CELL_SIZE));
setBackground(new Color(200, 200, 200));
setPreferredSize(new Dimension(CELL_SIZE, CELL_SIZE));
}
}
/* POSSIBLE FUNCTION TO SET GRID_SIZE BASED OFF RADIO BUTTON INPUT? DOESNT WORK HERE
public getGridSize() {
if (GameBoard().SmallGridButton.isSelected() == true) {
GRID_SIZE = 5;
}
else if (GameBoard().LargeGridButton.isSelected() == true) {
GRID_SIZE = 8;
}
return GRID_SIZE;
}
*/
public static void main(String[] args) {
new SOS_GUI();
}
}
screenshot of the smaller 5x5 grid
screenshot of larger 8x8 grid
Again, I suggest that if you want to use components as your grid cell, that you either swap views (JPanels) using a CardLayout, or you swap out the grid cells when a JRadioButton is pressed.
I suggest:
Adding an ActionListener to the JRadioButton to be notified when it is pressed.
If you will swap components, then create a JPanel to hold the grid cells, say called gridHolder, and remove all components when the button is pressed.
Then add a new GridLayout layout manager to this JPanel, with constraints set depending on whih JRadioButton has been pressed.
Then re-adding grid cell components to this holder JPanel
Then relaying out all components in the GUI and resizing it by calling pack() on the top-level window, here a JFrame.
In the example below, I use JLabels to hold the grid cells since it is trivial to add text to these.
I store the row and column of each grid cell using the .putClientProperty(...) method and likewise can retrieve values using the .getClientProperty(...) method.
I call createGrid(...) in the constructor to create the grid with the default, small, size.
I call the same method whenever a JRadioButton has been pressed.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.border.BevelBorder;
#SuppressWarnings("serial")
public class SosGrid2 extends JPanel {
private static final int SMALL_SIZE = 5;
private static final int LARGE_SIZE = 8;
private static final String[] SIZES = { "Small", "Large" };
private static final Dimension CELL_SIZE = new Dimension(60, 60);
private static final Color GRID_BG = new Color(200, 200, 200);
private static final String ROW = "row";
private static final String COL = "col";
private JPanel gridHolder = new JPanel();
private ButtonGroup gridSizeGroup = new ButtonGroup();
public SosGrid2() {
JPanel radioButtonPanel = new JPanel();
for (String size : SIZES) {
JRadioButton radioButton = new JRadioButton(size);
radioButton.setSelected(size.equals(SIZES[0]));
radioButton.setActionCommand(size);
gridSizeGroup.add(radioButton);
radioButtonPanel.add(radioButton);
radioButton.addActionListener(e -> radioListener());
}
createGrid(SMALL_SIZE);
setLayout(new BorderLayout());
add(gridHolder);
add(radioButtonPanel, BorderLayout.PAGE_END);
}
private void createGrid(int gridSize) {
gridHolder.removeAll();
gridHolder.setLayout(new GridLayout(gridSize, gridSize));
for (int row = 0; row < gridSize; row++) {
for (int col = 0; col < gridSize; col++) {
JLabel gridCell = createGridCell(row, col);
gridHolder.add(gridCell);
}
}
}
// factory method to create grid cell JLabels.
private JLabel createGridCell(int row, int col) {
JLabel label = new JLabel("", SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, 32f));
label.setOpaque(true);
label.setBackground(GRID_BG);
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
label.setPreferredSize(CELL_SIZE);
label.putClientProperty(ROW, row);
label.putClientProperty(COL, col);
label.addMouseListener(new MyMouseListener());
return label;
}
private class MyMouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
JLabel gridCell = (JLabel) e.getSource();
int row = (int) gridCell.getClientProperty(ROW);
int col = (int) gridCell.getClientProperty(COL);
String message = String.format("Row: %d, Col: %d", row, col);
String title = "Cell Pressed";
int type = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(SosGrid2.this, message, title, type);
String text = gridCell.getText();
if (text.isEmpty()) {
gridCell.setText("X");
} else {
gridCell.setText("");
}
}
}
private void radioListener() {
ButtonModel btnModel = gridSizeGroup.getSelection();
if (btnModel != null) {
int gridSize = btnModel.getActionCommand().equals(SIZES[0]) ? SMALL_SIZE : LARGE_SIZE;
createGrid(gridSize);
Window jframe = SwingUtilities.getWindowAncestor(this);
jframe.pack();
jframe.setLocationRelativeTo(null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SosGrid2 mainPanel = new SosGrid2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
I want sort the JTable by the JRadioButton component's ActionListener method. When I click "name" the table will sorted out by name. But now I click name radio button, all is blank.
The Main code for query the database all is fine. So I have problem for add another table to the JScrollPane. For the simplicity, I deleted all the import related code. But all the code is working except the radio button's action listener.
public class JtableDemo extends JPanel implements ActionListener {
private static JFrame frame;
JTextField textField;
JScrollPane scrollPanel;
JRadioButton nameButton = new JRadioButton("name");
JRadioButton departmentButton =new JRadioButton("department");
JRadioButton salaryButton =new JRadioButton("Salary");
JRadioButton dateButton = new JRadioButton("date");
ButtonGroup orderbyButtonGroup = new ButtonGroup();
JTable jTable = new JTable();
String orderbyname = "select * from emp where salary >6000 order by name";
String orderbydepartment = "select * from emp where salary >6000 order by department";
String orderbysalary = "select * from emp where salary >6000 order by salary";
public JtableDemo() throws SQLException {
nameButton.addActionListener(this);
departmentButton.addActionListener(this);
salaryButton.addActionListener(this);
dateButton.addActionListener(this);
orderbyButtonGroup.add(nameButton);
orderbyButtonGroup.add(departmentButton);
orderbyButtonGroup.add(salaryButton);
orderbyButtonGroup.add(dateButton);
this.add(nameButton);
this.add(departmentButton);
this.add(salaryButton);
this.add(dateButton);
String query = "select * from emp where salary>? ";
PreparedStatement statement = Main.connection.prepareStatement(query);
statement.setInt(1,6000);
//statement.setString(2,"id");
ResultSet resultSet = statement.executeQuery();
jTable.setModel(DbUtils.resultSetToTableModel(resultSet));
jTable.setPreferredScrollableViewportSize(new Dimension(500,200));
jTable.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(jTable);
add(scrollPane);
String title = "all emp's salary less than 5600";
this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),title, TitledBorder.CENTER,TitledBorder.TOP));
}
public static void createandShowGUI() throws SQLException {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JtableDemo newContentPane = new JtableDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==nameButton) {
try {
JScrollPane scrollPane = new JScrollPane(jTable);
PreparedStatement orderbystatement = Main.connection.prepareStatement(orderbyname);
//orderbystatement.setString(1,"name");
ResultSet resultSet = orderbystatement.executeQuery();
jTable.setModel(DbUtils.resultSetToTableModel(resultSet));
jTable.setPreferredScrollableViewportSize(new Dimension(500,200));
jTable.setFillsViewportHeight(true);
} catch (SQLException throwables) {
throwables.printStackTrace();
} }
if(e.getSource()==departmentButton) { System.out.println("testdepartmentButton"); }
if(e.getSource()==salaryButton) { System.out.println("testsalaryButton"); }
if(e.getSource()==dateButton) { System.out.println("testdateButton"); }
}
}
So I'm making a program that finds out the surface area and the volume of polyhedrons, so I need to use JRadioButtons to let the user select what shape they want, if they want SurfaceArea or Volume, and stuff like that.
However, I ran into a problem that requires me to make something run every time that a new button is clicked.
When I added an actionListener() to my JRadioButton, the actionPerformed() method didn't even run. Is there something that I am missing?
I want my actionPerformed()method to run.
width.addActionListener(ral);
height.addActionListener(ral);
length.addActionListener(ral);
slantHeight.addActionListener(ral);
radius.addActionListener(ral);
displayAnswer.addActionListener(ral);
public void actionPerformed(ActionEvent a) {
System.out.println("Changed Radio Button: " + a.getSource());
}
From How to Write an Item Listener (emphasis mine):
Item events are fired by components that implement the ItemSelectable interface. Generally, ItemSelectable components maintain on/off state for one or more items.
Since a radio button fits this description, ItemListener would be a more suitable listener to use; try that instead.
Hope this helps!
Just FYI, this is what I mean by a small-"ish" compilable runnable program that demonstrates a problem. Here I demonstrate not adding action listeners or any listeners to JRadioButtons but rather adding a single listener to a JButton (actually an AbstractAction which is like an ActionListener on steroids). This uses ButtonGroup objects to allow only one JRadioButton to be selected per group, and to allow the code to query which button was selected. The ButtonGroup will return the "model" for the selected JRadioButton, and then we extract the actionCommand String from this model:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MyMcve extends JPanel {
private static final String[] SHAPES = {
"Circle", "Square", "Triangle"
};
private static final String[] COLORS = {
"Red", "Orange", "Yellow", "Green", "Blue"
};
private ButtonGroup shapeButtonGroup = new ButtonGroup();
private ButtonGroup colorButtonGroup = new ButtonGroup();
public MyMcve() {
JPanel shapesBtnPanel = new JPanel(new GridLayout(0, 1));
shapesBtnPanel.setBorder(BorderFactory.createTitledBorder("Shapes"));
for (String shape : SHAPES) {
JRadioButton radioButton = new JRadioButton(shape);
radioButton.setActionCommand(shape);
shapeButtonGroup.add(radioButton);
shapesBtnPanel.add(radioButton);
}
JPanel colorsBtnPanel = new JPanel(new GridLayout(0, 1));
colorsBtnPanel.setBorder(BorderFactory.createTitledBorder("Colors"));
for (String color : COLORS) {
JRadioButton radioButton = new JRadioButton(color);
radioButton.setActionCommand(color);
colorButtonGroup.add(radioButton);
colorsBtnPanel.add(radioButton);
}
JPanel bothButtonPanel = new JPanel(new GridLayout(1, 2));
bothButtonPanel.add(shapesBtnPanel);
bothButtonPanel.add(colorsBtnPanel);
JButton getSelectionBtn = new JButton(new GetSelectionAction("Get Selection"));
JPanel btnPanel = new JPanel();
btnPanel.add(getSelectionBtn);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout());
add(bothButtonPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private class GetSelectionAction extends AbstractAction {
public GetSelectionAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
String shapeSelection = "";
String colorSelection = "";
ButtonModel shapeModel = shapeButtonGroup.getSelection();
if (shapeModel != null) {
shapeSelection = shapeModel.getActionCommand();
}
ButtonModel colorModel = colorButtonGroup.getSelection();
if (colorModel != null) {
colorSelection = colorModel.getActionCommand();
}
System.out.println("Selected Shape: " + shapeSelection);
System.out.println("Selected Color: " + colorSelection);
}
}
private static void createAndShowGui() {
MyMcve mainPanel = new MyMcve();
JFrame frame = new JFrame("MCVE");
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();
}
});
}
}
I'm writing a small body weight program for my assignment. I have 2 JRadioButton for gender, and five JRadioButtons for the heightt categories. I added an ActionListener for each of these buttons.
In the actionPerformed function, how can I put an an if() condition that lets me decide on the ideal weight based on both the gender and the height?
if(e.getSource() == genderM && e.getSource() == h60 )
doesn't seem to be working.
The problem specifically states that it should be done without a submit button.
This is the code im working with:
public class IdealWeight extends JFrame implements ActionListener {
JLabel lblHeight;
JLabel lblGender;
JLabel lblIdeal;
JRadioButton genderM;
JRadioButton genderF;
JRadioButton h60;
JRadioButton h64;
JRadioButton h68;
JRadioButton h72;
JRadioButton h76;
JTextField txtIdealWeight;
public IdealWeight(){
super("Ideal Wight");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
p1.setLayout(new GridLayout(3,1));
p2.setLayout(new GridLayout(6,1));
lblGender = new JLabel("Your gender: ");
lblHeight = new JLabel("Your height: ");
lblIdeal = new JLabel("Your ideal weight: ");
this.setLayout(new GridLayout(2,3));
ButtonGroup genderGroup = new ButtonGroup();
ButtonGroup weightGroup = new ButtonGroup();
genderM = new JRadioButton("Male: ");
genderM.addActionListener(this);
genderF = new JRadioButton("Female: ");
genderF.addActionListener(this);
h60 = new JRadioButton("60 to 64 inches");
h60.addActionListener(this);
h64 = new JRadioButton("64 to 68 inches");
h64.addActionListener(this);
h68 = new JRadioButton("68 to 72 inches");
h68.addActionListener(this);
h72 = new JRadioButton("72 to 76 inches");
h72.addActionListener(this);
h76 = new JRadioButton("76 to 80 inches");
h76.addActionListener(this);
txtIdealWeight = new JTextField();
txtIdealWeight.setEditable(false);
txtIdealWeight.setColumns(5);
genderGroup.add(genderM);
genderGroup.add(genderF);
weightGroup.add(h60);
weightGroup.add(h64);
weightGroup.add(h68);
weightGroup.add(h72);
weightGroup.add(h76);
p1.add(lblGender);
p1.add(genderM);
p1.add(genderF);
p2.add(lblHeight);
p2.add(h60);
p2.add(h64);
p2.add(h68);
p2.add(h72);
p2.add(h76);
p3.add(lblIdeal);
p3.add(txtIdealWeight);
this.add(p1);
this.add(p2);
this.add(p3);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(new Dimension(400,400));
}
Since the user needs to enter information in all fields before it can be accurately processed, I'd not use ActionListeners on your JCheckBoxes or JRadioButtons, but rather have a single JButton, say called submitButton and then extract the data from your GUI within its ActionListener.
You can get the selected item from each of the ButtonGroup objects that you're using, since it will return the ButtonModel of the JRadioButton selected, or null if nothing has been selected.
If you need more help -- please ask and also edit your question to show us more pertinent code.
Edit
You state in comment:
The problem specifically states that it should be done without a submit button
This is key information that should be part of your original question.
Then use one single ActionListener, and don't worry about the source. Instead in the ActionListener, either query all the JRadioButtons as to their state, and then act on it, or get the models out of your ButtonGroups and do the same.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TwoButtonGroups extends JPanel {
public static final String[] LABELS_1 = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
public static final String[] LABELS_2 = {"Fubar", "Snafu", "DILLIGAF"};
private ButtonGroup buttonGroup1 = new ButtonGroup();
private ButtonGroup buttonGroup2 = new ButtonGroup();
public TwoButtonGroups() {
JPanel panel1 = new JPanel(new GridLayout(0, 1));
JPanel panel2 = new JPanel(new GridLayout(0, 1));
MyActionListener myActionListener = new MyActionListener();
for (String label1 : LABELS_1) {
JRadioButton radioButton = new JRadioButton(label1);
radioButton.setActionCommand(label1);
radioButton.addActionListener(myActionListener);
buttonGroup1.add(radioButton);
panel1.add(radioButton);
}
for (String label2 : LABELS_2) {
JRadioButton radioButton = new JRadioButton(label2);
radioButton.setActionCommand(label2);
radioButton.addActionListener(myActionListener);
buttonGroup2.add(radioButton);
panel2.add(radioButton);
}
add(panel1);
add(panel2);
}
private class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model1 = buttonGroup1.getSelection();
ButtonModel model2 = buttonGroup2.getSelection();
if (model1 == null || model2 == null) {
return; // not selected
}
System.out.printf("Selections: %s and %s%n", model1.getActionCommand(), model2.getActionCommand() );
}
}
private static void createAndShowGui() {
TwoButtonGroups mainPanel = new TwoButtonGroups();
JFrame frame = new JFrame("TwoButtonGroups");
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();
}
});
}
}
The condition
e.getSource() == genderM && e.getSource() == h60
Can never return true because the source is either genderM or h60. Perhaps you meant logical OR.
e.getSource() == genderM || e.getSource() == h60
As an alternative, I'd ignore the source of the event, and use the state of the components instead..
#Override
public void actionPerformed(ActionEvent e) {
if (genderM.isSelected() && h60.isSelected()) {
}
}
I am trying to repaint a panel with a button click, but its not happening. i tried using many methods like setEnabled(true), setVisible(true), repaint(), but none of these are working. And also i want to switch between two panels, like, if i click the "Total Vote" button, one panel should display, when i click on "Departmentwise Vote", another panel should display in the same place.
please help. Thanks in advance.
here i m providing the code :
public class RSummary extends JFrame implements ActionListener
{
JFrame rframe = new JFrame();
JPanel panel1, panel2, panel3, panel4, panel5;
JTable table;
JScrollPane scroll;
JSplitPane splitPane;
JButton butx;
public RSummary()
{
rframe.setSize(550,300);
rframe.setLocationRelativeTo(null);
setSize(550,300);
rframe.setTitle("Summary Report");
/* Total Vote & Department wise vote buttons */
panel1= new JPanel();
JButton but1 = new JButton("TOTAL VOTE");
JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
but1.addActionListener(this);
panel1.add(but1);
panel1.add(but2);
/* Report contents according to button */
panel2 = new JPanel();
String[] columnNames = {"Name", "Department","Phno","LUID","Select"};
DefaultTableModel model1 = new DefaultTableModel();
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel2.setVisible(false);
/* close button */
panel3 = new JPanel();
JButton but4= new JButton("CLOSE");
but4.addActionListener(this);
panel3.add(but4);
/* Page heading */
panel4 = new JPanel();
JLabel lab =new JLabel("VOTE SUMMARY REPORT");
panel4.add(lab);
/* dummy panel */
panel5 = new JPanel();
JButton butx = new JButton("Hello butx");
panel5.add(butx);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
rframe.add(splitPane);
rframe.add(panel3,BorderLayout.SOUTH);
rframe.add(panel4,BorderLayout.NORTH);
rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rframe.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String action=ae.getActionCommand();
if(action == "CLOSE")
{
rframe.setVisible(false);
}
if(action == "TOTAL VOTE")
{
panel2.setVisible(true); //this code is not working, i want the solution here.
}
}
public static void main(String args[]) throws ClassNotFoundException, SQLException
{
new RSummary();
}
}
The first problem is you're comparing the object references of your String values and not there contents...
if(action == "TOTAL VOTE")
Because of the way Strings are managed by Java, it is very unlikely that these will ever be equal.
String comparison in Java is done using String#equals
if ("TOTAL VOTE".equals(action))
Your second problem may be related to the fact the setVisible may not be invalidating the container hierarchy, which would tell the layout framework that the containers need to be updated.
You have two solutions, the first would be to call revalidate on the parent container, the second, and better, would be to use a CardLayout, which is designed to just what you are trying to do...
Take a look at How to use Card Layout for more details
Update after running the Code
You have a series of compounding issues...
You never set the action command of any of the buttons, so when the actionPerformed event is raised, the action is actually null
RSummary extends from JFrame, yet you create a second JFrame called rframe. This is very confusing and could potentially lead to more problems if you're not dealing with the correct frame.
Start by setting the actionCommand property of your buttons...
JButton but1 = new JButton("TOTAL VOTE");
but1.setActionCommand("TOTAL VOTE");
Then remove extends JFrame from RSummary, as it is doing nothing but adding to the confusion and adds no benefit
Setting a frame invisible will not "close" it. Instead use JFrame#dispose
Finally, making a component visible while it's part of split pane won't resize the split divider. Once you've made the corrections, you will need to manually move the divider.
You may consider placing a empty panel into the split pane and using a CardLayout, add the other components to it, switching them in and out using the CardLayout
Updated with modified code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class RSummary extends JFrame implements ActionListener {
JFrame rframe = new JFrame();
JPanel panel1, panel2, panel3, panel4, panel5;
JTable table;
JScrollPane scroll;
JSplitPane splitPane;
JButton butx;
public RSummary() {
rframe.setSize(550, 300);
rframe.setLocationRelativeTo(null);
setSize(550, 300);
rframe.setTitle("Summary Report");
/* Total Vote & Department wise vote buttons */
panel1 = new JPanel();
JButton but1 = new JButton("TOTAL VOTE");
but1.setActionCommand("TOTAL VOTE");
JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
but1.addActionListener(this);
panel1.add(but1);
panel1.add(but2);
/* Report contents according to button */
panel2 = new JPanel();
String[] columnNames = {"Name", "Department", "Phno", "LUID", "Select"};
DefaultTableModel model1 = new DefaultTableModel();
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel2.setVisible(false);
/* close button */
panel3 = new JPanel();
JButton but4 = new JButton("CLOSE");
but4.addActionListener(this);
panel3.add(but4);
/* Page heading */
panel4 = new JPanel();
JLabel lab = new JLabel("VOTE SUMMARY REPORT");
panel4.add(lab);
/* dummy panel */
panel5 = new JPanel();
JButton butx = new JButton("Hello butx");
panel5.add(butx);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
rframe.add(splitPane);
rframe.add(panel3, BorderLayout.SOUTH);
rframe.add(panel4, BorderLayout.NORTH);
rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rframe.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
if ("CLOSE".equals(action)) {
rframe.dispose();
}
if ("TOTAL VOTE".equals(action)) {
panel2.setVisible(true); //this code is not working, i want the solution here.
panel2.getParent().revalidate();
}
}
public static void main(String args[]) throws ClassNotFoundException, SQLException {
new RSummary();
}
}
To switch panels you can do:
rframe.remove (panelToRemove);
rframe.add(panelToShow);
Is this the answer to your question or why do you want to repaint?
Geosearchef
UPDATE:
To summarize:
MadProgrammer is right, you have to replace if(action == "TOTAL VOTE") by if(action.equals("TOTAL VOTE")) (same for CLOSE)
and you have to add an actionCommand:
JButton but1 = new JButton("TOTAL VOTE");
but1.addActionListener(this);
but1.setActionCommand("TOTAL VOTE");
To change panels:
if (action.equals("TOTAL VOTE")) {
try{rframe.remove(panel1;)}catch(Exception e){}//clear window, maybe there is a method
try{rframe.remove(panel2;)}catch(Exception e){}
try{rframe.remove(panel3;)}catch(Exception e){}
rframe.add(panel2);//the panel you want to show
}
Of course, you have to get references to the panels to actionPerformed(ActionEvent ae).