I am trying to open a new JDialog when the "Register" Button is clicked..
But I am unable to make the JDialog modal..
I have tried setModal(true) and also setModalityType(ModalityType.DOCUMENT_MODAL);
But no luck..(I am using Eclipse's WindowBuilder plugin)
P.S: I am new to JAVA..
Here is my code...
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.xml.ws.handler.MessageContext;
public class loginpage extends JFrame {
private JPanel contentPane;
private JTextField userid;
private JPasswordField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
loginpage frame = new loginpage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public loginpage() {
super("User Login");
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(400, 200, 550, 370);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JLabel label = new JLabel("Please enter your login credentials...");
label.setFont(new Font("Times New Roman", Font.PLAIN, 25));
label.setForeground(Color.BLUE);
label.setBounds(79, 11, 400, 61);
contentPane.add(label);
JLabel lblLoginId = new JLabel("User ID :");
lblLoginId.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblLoginId.setBounds(159, 142, 71, 17);
contentPane.add(lblLoginId);
JLabel lblUserType = new JLabel("User Type :");
lblUserType.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblUserType.setBounds(159, 102, 85, 17);
contentPane.add(lblUserType);
JLabel lblPassword = new JLabel("Password :");
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblPassword.setBounds(159, 188, 96, 14);
contentPane.add(lblPassword);
userid = new JTextField();
userid.setBounds(254, 141, 114, 20);
contentPane.add(userid);
userid.setColumns(10);
password = new JPasswordField();
password.setBounds(254, 186, 114, 20);
contentPane.add(password);
JComboBox usertype = new JComboBox();
usertype.setBounds(254, 101, 89, 20);
contentPane.add(usertype);
usertype.addItem("Admin");
usertype.addItem("Employee");
JButton btnLogin = new JButton("Login");
btnLogin.setBounds(254, 228, 71, 23);
contentPane.add(btnLogin);
JLabel lblNewEmployeeRegister = new JLabel("New employee? ");
lblNewEmployeeRegister.setForeground(Color.RED);
lblNewEmployeeRegister.setBounds(296, 304, 114, 14);
contentPane.add(lblNewEmployeeRegister);
JButton btnRegister = new JButton("Register Here");
btnRegister.setBounds(398, 301, 126, 20);
contentPane.add(btnRegister);
ImageIcon myicon = new ImageIcon("src\\logo.gif");
JLabel iconlabel = new JLabel(myicon);
iconlabel.setBounds(0, 233, 103, 99 );
iconlabel.setIcon(myicon);
contentPane.add(iconlabel);
//Adding Listeners to buttons
//Login Button Listener
btnLogin.addActionListener(new ActionListener()
{
//Making the Connection and registering the Drivers
#Override
public void actionPerformed(ActionEvent arg0) {
}//actionPerformed ends here
});//Login Button Listener ends here
//Register Button Listener
btnRegister.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog jd=new JDialog(loginpage.this,"User Registration");
jd.setLayout(null);
jd.setVisible(true);
jd.setBounds(400,300, 479, 329);
jd.setResizable(false);
setLocationRelativeTo(loginpage.this);
jd.setModal(true);
JLabel lblFillUpThe = new JLabel("Fill up the form to register");
lblFillUpThe.setForeground(Color.BLUE);
lblFillUpThe.setFont(new Font("Times New Roman", Font.PLAIN, 25));
lblFillUpThe.setBounds(93, 11, 400, 61);
jd.add(lblFillUpThe);
JLabel lblUserId = new JLabel("Type in a User ID :");
lblUserId.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblUserId.setBounds(77, 96, 104, 14);
jd.add(lblUserId);
JTextField newid = new JTextField();
newid.setBounds(236, 94, 122, 20);
jd.add(newid);
newid.setColumns(10);
JLabel lblTypeA = new JLabel("Type in a new Password :");
lblTypeA.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblTypeA.setBounds(77, 142, 142, 14);
jd.add(lblTypeA);
JPasswordField newpass = new JPasswordField();
newpass.setBounds(236, 140, 122, 20);
jd.add(newpass);
JLabel lblConfirmThePassword = new JLabel("Confirm the Password :");
lblConfirmThePassword.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblConfirmThePassword.setBounds(77, 189, 130, 14);
jd.add(lblConfirmThePassword);
JPasswordField confpass = new JPasswordField();
confpass.setBounds(236, 187, 122, 20);
jd.add(confpass);
JButton reg = new JButton("Register");
reg.setBounds(239, 237, 89, 23);
jd.add(reg);
reg.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(getParent(), "User Registered Successfully..!!", "Successful",JOptionPane.INFORMATION_MESSAGE);
}
});
}
});//Register Button Listener ends here
}
}
Try making the dialog modal BEFORE you try and make it visible. You can't change the modal state once the dialog is made visible...
JDialog jd=new JDialog(loginpage.this,"User Registration");
jd.setModal(true);
jd.setLayout(null); // THIS IS A BAD IDEA //
jd.setLocationRelativeTo(null);
// This is somewhat pointless, you've set relative location, but know overridden it...
// You should also be relying on the layout manager and pack to determine the size...
jd.setBounds(400,300, 479, 329);
jd.setResizable(false);
setLocationRelativeTo(loginpage.this);
// Add you other components
jd.setVisible(true);
Related
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 ;-)
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)
I've been having trouble with exporting my GUI project from Eclipse Oxygen. At first I tried exporting my project by going to export>Runnable Jar File>Main Class, but when I try and open my program nothing shows up. Then I tried opening the GUI inside its own class by specifying a Main method in there, and I keep getting the error that I put in the title. Any help would be appreciated. I'll post both of my classes here.
Also I used WindowBuilder plugin to build my GUI.
Main class
package me.iran.cryptotracker;
import java.util.ArrayList;
import lombok.Getter;
import me.iran.cryptotracker.window.Window;
public class CryptoTracker {
private static SaveFile saveFile = new SaveFile();
private static ReadFile readFile = new ReadFile();
#Getter
public static ArrayList<Crypto> allCrypto = new ArrayList<Crypto>();
public static void main(String[] args) {
readFile.openFile();
readFile.readFile();
readFile.closeFile();
saveFile.openFile();
saveFile.updateFile();
saveFile.closeFile();
Window.open();
}
}
Window1 Class
package me.iran.cryptotracker.window;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import lombok.Getter;
import me.iran.cryptotracker.Crypto;
import me.iran.cryptotracker.CryptoTracker;
import me.iran.cryptotracker.ReadFile;
import me.iran.cryptotracker.SaveFile;
public class Window {
static #Getter
private JFrame frame;
#Getter
private static JTable table;
/**
* Launch the application.
*/
public static void open() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBackground(Color.DARK_GRAY);
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setBounds(100, 100, 571, 622);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable();
table.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
table.setBackground(new Color(169, 169, 169));
Object columnName[] = {"Name", "Date", "Initial Price", "Stock", "URL"};
DefaultTableModel model = new DefaultTableModel(columnName, 0);
model.addRow(columnName);
for(Crypto crypto : CryptoTracker.allCrypto) {
String name = crypto.getName();
String date = crypto.getDate();
double initial = crypto.getInitialPrice();
double amount = crypto.getAmount();
String url = crypto.getUrl();
Object[] data = {name, date, initial + "", amount + "", url};
model.addRow(data);
}
SpringLayout springLayout = new SpringLayout();
springLayout.putConstraint(SpringLayout.NORTH, table, 37, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, table, 30, SpringLayout.WEST, frame.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, table, 478, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, table, 464, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().setLayout(springLayout);
table.setModel(model);
frame.getContentPane().add(table);
JButton btnAdd = new JButton("Add Currency");
springLayout.putConstraint(SpringLayout.NORTH, btnAdd, -48, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, btnAdd, 0, SpringLayout.WEST, table);
springLayout.putConstraint(SpringLayout.SOUTH, btnAdd, -25, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, btnAdd, 150, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().add(btnAdd);
btnAdd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
AddWindow.open();
}
});
}
public static void updateTable(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
Object columnName[] = {"Name", "Date", "Initial Price", "Stock", "URL"};
model.addRow(columnName);
for(Crypto crypto : CryptoTracker.allCrypto) {
String name = crypto.getName();
String date = crypto.getDate();
double initial = crypto.getInitialPrice();
double amount = crypto.getAmount();
String url = crypto.getUrl();
Object[] data = {name, date, initial + "", amount + "", url};
model.addRow(data);
}
table.setModel(model);
}
}
Window 2 Class
package me.iran.cryptotracker.window;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import me.iran.cryptotracker.Crypto;
import me.iran.cryptotracker.CryptoTracker;
import me.iran.cryptotracker.SaveFile;
public class AddWindow {
private JFrame frame;
private JTextField txtName;
private JTextField txtDate;
private JTextField txtCost;
private JTextField txtAmount;
private JTextField txtURL;
private SaveFile saveFile = new SaveFile();
public static void open() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddWindow window = new AddWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.getContentPane().setLayout(null);
txtName = new JTextField();
txtName.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtName.setBounds(107, 11, 138, 20);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
txtDate = new JTextField();
txtDate.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtDate.setColumns(10);
txtDate.setBounds(107, 44, 138, 20);
frame.getContentPane().add(txtDate);
txtCost = new JTextField();
txtCost.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtCost.setColumns(10);
txtCost.setBounds(107, 75, 138, 20);
frame.getContentPane().add(txtCost);
txtAmount = new JTextField();
txtAmount.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtAmount.setColumns(10);
txtAmount.setBounds(107, 106, 138, 20);
frame.getContentPane().add(txtAmount);
txtURL = new JTextField();
txtURL.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtURL.setColumns(10);
txtURL.setBounds(107, 137, 138, 20);
frame.getContentPane().add(txtURL);
JLabel lblName = new JLabel("Name");
lblName.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblName.setBounds(22, 11, 46, 14);
frame.getContentPane().add(lblName);
JLabel lblDate = new JLabel("Date");
lblDate.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblDate.setBounds(22, 44, 46, 14);
frame.getContentPane().add(lblDate);
JLabel lblInitialCost = new JLabel("Initial Cost");
lblInitialCost.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblInitialCost.setBounds(22, 75, 75, 14);
frame.getContentPane().add(lblInitialCost);
JLabel lblAmount = new JLabel("Amount");
lblAmount.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblAmount.setBounds(22, 106, 63, 14);
frame.getContentPane().add(lblAmount);
JLabel lblUrl = new JLabel("URL");
lblUrl.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblUrl.setBounds(22, 137, 46, 14);
frame.getContentPane().add(lblUrl);
final JLabel lblError = new JLabel("");
lblError.setFont(new Font("Cambria Math", Font.PLAIN, 14));
lblError.setBounds(278, 59, 284, 102);
frame.getContentPane().add(lblError);
JButton btnAddCurrency = new JButton("Add Currency");
btnAddCurrency.setBounds(355, 11, 138, 38);
frame.getContentPane().add(btnAddCurrency);
frame.setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 588, 211);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnAddCurrency.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(!txtName.getText().isEmpty() && !txtDate.getText().isEmpty() && !txtURL.getText().isEmpty() && !txtCost.getText().isEmpty() && !txtAmount.getText().isEmpty()) {
String name = txtName.getText();
String date = txtDate.getText();
String url = txtURL.getText();
try {
double initial = Double.parseDouble(txtCost.getText());
double amount = Double.parseDouble(txtAmount.getText());
CryptoTracker.allCrypto.add(new Crypto(name, date, url, initial, amount));
saveFile.openFile();
saveFile.updateFile();
saveFile.closeFile();
frame.setVisible(false);
Window.getFrame().setVisible(true);
Window.updateTable(Window.getTable());
} catch(Exception exc) {
lblError.setText("You have not entered a number in the Initial Cost and/or Amount field");
}
}
}
});
}
}
Turns out that winrar does not like runnable jar files. I had tried Right Clicking the file and running it as a java application SE binary, but it would not work. So after #Adam Horvath mentioned that it worked for him I set the exported jar to default java jar and it opened up just fine.
Hi I'm trying to display an ArrayList of Objects on a Jlist. While displaying the ArrayList, I'm trying to be able to add or delete objects to the ArrayList through the GUI.
1) How can I display the ArrayList objects on the Jlist? 2)How can I delete an object by selecting it on the JList?
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.JList;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
public class DriverFrame extends JFrame implements ItemListener{
private JPanel contentPane;
private JList driverlist;
private ArrayList drivers= new ArrayList<Driver>();
JTextField textFieldFirstName;
JTextField textFieldLastName;
JTextField textFieldTruckNumber;
JTextField textFieldTrailerNumber;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_7;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DriverFrame frame = new DriverFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DriverFrame() {
Driver guy1= new Driver("Jeff","Blank","4125","1234",1400);
Driver guy2= new Driver("Marcus","Geralds","0093","1203",1800);
Driver guy3= new Driver("Steve","Wemmings","2010","2046",2100);
Driver guy4= new Driver("Kyle","Patricks","8427","5625",900);
Driver guy5= new Driver("Ficel","Metter","9124","4536",5500);
setBackground(Color.WHITE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
setResizable(false);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
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(5, 5, 495, 480);
contentPane.add(tabbedPane);
//Drivers TabbedPan ********
JPanel Drivers = new JPanel();
Drivers.setBackground(Color.WHITE);
tabbedPane.addTab("Drivers", null, Drivers, null);
Drivers.setLayout(null);
//List to display drivers
JList<Object> driverlist = new JList<>(drivers.toArray(new String[0]));
driverlist.setBackground(Color.WHITE);
driverlist.setVisibleRowCount(8);
driverlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Drivers.add(driverlist);
driverlist.setBounds(221,6,247,234);
JTextPane txtpnFirstName = new JTextPane();
txtpnFirstName.setText("First name");
txtpnFirstName.setBounds(5, 20, 140, 15);
Drivers.add(txtpnFirstName);
txtpnFirstName.setEditable(false);
textFieldFirstName = new JTextField();
textFieldFirstName.setBounds(5, 40, 140, 30);
Drivers.add(textFieldFirstName);
textFieldFirstName.setColumns(10);
JTextPane txtpnLastName = new JTextPane();
txtpnLastName.setText("Last Name");
txtpnLastName.setBounds(5, 75, 140, 15);
Drivers.add(txtpnLastName);
txtpnLastName.setEditable(false);
textFieldLastName = new JTextField();
textFieldLastName.setBounds(5, 95, 140, 30);
Drivers.add(textFieldLastName);
textFieldLastName.setColumns(10);
JTextPane txtpnTruckNumber = new JTextPane();
txtpnTruckNumber.setText("Truck Number");
txtpnTruckNumber.setBounds(5, 130, 140, 15);
Drivers.add(txtpnTruckNumber);
txtpnTruckNumber.setEditable(false);
textFieldTruckNumber = new JTextField();
textFieldTruckNumber.setBounds(5, 150, 140, 30);
Drivers.add(textFieldTruckNumber);
textFieldTruckNumber.setColumns(10);
JTextPane txtpnTrailerNumber = new JTextPane();
txtpnTrailerNumber.setText("Trailer Number");
txtpnTrailerNumber.setBounds(5, 185, 140, 15);
Drivers.add(txtpnTrailerNumber);
txtpnTrailerNumber.setEditable(false);
textFieldTrailerNumber = new JTextField();
textFieldTrailerNumber.setBounds(5, 205, 140, 30);
Drivers.add(textFieldTrailerNumber);
textFieldTrailerNumber.setColumns(10);
JButton btnAddDriver = new JButton("Add Driver");
btnAddDriver.setBounds(5, 285, 117, 29);
Drivers.add(btnAddDriver);
JButton btnNewButton = new JButton("Delete Driver");
btnNewButton.setBounds(302, 285, 117, 29);
Drivers.add(btnNewButton);
btnAddDriver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Driver blah = new Driver();
blah.setFirst(textFieldFirstName.getText());
blah.setLast(textFieldLastName.getText());
blah.setTnum(textFieldTruckNumber.getText());
blah.setTrailer(textFieldTrailerNumber.getText());
drivers.add(blah);
System.out.println(blah.printDriver());
System.out.println(drivers.size());
//drivers.remove(example);
}
});
//End of DriversPane******
//New Expenses Tab*****
JPanel NewExpense = new JPanel();
tabbedPane.addTab("New Expense", null, NewExpense, null);
JButton buttontest = new JButton();
NewExpense.add(buttontest);
//End of New Expense Tab****
//Income Tab****
JPanel Income = new JPanel();
Income.setBackground(Color.WHITE);
tabbedPane.addTab("Income", null, Income, null);
Income.setLayout(null);
JComboBox comboBox_3 = new JComboBox();
comboBox_3.setBounds(6, 70, 138, 27);
Income.add(comboBox_3);
JTextPane txtpnDriver_3 = new JTextPane();
txtpnDriver_3.setText("Driver:");
txtpnDriver_3.setBounds(6, 42, 42, 16);
Income.add(txtpnDriver_3);
JTextPane txtpnLoadLocationstate = new JTextPane();
txtpnLoadLocationstate.setText("Load Location(State): ");
txtpnLoadLocationstate.setBounds(6, 161, 138, 16);
Income.add(txtpnLoadLocationstate);
textField_6 = new JTextField();
textField_6.setBounds(6, 205, 130, 26);
Income.add(textField_6);
textField_6.setColumns(10);
JTextPane txtpnLoadAmount = new JTextPane();
txtpnLoadAmount.setText("Load Amount $$:");
txtpnLoadAmount.setBounds(6, 299, 108, 16);
Income.add(txtpnLoadAmount);
textField_7 = new JTextField();
textField_7.setBounds(6, 339, 130, 26);
Income.add(textField_7);
textField_7.setColumns(10);
//End of Income Tab****
//Results Tab***
JPanel Results = new JPanel();
Results.setBackground(Color.WHITE);
tabbedPane.addTab("Result", null, Results, null);
Results.setLayout(null);
JComboBox comboBox_4 = new JComboBox();
comboBox_4.setBounds(6, 69, 140, 27);
Results.add(comboBox_4);
JTextPane txtpnDriver_4 = new JTextPane();
txtpnDriver_4.setText("Driver:");
txtpnDriver_4.setBounds(6, 42, 140, 16);
Results.add(txtpnDriver_4);
JTextArea txtrHowMuchTo = new JTextArea();
txtrHowMuchTo.setText("How much to pay driver. How much are the expenses of the driver");
txtrHowMuchTo.setBounds(6, 124, 234, 304);
Results.add(txtrHowMuchTo);
JTextPane txtpnDriverInformation = new JTextPane();
txtpnDriverInformation.setText("Driver Information");
txtpnDriverInformation.setBounds(16, 108, 140, 16);
Results.add(txtpnDriverInformation);
JTextPane txtpnCompanyInfo = new JTextPane();
txtpnCompanyInfo.setText("Company Info:");
txtpnCompanyInfo.setBounds(414, 80, 178, 16);
Results.add(txtpnCompanyInfo);
JTextArea txtrIncome = new JTextArea();
txtrIncome.setText("Income Expenses");
txtrIncome.setBounds(390, 124, 294, 304);
Results.add(txtrIncome);
//End of Results Tab****
}
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
}
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