Sort the JTable by JRadioButton - java

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"); }
}
}

Related

I need to add another column in my database but I don't know how to

I want to add another column in mysql either by using java or manually in the mysql application. This is my java code and I need to add a column named book_id
package liblog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class AStudents extends JFrame {
private JTextField admissionnumber;
private JTextField firstname;
private JTextField lastname;
private JTextField surname;
private JTextField house;
private JTextField dome;
private JButton add;
private JButton back;
private static Connection conn;
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("C:/Users/User/workspace/Login/src/liblog/parklands.png");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel admissionNumber = new JLabel();
JLabel firstName = new JLabel();
JLabel lastName = new JLabel();
JLabel surName = new JLabel();
JLabel mainHouse = new JLabel();
JLabel mainDome = new JLabel();
AStudents(){
super("DR.RIBEIRO PARKLANDS SCHOOL");
setLayout(new FlowLayout(FlowLayout.LEFT,3,100));
setBounds(500,500,550,550);
setLocation(500,200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container con = this.getContentPane();
con.setBackground(Color.GRAY);
con.add(panel);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER,3,10));/*X axis,Y axis*/
panel3.setLayout(new BoxLayout(panel,BoxLayout.LINE_AXIS));
panel.setBackground(Color.GRAY);
/* admissionNumber=new JLabel("Admission Number");
admissionNumber.setAlignmentX(0.0f);
admissionnumber = new JTextField("No",30);
admissionnumber.setAlignmentX(0.0f);*/
firstName=new JLabel("First Name");
firstName.setAlignmentX(0.0f);
firstname = new JTextField("Name",20);
firstname.setAlignmentX(0.0f);
lastName=new JLabel("Last Name");
lastName.setAlignmentX(0.0f);
lastname = new JTextField("Name",20);
lastname.setAlignmentX(0.0f);
surName=new JLabel("Surname");
surName.setAlignmentX(0.0f);
surname = new JTextField("Name",20);
surname.setAlignmentX(0.0f);
mainHouse=new JLabel("House");
mainHouse.setAlignmentX(0.0f);
house = new JTextField("House",20);
house.setAlignmentX(0.0f);
mainDome=new JLabel("Dome");
mainDome.setAlignmentX(0.0f);
dome = new JTextField("Dome",20);
dome.setAlignmentX(0.0f);
add = new JButton("Add Student");
back = new JButton("Back");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert into SQL:
try {
PreparedStatement insert = conn.prepareStatement("INSERT INTO students (first_name, last_name, surname, house, dome) VALUES (?,?,?,?,?)");
insert.setString(1, firstname.getText());
insert.setString(2, lastname.getText());
insert.setString(3, surname.getText());
insert.setString(4, house.getText());
insert.setString(5, dome.getText());
insert.execute();
ABooks abooks = new ABooks();
dispose();
}
catch(Exception ex) {
System.out.println(ex);
}
}
});
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Admin admin = new Admin();
dispose();
}
});
//panel.add(admissionNumber);
//panel.add(admissionnumber);
panel.add(firstName);
panel.add(firstname);
panel.add(lastName);
panel.add(lastname);
panel.add(surName);
panel.add(surname);
panel.add(mainHouse);
panel.add(house);
panel.add(mainDome);
panel.add(dome);
panel.add(add);
panel.add(back);
try {
conn = getConnection();
createTable();
}
catch(Exception ex) {
System.out.println(ex);
}
setVisible(true);
}
/*public static void main(String[]args) throws Exception{new AStudents();
createTable();
}*/
//Table
public static void createTable() throws Exception{
try{
Connection conn = getConnection();
PreparedStatement create = conn.prepareStatement("CREATE TABLE IF NOT EXISTS students(id int NOT NULL AUTO_INCREMENT,first_name varchar(45),last_name varchar(45),surname varchar(320),house varchar(50),dome varchar(50),book_id varchar(50),PRIMARY KEY(id))");
create.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally {
System.out.println("System Updated");};
}
//EndofTable
//DB
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/students?useSSL=false";
String username = "root";
String password = "toor";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
}catch(Exception e){
System.out.println(e);
}
return null;
}
//DB
}
The application is giving me the following error which I cannot get rid of
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'borrow_id' in 'field list'
This is the other code http://www.rapidtables.com/tools/notepad.htm
In your SQL DB:
ALTER TABLE students ADD book_id varchar(50)
I'm guessing as to the datatype of the book_id.
Do you mean book_id or borrow_id? I don't see borrow_id in your code which is somewhat confusing and probably why you're getting down voted.

having NullPointerException in JTable using MouseListener event

I am new to java and I am trying to build a simple project that connects
to database then display it on JTable with MouseClick event. When i click in the row to transfer its content to JTextFields but it returns NullPointerException in line 225. Here's the full code of my project:
package Dbase;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
#SuppressWarnings("serial")
public class MainForm extends JFrame {
Connection con;
Statement stmt;
ResultSet rs;
PreparedStatement pstmt;
#SuppressWarnings("rawtypes")
Vector columnNames = new Vector();
#SuppressWarnings("rawtypes")
Vector data = new Vector();
//JTable table;
private JPanel gui;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm frame = new MainForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
setLookAndFeel();
setSize(800,500);
gui = new JPanel();
gui.setLayout(new BorderLayout(5, 5));
setContentPane(gui);
DBConnect();
initComponents();
tbData();
}
public void DBConnect(){
try{
String host = "jdbc:mysql://localhost:3306/birthdb";
String uName = "admin";
String uPass = "46m1n";
// connection to mysql database
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo";
rs = stmt.executeQuery(sql);
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
private void initComponents(){
//child's information
JLabel lblfirstName = new JLabel("FirstName", JLabel.RIGHT);
JLabel lbllastName = new JLabel("LastName", JLabel.RIGHT);
JLabel lblmiddleName = new JLabel("MiddleName", JLabel.RIGHT);
JLabel lblbirthDate = new JLabel("BirthDate",JLabel.RIGHT);
JLabel lblgender = new JLabel("Gender",JLabel.RIGHT);
JLabel lblbirthType = new JLabel("BirthType", JLabel.RIGHT);
JLabel lblmultiBirth = new JLabel("If Multiple Birth, Child Was", JLabel.RIGHT);
JLabel lblbirthOrder = new JLabel("BirthOrder", JLabel.RIGHT);
JLabel lblbirthWeight = new JLabel("BirthWeight",JLabel.RIGHT);
JLabel lblregistry = new JLabel("Registry",JLabel.RIGHT);
JTextField txtfirstName = new JTextField();
JTextField txtlastName = new JTextField();
JTextField txtmiddleName = new JTextField();
JTextField txtbirthDate = new JTextField();
JTextField txtgender = new JTextField();
JTextField txtbirthType = new JTextField();
JTextField txtmultiBirth = new JTextField();
JTextField txtbirthOrder = new JTextField();
JTextField txtbirthWeight = new JTextField();
JTextField txtregistry = new JTextField();
JButton newData = new JButton("New");
JButton updateData = new JButton("Update");
JButton deleteData = new JButton("Delete");
JButton printData = new JButton("Print");
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//trial menu
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menuBar.add(menu);
//trial menu item
menuItem = new JMenuItem("Quit");
menuItem.setMnemonic(KeyEvent.VK_Q);
menu.add(menuItem);
//trial row panel
JPanel row = new JPanel(new GridLayout(6,4,5,10));
row.add(lblregistry);
txtregistry.setEditable(false);
row.add(txtregistry);
row.add(lblfirstName);
txtfirstName.setEditable(false);
row.add(txtfirstName);
row.add(lbllastName);
txtlastName.setEditable(false);
row.add(txtlastName);
row.add(lblmiddleName);
txtmiddleName.setEditable(false);
row.add(txtmiddleName);
row.add(lblgender);
txtgender.setEditable(false);
row.add(txtgender);
row.add(lblbirthDate);
txtbirthDate.setEditable(false);
row.add(txtbirthDate);
row.add(lblbirthType);
txtbirthType.setEditable(false);
row.add(txtbirthType);
row.add(lblmultiBirth);
txtmultiBirth.setEditable(false);
row.add(txtmultiBirth);
row.add(lblbirthOrder);
txtbirthOrder.setEditable(false);
row.add(txtbirthOrder);
row.add(lblbirthWeight);
txtbirthWeight.setEditable(false);
row.add(txtbirthWeight);
gui.add(row, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new BorderLayout(3,3));
gui.add(buttonPanel,BorderLayout.WEST);
JPanel btn = new JPanel(new GridLayout(6,1,5,5));
btn.add(newData);
btn.add(updateData);
btn.add(deleteData);
btn.add(printData);
buttonPanel.add(btn);
}
#SuppressWarnings("unchecked")
private void tbData(){
try{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT ChildID, FirstName, LastName, MiddleName FROM childinfo";
rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for(int i = 1; i <= columns; ++i){
columnNames.add(md.getColumnName(i));
}
while(rs.next()){
#SuppressWarnings("rawtypes")
Vector row = new Vector(columns);
for(int i = 1; i<= columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stmt.close();
}
catch(SQLException e){
JOptionPane.showMessageDialog(MainForm.this, e.getMessage());
}
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model){
#SuppressWarnings({ "rawtypes" })
public Class getColumnClass(int column){
for(int row = 0; row < getRowCount(); row++){
Object o = getValueAt(row,column);
if(o != null){
return o.getClass();
}
}
return Object.class;
}
};
table.setRowSelectionAllowed(true);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
int row = table.getSelectedRow();
try{
String dataClick = (table.getModel().getValueAt(row, 0).toString());
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo WHERE ChildID='"+dataClick+"'";
rs = stmt.executeQuery(sql);
if(rs.next()){
txtregistry.setText(Integer.toString(rs.getInt("ChildID"))); *this is where i get the error*
txtfirstName.setText(rs.getString("FirstName"));
txtlastName.setText(rs.getString("LastName"));
txtmiddleName.setText(rs.getString("MiddleName"));
txtgender.setText(rs.getString("Gender"));
txtbirthDate.setText(rs.getString("BirthDate"));
txtbirthType.setText(rs.getString("BirthType"));
txtmultiBirth.setText(rs.getString("IfMultiBirth"));
txtbirthOrder.setText(Integer.toString(rs.getInt("BirthOrder")));
txtbirthWeight.setText(Integer.toString(rs.getInt("BirthWeight")));
}
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
gui.add(scrollPane, BorderLayout.CENTER);
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception ee){
}
}
JTextField txtfirstName;
JTextField txtlastName;
JTextField txtmiddleName;
JTextField txtbirthDate;
JTextField txtgender;
JTextField txtbirthType;
JTextField txtmultiBirth;
JTextField txtbirthOrder;
JTextField txtbirthWeight;
JTextField txtregistry;
JTable table;
Kindly help me to fix the problem.
You're shadowing all the variable names for the components used in your class. E.g. Replace
JTextField txtfirstName = new JTextField();
with
txtfirstName = new JTextField();

Dynamically update values form database against selected index in Combobox

Scenario is, There is combobox and 2 textfields. Combobox items (model) are fetched from database and update Combobox dynamically. I have done it.
Now i need to do that when user select any item(model) from Combobox then its name and price should be updated in textfields.
How to do it ?
//This code only have one textfield one i will make after.
public class Purchases extends JFrame {
private JPanel contentPane;
private JTextField textField;
JComboBox comboBox = new JComboBox();
String model, name;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Purchases frame = new Purchases();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Purchases() {
try {
String host;
host = "jdbc:mysql://localhost:3306/sfs_electronics";// [root on Default schema]";
String uName = "root";
String uPass= "";
Connection con = DriverManager.getConnection( host, uName, uPass );
Statement stmt = con.createStatement( );
String SQL = "SELECT * FROM purchases";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
model= rs.getString("Model");
name= rs.getString("Name");
comboBox.addItem(model); // Adding Items in ComboBox
System.out.println(model);
}
}
catch(SQLException e){
System.out.println(e);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 501, 420);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 465, 146);
contentPane.add(panel);
panel.setLayout(null);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int n=comboBox.getSelectedIndex();
System.out.println(n);
System.out.println(comboBox.getSelectedItem());
textField.setText(?????); //Here What i need to code that selected models name should be place here.
}
});
comboBox.setBounds(109, 11, 86, 20);
panel.add(comboBox);
textField = new JTextField();
textField.setBounds(109, 47, 86, 20);
panel.add(textField);
textField.setColumns(10);
}
}
Code will be placed in comboBox.addActionListener.
//Connect database
String s = comboBox.getSelectedItem().toString();
String SQL = "SELECT * FROM `products` WHERE `Model` = '" + s + "'";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
requiredtextfield.setText(rs.getString("ColumnNAme_of_database"));
}
You can introduce a class Purchase with all necessary fields from DB you are going to use
public class Purchase {
int id;
String name;
String model;
...
public String toString() {
return model;
}
}
On retrieving data from DB create Purchase instances filling the fields from your result set. Place the purchase items in the combobox. TO provide correct showing you can either add your renderer which shows model field of the item (more complicated) or just override toString() method of Purchase class to return model field.
When somethinf is selected in the combobox the selected item is particular purchase instance and you can use the name field to reflect in the text field.

JTable not shown columns titles

I have a little problem in this code. I want to display a JTable with Column Headers but the problem is that the column's titles are not being displayed, as the Screenshot shows below:
private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DB_CONNECTION = "jdbc:oracle:thin:#localhost:1521:DB";
private static final String DB_USER = "*******";
private static final String DB_PASSWORD = "********";
Connection conn = null;
Statement stmt = null;
static Vector<Vector<String>> dataJ, dataC, data;
Vector<String> columnJ,
public void getCleubJoueurData() {
data = new Vector<Vector<String>>();
colum = new Vector<String>();
colum.add("nom");
colum.add("nom_cleub");
colum.add("numero_maillot");
colum.add("nationalite");
String query = "SELECT joueur.NOM,CLEUB.NOM_CLEUB," +
"JOUEUR_CLEUB.NUMERO_MAILLOT, joueur.NATIONALITE " +
"FROM joueur JOIN JOUEUR_CLEUB ON joueur.ID_J=" +
"JOUEUR_CLEUB.ID_J JOIN CLEUB ON JOUEUR_CLEUB.ID_C=CLEUB.ID_C";
try {
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Vector<String> vstring = new Vector<String>();
vstring.add(rs.getString("nom"));
vstring.add(rs.getString("nom_cleub"));
vstring.add(rs.getString("numero_maillot"));
vstring.add(rs.getString("nationalite"));
data.add(vstring);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
}
}
public App() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 882, 477);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBackground(Color.WHITE);
tabbedPane.setBounds(40, 43, 812, 390);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("joueurs", null, panel, null);
panel.setLayout(null);
getJoueurData();
DefaultTableModel mode = new DefaultTableModel(data, column);
table = new JTable(model);
table.setToolTipText("");
table.setBounds(0, 94, 819, 269);
panel.add(table);
}
Don't use null layouts. (And don't set the bounds)
Wrap your table in a JScrollPane. The JScrollPane will show the headers. If you don't want to use a JScrollPane, then you can get the JTableHeader of the table and add it separately
Former: (with JScrollPane)
JPanel container = new JPanel(); // default FlowLayout
JScrollPane scrollPane = new JScrollPane(table);
//container.add(table); // don't add the table, just the JScrollPane
container.add(scrollPane);
Latter: (without JScrollPane)
JPanel container = new JPanel(new BorderLayout());
container.add(table, BorderLayout.CENTER);
container.add(table.getTableHeader(), BorderLayout.PAGE_START);
The JTable documentation states that you'd typically want to use JTable in conjunction with a JScrollPane. If not:
JTables are typically placed inside of a JScrollPane. [...] Note that if you wish to
use a JTable in a standalone view (outside of a JScrollPane) and want
the header displayed, you can get it using getTableHeader() and
display it separately.
I'd recommend wrapping in a JScrollPane myself:
...
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
...

Adding JRadioButton to Group

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);
}

Categories