add dynamic checkbox in java windowbuilder - java

I want to add a dynamic checkbox after selecting an item in combo box.
I am working on eclipse and design my frame on window builder.
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
c.setVisible(true);
coursePanel.add(c);
frame.repaint();
frame.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
edit: thats my full code.
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(75, 171, 221, 39);
frame.getContentPane().add(dateChooser);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton btnSend = new JButton("\u05E9\u05DC\u05D7");
btnSend.setBounds(258, 334, 61, 58);
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// date
Date date = new Date(dateChooser.getDate().getTime());
}
});
frame.getContentPane().add(btnSend);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = c.getParent() == coursePanel;
if (selectedIndex == 1 && !isInPanel) {
coursePanel.add(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
} else if (isInPanel && selectedIndex != 1) {
coursePanel.remove(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
}
coursePanel.repaint();
coursePanel.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
List<String> lst = SqlQuery.getTypes();
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Hope you understand what I wrote. I want to show a list of coursesName after click on the comboBox.
Why the frame does'nt show the checkbox?
Thank you.

First and foremost. The comboBox.setBounds() is a very bad practice. Take some time and see Layout Managers. Also add 'swing' tag in your post since you are referring to Swing library.
The frame doesn't show the component because you repaint the wrong one. You add the checkbox in coursePanel, which means you have to repaint() & revalidate() coursePanel. So coursePanel.repaint() instead of frame.repaint() will help you.
Also checkBox.setVisible(true)is not required, since checkBox is visible by default.
Finally i have added the way of how i would do it.
package test;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private JCheckBox checkBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createPanel());
frame.pack();
}
private JPanel createPanel() {
JPanel p = new JPanel(new FlowLayout());
checkBox = new JCheckBox("I am a checkbox"); //Create the checkbox
JComboBox<String> combo = new JComboBox<>();
combo.addItem("Hello");
combo.addItem("Stack");
combo.addItem("OverFlow");
combo.addActionListener(e -> {
//Its better to handle indices when there is not dynmic data to your combobox
int selectedIndex = combo.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == p;
if (selectedIndex == 1 && !isInPanel) {
p.add(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
} else if (isInPanel && selectedIndex != 1) {
p.remove(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
}
});
p.add(combo);
return p;
}
}
The answer to your problem (make the checkbox visible) after comments:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
private JCheckBox checkBox;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
List<String> lst = new ArrayList<>();
lst.add("Hello");
lst.add("Stack");
lst.add("Over");
lst.add("Flow");
//Prepare the checkBox
checkBox = new JCheckBox("nothing");
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < lst.size(); i++) {
checkBox.setText(typeName);
//set the same bounds as comboBox but reduce its X by 80.
//Compare checkBoxbounds and combobox bounds
//Remind: setBounds is baaaaad practice.
checkBox.setBounds(128, 221, 91, 20);
//if you want to add it in coursePanel, change all frame.getContentPane() to coursePanel
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == frame.getContentPane();
if (selectedIndex == 1 && !isInPanel) {
frame.getContentPane().add(checkBox);
} else if (isInPanel && selectedIndex != 1) {
frame.getContentPane().remove(checkBox);
}
frame.getContentPane().repaint();
frame.getContentPane().validate();
System.out.println(checkBox.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Another option is to create the checkbox as a field outside of the actionlistener (like i did) and set its bounds with window builder and use setVisible(false). Then on your listener, setVisible(true)

Related

JComboBox selected index change use to send different JTextField values to JTable using Button Click Event

I attempt to send Text Field values to Table using button click event. But using combo box I need to change Unit type as "Imperial" or "Metric".
When select "Imperial" from combo box and Click ADD Button, Table should fill using "Name" , "Unit Imperial" & "Price Imperial" Text Field values.
But When select "Metric" from combo box and Click ADD Button,Table should fill using "Name" , "Unit Metric" & "Price Metric" Text Field values.
I don't have clear idea to use comboBox Item change use to effect on Button click event. Thanks in advance to guiding me to solve this problem.
public class UnitTable {
private JFrame frame;
private JTable table;
private JTextField txtName;
private JTextField txtUImp;
private JTextField txtPImp;
private JTextField txtUMetric;
private JTextField txtPMetric;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UnitTable window = new UnitTable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UnitTable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 649, 288);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 526, 181);
frame.getContentPane().add(scrollPane);
table = new JTable();
Object[] columns = { "Name", "Unit", "Price" };
DefaultTableModel model = new DefaultTableModel();
scrollPane.setViewportView(table);
model.setColumnIdentifiers(columns);
table.setModel(model);
JLabel lblName = new JLabel("Name");
lblName.setBounds(10, 201, 96, 13);
frame.getContentPane().add(lblName);
txtName = new JTextField();
txtName.setBounds(10, 224, 96, 19);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
JLabel lblUImp = new JLabel("Unit Imperial");
lblUImp.setBounds(121, 201, 91, 13);
frame.getContentPane().add(lblUImp);
txtUImp = new JTextField();
txtUImp.setBounds(116, 224, 96, 19);
frame.getContentPane().add(txtUImp);
txtUImp.setColumns(10);
JLabel lblPImp = new JLabel("Price Imperial");
lblPImp.setBounds(222, 201, 96, 13);
frame.getContentPane().add(lblPImp);
txtPImp = new JTextField();
txtPImp.setBounds(222, 224, 96, 19);
frame.getContentPane().add(txtPImp);
txtPImp.setColumns(10);
JLabel lblUMetric = new JLabel("Unit Metric");
lblUMetric.setBounds(330, 201, 94, 13);
frame.getContentPane().add(lblUMetric);
txtUMetric = new JTextField();
txtUMetric.setBounds(328, 224, 96, 19);
frame.getContentPane().add(txtUMetric);
txtUMetric.setColumns(10);
JLabel lblPMetric = new JLabel("Price Metric");
lblPMetric.setBounds(434, 201, 102, 13);
frame.getContentPane().add(lblPMetric);
txtPMetric = new JTextField();
txtPMetric.setBounds(434, 224, 96, 19);
frame.getContentPane().add(txtPMetric);
txtPMetric.setColumns(10);
JButton btnAdd = new JButton("ADD");
Object[] row = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
row[0] = txtName.getText();
row[1] = txtUImp.getText();
row[2] = txtPImp.getText();
model.addRow(row);
}
});
btnAdd.setBounds(546, 45, 85, 21);
frame.getContentPane().add(btnAdd);
JComboBox cmbUType = new JComboBox();
cmbUType.setModel(new DefaultComboBoxModel(new String[] { "Imperial", "Metric" }));
cmbUType.setBounds(546, 8, 85, 21);
frame.getContentPane().add(cmbUType);
JButton btnDelete = new JButton("DELETE");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if (i >= 0) {
model.removeRow(i);
} else {
JOptionPane.showMessageDialog(null, "Please Select Item to Delete");
}
}
});
btnDelete.setBounds(546, 76, 85, 21);
frame.getContentPane().add(btnDelete);
}
}
You should not be using a null layout and absolute positioning. Study Swing layout managers.
A JComboBox can hold any object. You need to tell the compiler what type of object (String) you're passing. You also need to tell the compiler what type of object you're storing in the DefaultComboBoxModel.
Having said that, I made cmbUType a class variable so I could reference it in the Add button action listener.
Here's your modified code.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class UnitTable {
private JFrame frame;
private JTable table;
private JTextField txtName;
private JTextField txtUImp;
private JTextField txtPImp;
private JTextField txtUMetric;
private JTextField txtPMetric;
private JComboBox<String> cmbUType;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UnitTable window = new UnitTable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UnitTable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 649, 288);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 526, 181);
frame.getContentPane().add(scrollPane);
table = new JTable();
Object[] columns = { "Name", "Unit", "Price" };
DefaultTableModel model = new DefaultTableModel();
scrollPane.setViewportView(table);
model.setColumnIdentifiers(columns);
table.setModel(model);
JLabel lblName = new JLabel("Name");
lblName.setBounds(10, 201, 96, 13);
frame.getContentPane().add(lblName);
txtName = new JTextField();
txtName.setBounds(10, 224, 96, 19);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
JLabel lblUImp = new JLabel("Unit Imperial");
lblUImp.setBounds(121, 201, 91, 13);
frame.getContentPane().add(lblUImp);
txtUImp = new JTextField();
txtUImp.setBounds(116, 224, 96, 19);
frame.getContentPane().add(txtUImp);
txtUImp.setColumns(10);
JLabel lblPImp = new JLabel("Price Imperial");
lblPImp.setBounds(222, 201, 96, 13);
frame.getContentPane().add(lblPImp);
txtPImp = new JTextField();
txtPImp.setBounds(222, 224, 96, 19);
frame.getContentPane().add(txtPImp);
txtPImp.setColumns(10);
JLabel lblUMetric = new JLabel("Unit Metric");
lblUMetric.setBounds(330, 201, 94, 13);
frame.getContentPane().add(lblUMetric);
txtUMetric = new JTextField();
txtUMetric.setBounds(328, 224, 96, 19);
frame.getContentPane().add(txtUMetric);
txtUMetric.setColumns(10);
JLabel lblPMetric = new JLabel("Price Metric");
lblPMetric.setBounds(434, 201, 102, 13);
frame.getContentPane().add(lblPMetric);
txtPMetric = new JTextField();
txtPMetric.setBounds(434, 224, 96, 19);
frame.getContentPane().add(txtPMetric);
txtPMetric.setColumns(10);
JButton btnAdd = new JButton("ADD");
Object[] row = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String type = (String) cmbUType.getSelectedItem();
if (type.equals("Imperial")) {
row[0] = txtName.getText();
row[1] = txtUImp.getText();
row[2] = txtPImp.getText();
} else {
row[0] = txtName.getText();
row[1] = txtUMetric.getText();
row[2] = txtPMetric.getText();
}
model.addRow(row);
}
});
btnAdd.setBounds(546, 45, 85, 21);
frame.getContentPane().add(btnAdd);
cmbUType = new JComboBox<>();
cmbUType.setModel(new DefaultComboBoxModel<String>
(new String[] { "Imperial", "Metric" }));
cmbUType.setBounds(546, 8, 85, 21);
frame.getContentPane().add(cmbUType);
JButton btnDelete = new JButton("DELETE");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if (i >= 0) {
model.removeRow(i);
} else {
JOptionPane.showMessageDialog(null, "Please Select Item to Delete");
}
}
});
btnDelete.setBounds(546, 76, 85, 21);
frame.getContentPane().add(btnDelete);
}
}

How to display multiple jpassword field in pop up in swing java?

I have 2 JTextField and 2 JPasswordField component in my swing java which frame looks as below:
When ShowAllDetails button is clicked, all the entered details is displayed in JtextArea as shown below:
Below is the code for the same:
package popUpTest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PopUpTest
{
private JFrame frame;
private JPasswordField passSourcePassword;
private JTextField txtSourceUserName;
private JTextField txtTargetUserName;
private JPasswordField passTargetPassword;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
PopUpTest window = new PopUpTest();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PopUpTest()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 444, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblSourceUserName = new JLabel("SourceUserName:");
lblSourceUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourceUserName.setBounds(15, 62, 170, 20);
frame.getContentPane().add(lblSourceUserName);
passSourcePassword = new JPasswordField();
passSourcePassword.setBounds(15, 153, 147, 26);
frame.getContentPane().add(passSourcePassword);
JLabel lblSourcePassword = new JLabel("SourcePassword:");
lblSourcePassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourcePassword.setBounds(15, 132, 147, 20);
frame.getContentPane().add(lblSourcePassword);
txtSourceUserName = new JTextField();
txtSourceUserName.setBounds(16, 81, 146, 26);
frame.getContentPane().add(txtSourceUserName);
txtSourceUserName.setColumns(10);
JLabel lblTargetUserName = new JLabel("TargetUserName:");
lblTargetUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetUserName.setBounds(240, 62, 170, 20);
frame.getContentPane().add(lblTargetUserName);
txtTargetUserName = new JTextField();
txtTargetUserName.setColumns(10);
txtTargetUserName.setBounds(241, 81, 146, 26);
frame.getContentPane().add(txtTargetUserName);
JLabel lblTargetPassword = new JLabel("TargetPassword:");
lblTargetPassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetPassword.setBounds(240, 132, 147, 20);
frame.getContentPane().add(lblTargetPassword);
passTargetPassword = new JPasswordField();
passTargetPassword.setBounds(240, 153, 147, 26);
frame.getContentPane().add(passTargetPassword);
JLabel lblEnterBelowDetails = new JLabel("Enter Below Details:");
lblEnterBelowDetails.setFont(new Font("Tahoma", Font.BOLD, 16));
lblEnterBelowDetails.setBounds(15, 26, 187, 20);
frame.getContentPane().add(lblEnterBelowDetails);
JTextArea textArea = new JTextArea();
textArea.setBounds(15, 252, 365, 85);
frame.getContentPane().add(textArea);
JButton btnShowAllDetails = new JButton("Show All Details:");
btnShowAllDetails.setBounds(15, 207, 226, 29);
frame.getContentPane().add(btnShowAllDetails);
btnShowAllDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
}
});
}
}
Now instead of diplaying these 4 components on loading the main frame instead, i want to diplay these 4 components in a Pop up Window on click of a button as below:
Also on clicking of Show All Details button should work as before.(i.e. it should populate JtextArea with the values entered in Pop Up)
How can I achieve this?
I have gone through other blogs as well however didn't find to show such multiple JPasswordField/JTextField in popup.Any guidance would be highly appreciated.
Just add the new components (JTextFields and JPasswordFields) within a button listener and call repaint() and revalidate() on the frame after that.
Here is a solution without proper layout:
EDIT:
package popUpTest;
import java.awt.EventQueue;
import javax.swing.*;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PopUpTest
{
private JFrame frame;
private JPasswordField passSourcePassword;
private JTextField txtSourceUserName;
private JTextField txtTargetUserName;
private JPasswordField passTargetPassword;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
PopUpTest window = new PopUpTest();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PopUpTest()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 444, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton popUpButton = new JButton("Click to Show Pop Up To Enter Detail");
popUpButton.setBounds(15, 100, 365, 85);
popUpButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
});
frame.getContentPane().add(popUpButton);
textArea = new JTextArea();
textArea.setBounds(15, 252, 365, 85);
frame.getContentPane().add(textArea);
JButton btnShowAllDetails = new JButton("Show All Details:");
btnShowAllDetails.setBounds(15, 207, 226, 29);
frame.getContentPane().add(btnShowAllDetails);
btnShowAllDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
}
});
}
public JTextArea getTextArea() {
return textArea;
}
private class MyDialog extends JDialog {
private final JPasswordField passSourcePassword;
private final JTextField txtSourceUserName;
private final JTextField txtTargetUserName;
private final JPasswordField passTargetPassword;
public MyDialog() {
setSize(600, 500);
setLayout(null);
JLabel lblEnterBelowDetails = new JLabel("Enter Below Details:");
lblEnterBelowDetails.setFont(new Font("Tahoma", Font.BOLD, 16));
lblEnterBelowDetails.setBounds(15, 26, 187, 20);
add(lblEnterBelowDetails);
JLabel lblSourceUserName = new JLabel("SourceUserName:");
lblSourceUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourceUserName.setBounds(15, 62, 170, 20);
add(lblSourceUserName);
passSourcePassword = new JPasswordField();
passSourcePassword.setBounds(15, 153, 147, 26);
add(passSourcePassword);
JLabel lblSourcePassword = new JLabel("SourcePassword:");
lblSourcePassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSourcePassword.setBounds(15, 132, 147, 20);
add(lblSourcePassword);
txtSourceUserName = new JTextField();
txtSourceUserName.setBounds(16, 81, 146, 26);
add(txtSourceUserName);
txtSourceUserName.setColumns(10);
JLabel lblTargetUserName = new JLabel("TargetUserName:");
lblTargetUserName.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetUserName.setBounds(240, 62, 170, 20);
add(lblTargetUserName);
txtTargetUserName = new JTextField();
txtTargetUserName.setColumns(10);
txtTargetUserName.setBounds(241, 81, 146, 26);
add(txtTargetUserName);
JLabel lblTargetPassword = new JLabel("TargetPassword:");
lblTargetPassword.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTargetPassword.setBounds(240, 132, 147, 20);
add(lblTargetPassword);
passTargetPassword = new JPasswordField();
passTargetPassword.setBounds(240, 153, 147, 26);
add(passTargetPassword);
JButton publishButton = new JButton("Publish");
publishButton.setBounds(100, 200, 146, 26);
add(publishButton);
publishButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.append(txtSourceUserName.getText() + "\n");
textArea.append(passSourcePassword.getText() + "\n");
textArea.append(txtTargetUserName.getText() + "\n");
textArea.append(passTargetPassword.getText() + "\n");
dispose();
}
});
setVisible(true);
}
}
}
By the way: try to read about layout managers as soon as possible, because absolute coordinates are a pain in the ass ;-)

What is wrong with this Java random software code?

I have made software in Java that generates random number in range. But it don't work. Sorry for strange language and comments. I have three classes: main, for generating and GUI. When I click button to generate it shows 0 on screen. Please help me.
public class glavnaKlasa {
static public int broj;
public static void main(String[] args) {
GUI guiObject = new GUI();
guiObject.mainGUI();
generisanje generisanjeObject = new generisanje();
broj = generisanjeObject.glavno(guiObject.min, guiObject.max);
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUI {
private JFrame frmNasumicniBroj;
private JTextField textField;
private JTextField textField_1;
private JLabel lblNasumicniBroj;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void mainGUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frmNasumicniBroj.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public int min, max;
private void initialize() {
frmNasumicniBroj = new JFrame();
frmNasumicniBroj.setTitle("Nasumicni broj");
frmNasumicniBroj.getContentPane().setBackground(Color.CYAN);
frmNasumicniBroj.setBounds(100, 100, 400, 300);
frmNasumicniBroj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmNasumicniBroj.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Donja granica: ");
lblNewLabel.setForeground(Color.YELLOW);
lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 154, 14);
frmNasumicniBroj.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setBounds(200, 8, 154, 20);
frmNasumicniBroj.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblGornjaGranica = new JLabel("Gornja granica: ");
lblGornjaGranica.setForeground(Color.YELLOW);
lblGornjaGranica.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblGornjaGranica.setBounds(10, 36, 165, 14);
frmNasumicniBroj.getContentPane().add(lblGornjaGranica);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(200, 33, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_1);
lblNasumicniBroj = new JLabel("Nasumicni broj: ");
lblNasumicniBroj.setForeground(Color.YELLOW);
lblNasumicniBroj.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNasumicniBroj.setBounds(10, 144, 180, 14);
frmNasumicniBroj.getContentPane().add(lblNasumicniBroj);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_2.setBounds(200, 141, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_2);
textField_2.setColumns(10);
JButton btnNewButton = new JButton("GENERISI");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
glavnaKlasa glKlasa = new glavnaKlasa();
String brString = Integer.toString(glKlasa.broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(10, 61, 345, 72);
frmNasumicniBroj.getContentPane().add(btnNewButton);
JLabel lblVerzija = new JLabel("Verzija: 1.0");
lblVerzija.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
lblVerzija.setBounds(10, 180, 71, 14);
frmNasumicniBroj.getContentPane().add(lblVerzija);
JLabel label_1 = new JLabel("Autor: Djordje Milanovic");
label_1.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_1.setBounds(10, 205, 141, 14);
frmNasumicniBroj.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Copyright: Alfin Informatics");
label_2.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_2.setBounds(9, 236, 166, 14);
frmNasumicniBroj.getContentPane().add(label_2);
}}
import java.util.Random;
import javax.swing.JOptionPane;
public class generisanje {
public static int glavno(int min, int max){
if (min >= max) {
JOptionPane.showMessageDialog(null, "Maksimalni broj mora biti veci od minimalnog");
}
Random rnd = new Random();
return rnd.nextInt((max - min) + 1) + min;
}
}
This:
glavnaKlasa glKlasa = new glavnaKlasa();
creates the object with empty constructor, your main will not run there, so broj remains uninitialized.
Actually, you don't need to instantiate this class there, just this:
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
int broj = generisanje.glavno(guiObject.min, guiObject.max);
String brString = Integer.toString(broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Also consider working according to Java coding standards ( class name first uppercase and so on, it will be much easier to maintain the code).

JLabel does not show value from another class

I have two GUI classes. When I click a row in JTable in the first user interface, the second interface should display the corresponding values in JLabels.
But the second user interface does not show the values.
Here's my first GUI class:
public class ChequeGUI extends JFrame {
public String chqNo;
public String payName;
public double chkAmount = 10;
public Date chkDate;
JTable guiTable = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"Cheque Number","Payee Name","Cheque Amount","Cheque Date"});
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
//guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
chqNo = (String) guiTable.getValueAt(row,0);
payName = (String) guiTable.getValueAt(row,1);
chkAmount = (Double) guiTable.getValueAt(row,2);
chkDate = (Date) guiTable.getValueAt(row, 3);
try {
PrintChequeGUI pcg = new PrintChequeGUI();
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
System.out.println(chqNo);
System.out.println(payName);
System.out.println(chkAmount);
System.out.println(chkDate);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
guiTable.setModel(model);
add(new JScrollPane(guiTable));
DBConnection connection = new DBConnection();
//Populate Table
ChequeDAOImpl chqdi = new ChequeDAOImpl();
chqdi.setConnection(connection);
List<Cheque> cheques = chqdi.getCheques();
for(Cheque cq : cheques){
model.addRow(new Object[]{cq.getChqNum(), cq.getName(),cq.getAmount(),cq.getDate()});
}
}
}
This is my second GUI class:
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
* #throws SQLException
*/
public PrintChequeGUI() throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(gui.chqNo);
lblAmount.setText(Double.toString(gui.chkAmount));
lblName.setText(gui.payName);
lblDate.setText(String.valueOf(gui.chkDate));
}
}
This can be solved in many ways:
1.
As I mentioned in my comment, Pass the current instance of ChequeGUI to the constructor of PrintChequeGUI and use that instance instead of creating new one in PrintChequeGUI
PrintChequeGUI pcg = new PrintChequeGUI(this);
and in PrintChequeGUI class
public PrintChequeGUI(ChequeGUI gui) throws SQLException {
(but i think its not a good approach)
2.
For Better option, Pass the selected instance of Cheque to PrintChequeGUI as constructor argument. For this you need to create a TableModel with instance of Cheque.
Sample is given below:
package com.test;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class ChequeGUI extends JFrame {
JTable guiTable = new JTable();
ChequeTableModel model;
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
Cheque c = model.getChequeByRow(row);
try {
PrintChequeGUI pcg = new PrintChequeGUI(c);
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
model = new ChequeTableModel();
guiTable.setModel(model);
add(new JScrollPane(guiTable));
model.loadData();
}
public class ChequeTableModel extends AbstractTableModel {
List<Cheque> dataModel;
String[] columns = { "Cheque Number", "Payee Name", "Cheque Amount",
"Cheque Date" };
public ChequeTableModel() {
super();
dataModel = new ArrayList<Cheque>();
}
#Override
public int getColumnCount() {
return columns.length;
}
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public int getRowCount() {
return dataModel.size();
}
#Override
public Object getValueAt(int row, int column) {
Object value = null;
Cheque c = getChequeByRow(row);
switch (column) {
case 0:
value = c.chqNo;
break;
case 1:
value = c.payName;
break;
case 2:
value = c.chkAmount;
break;
case 3:
value = c.chkDate;
break;
default:
break;
}
return value;
}
public Cheque getChequeByRow(int row) {
if (dataModel.size() <= 0)
return null;
if (row < 0)
return null;
return dataModel.get(row);
}
public void loadData() {
/*
*
* //Uncomment this for database connection and load data from
* database; //Please note to disconnect database if not needed
*
*
* DBConnection connection = new DBConnection();
*
* // Populate Table ChequeDAOImpl chqdi = new ChequeDAOImpl();
* chqdi.setConnection(connection); List<Cheque> cheques =
* chqdi.getCheques();
*
* for (Cheque cq : cheques) { model.addRow(new Object[] {
* cq.getChqNum(), cq.getName(), cq.getAmount(), cq.getDate() }); }
*/
for (int i = 0; i < 10; i++) {
Cheque c = new Cheque();
c.chkAmount = i * 1000;
c.chqNo = String.valueOf(i);
c.chkDate = new Date(System.currentTimeMillis());
dataModel.add(c);
}
fireTableRowsInserted(0, dataModel.size());
}
}
public static void main(String[] args) throws SQLException {
ChequeGUI c = new ChequeGUI();
c.pack();
c.setVisible(true);
}
}
Second class
package com.test;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
*
* #throws SQLException
*/
public PrintChequeGUI(Cheque cheque) throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
// ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(cheque.chqNo);
lblAmount.setText(Double.toString(cheque.chkAmount));
lblName.setText(cheque.payName);
lblDate.setText(String.valueOf(cheque.chkDate));
}
}
The Cheque class you already used to get details from database

set Icon gives error on JLabel

I'm having an issue with trying to change the icon of a JLabel. I am using the windowbuilder addon in eclipse to make this program, so just disregard all the bad naming choices of the label and all that, they will be changed later.
The error I'm having is that at the bottom of the my code where I try to change the icon of label_1, I get the following message.
The method seticon(icon) in the type jlabel is not applicable for the
arguments (string)
Does anyone have any idea what this could be?
Here is my code. Sorry that it's rather long, that's window builder for you I suppose:
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Game {
public Timer bomb1;
public JLabel label;
public JLabel label_1;
public JLabel lblScore;
public JButton btnQuit;
public JLabel label_2;
public JLabel label_3;
public JLabel label_4;
public JLabel label_5;
public JLabel label_6;
public JLabel label_7;
public JLabel label_8;
public JLabel label_9;
public JLabel label_10;
public JLabel label_11;
public JLabel label_12;
public JLabel label_13;
public JLabel label_14;
public JLabel label_15;
public JLabel label_16;
public JLabel lblDodgeTheBombs;
public JFrame frame;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game window = new Game();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Game() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 489, 512);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setContentPane(contentPane);
contentPane.setLayout(null);
label_1 = new JLabel("");
label_1.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_1.setBackground(Color.WHITE);
label_1.setBounds(59, 44, 80, 80);
contentPane.add(label_1);
label = new JLabel("0");
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
label.setBounds(71, 12, 46, 14);
contentPane.add(label);
lblScore = new JLabel("Score:");
lblScore.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblScore.setBounds(28, 11, 45, 17);
contentPane.add(lblScore);
btnQuit = new JButton("Quit");
btnQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
}
});
btnQuit.setBounds(359, 10, 89, 23);
contentPane.add(btnQuit);
label_2 = new JLabel("");
label_2.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_2.setBackground(Color.WHITE);
label_2.setBounds(149, 44, 80, 80);
contentPane.add(label_2);
label_3 = new JLabel("");
label_3.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_3.setBackground(Color.WHITE);
label_3.setBounds(239, 44, 80, 80);
contentPane.add(label_3);
label_4 = new JLabel("");
label_4.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_4.setBackground(Color.WHITE);
label_4.setBounds(329, 44, 80, 80);
contentPane.add(label_4);
label_5 = new JLabel("");
label_5.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_5.setBackground(Color.WHITE);
label_5.setBounds(59, 138, 80, 80);
contentPane.add(label_5);
label_6 = new JLabel("");
label_6.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_6.setBackground(Color.WHITE);
label_6.setBounds(149, 135, 80, 80);
contentPane.add(label_6);
label_7 = new JLabel("");
label_7.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_7.setBackground(Color.WHITE);
label_7.setBounds(239, 135, 80, 80);
contentPane.add(label_7);
label_8 = new JLabel("");
label_8.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_8.setBackground(Color.WHITE);
label_8.setBounds(329, 135, 80, 80);
contentPane.add(label_8);
label_9 = new JLabel("");
label_9.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_9.setBackground(Color.WHITE);
label_9.setBounds(329, 320, 80, 80);
contentPane.add(label_9);
label_10 = new JLabel("");
label_10.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_10.setBackground(Color.WHITE);
label_10.setBounds(59, 229, 80, 80);
contentPane.add(label_10);
label_11 = new JLabel("");
label_11.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_11.setBackground(Color.WHITE);
label_11.setBounds(149, 229, 80, 80);
contentPane.add(label_11);
label_12 = new JLabel("");
label_12.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_12.setBackground(Color.WHITE);
label_12.setBounds(239, 229, 80, 80);
contentPane.add(label_12);
label_13 = new JLabel("");
label_13.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_13.setBackground(Color.WHITE);
label_13.setBounds(329, 229, 80, 80);
contentPane.add(label_13);
label_14 = new JLabel("");
label_14.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_14.setBackground(Color.WHITE);
label_14.setBounds(239, 320, 80, 80);
contentPane.add(label_14);
label_15 = new JLabel();
label_15.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_15.setBackground(Color.WHITE);
label_15.setBounds(149, 320, 80, 80);
contentPane.add(label_15);
label_16 = new JLabel("");
label_16.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_16.setBackground(Color.WHITE);
label_16.setBounds(59, 323, 80, 80);
contentPane.add(label_16);
lblDodgeTheBombs = new JLabel("Dodge the bombs!");
lblDodgeTheBombs.setForeground(Color.RED);
lblDodgeTheBombs.setFont(new Font("Tahoma", Font.PLAIN, 25));
lblDodgeTheBombs.setBounds(137, 418, 217, 33);
contentPane.add(lblDodgeTheBombs);
bomb1 = new Timer(1000, new TimerListener());
bomb1.start();
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label_1.setIcon("C:\\Users\\Josh\\Desktop\\blank.png");
}
}
}
The method seticon(icon) in the type jlabel is not applicable for the
arguments (string)
yes its because as per the doc found here the setIcon() accepts a Icon as a parrameter not String. So, your code should be...
label_1.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\blank.png"));
I recommend you to go with documentations in the future. Its really a very good practice.
I think the error message is self-explanatory about what went wrong. The "setIcon()" method expects instance of Icon class and not string instance.
jLabelObject.setIcon("string") // Do not pass image path

Categories