I have created a simple Login Frame using a JFrame.
I have hardcoded validations wherein if a user enters username as AKASH and password as 12345 then Login Success is displayed below the Button else Wrong Password is displayed.
Everything is working fine.The only thing is :
I have to double click to see the result after entering the details
Could anyone please help me on this.
Here is my code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LginForm extends JFrame implements ActionListener{
Container c;
JTextField jt;
JButton jb;
JPasswordField jp;
JLabel jl1,jl2;
JLabel jl3 = new JLabel("Wrong Password");
JLabel jl4 = new JLabel("Login Successful");
public static void main(String[] args) {
LginForm lf = new LginForm();
lf.setBounds(100, 50, 500, 400);
lf.setVisible(true);
lf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public LginForm() {
c = this.getContentPane();
c.setBackground(Color.yellow);
c.setLayout(null);
jl1 = new JLabel("Enter Username");
jl1.setBounds(50, 10, 100, 30);
jl1.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
jl2 = new JLabel("Enter Password");
jl2.setBounds(50, 100, 100, 30);
jl2.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
jt = new JTextField();
jt.setBounds(200,10,100,30);
jp = new JPasswordField();
jp.setBounds(200,100,100,30);
jb = new JButton("login");
jb.setBounds(130,180,80,30);
c.add(jl1);
c.add(jl2);
c.add(jt);
c.add(jp);
c.add(jb);
jb.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == jb) {
String usrname = jt.getText();
String passwrd = String.valueOf(jp.getPassword());
if(usrname.equals("Akash") && passwrd.equals("12345")) {
jl4.setBounds(100, 230, 150, 40);
jl4.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
c.add(jl4);
c.remove(jl3);
}
else {
jl3.setBounds(100, 230, 150, 40);
jl3.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
c.add(jl3);
c.remove(jl4);
}
}
}
}
This the login frame created
c.add(jl4);
c.remove(jl3);
I would guess that after adding/removing components from the panel you need to invoked repaint() the panel.
This is only a guess because you should NOT be using a null layout. Swing was designed to be used with layout managers. Let the layout manager determine the size/location of components based on the rules the layout manager.
Then when you add/remove components from a panel the basic logic would be:
panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
Read the Swing tutorial on Using Layout Managers for more information.
Note:
I would also suggest a simpler solution is to add the "message label" to the panel with text set to " ". Then you can simply use the setText(...) method of the label to change the message. This way you don't even need to worry about adding/removing components.
Related
i was following a tutorial on youtube to learn java guis ands i was making a login screen.
i was testing the login button by making it print works in console w but i presses. i followed the whole tutoral properly and tried every way. the code is spamming widows shown in the video.
link to video : https://hriday.tk/2022-01-09%2019-56-32.mkv
the code :
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login implements ActionListener{
public Login() {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
JLabel Ulabel = new JLabel("UserName");
JLabel Plabel = new JLabel("PassWord");
JTextField Utext = new JTextField(20);
JPasswordField Ptext = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel success = new JLabel("");
panel.setLayout(null);
panel.add(Ulabel);
panel.add(Utext);
panel.add(Plabel);
panel.add(Ptext);
panel.add(login);
panel.add(success);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(350, 150);
frame.setTitle("Login");
frame.add(panel);
Ulabel.setBounds(10, 10, 80, 25);
Utext.setBounds(100, 10, 165, 25);
Plabel.setBounds(10, 40, 80, 25);
Ptext.setBounds(100, 40, 165, 25);
login.setBounds(50, 70, 100, 25);
success.setBounds(200, 70, 100, 25);
login.addActionListener(new Login());
}
public static void main(String[] args){ new Login(); }
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("works");
}
} ```
This is causing your problems:
// imports
public class Login implements ActionListener {
public Login() {
// .... code removed
login.addActionListener(new Login()); // **** here ****
}
// .....
}
You're calling this in the Login constructor and so are creating new Login objects recursively, meaning, each time the Login constructor is called, it creates a new Login object, which calls the constructor, which creates a new Login object, which.... well, you should get the point.
Instead, change it to this:
login.addActionListener(this);
Here you add the already created Login object, the this object, and add it to the ActionListener.
Caveat:
Having said this, I would be remiss if I didn't mention that using null layouts and setBounds(...) is not healthy as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead, you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.
For that reason you're far better off learning about and using the layout managers. You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info.
... and if this is from a tutorial and it recommends use of null layouts, then ditch the tutorial!
For example (using GridBagLayout):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import javax.swing.*;
public class Login2 {
private static final int GAP = 5;
private JPanel mainPanel = new JPanel();
private JTextField userNameField = new JTextField(20);
private JPasswordField passwordField = new JPasswordField(20);
private JButton loginButton = new JButton("Login");
private JLabel successLabel = new JLabel(" ");
public Login2() {
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.setLayout(new GridBagLayout());
mainPanel.add(new JLabel("UserName:"), createGBC(0, 0));
mainPanel.add(userNameField, createGBC(1, 0));
mainPanel.add(new JLabel("Password:"), createGBC(0, 1));
mainPanel.add(passwordField, createGBC(1, 1));
mainPanel.add(loginButton, createGBC(0, 2));
mainPanel.add(successLabel, createGBC(1, 2));
loginButton.addActionListener(e -> {
successLabel.setText("Success");
Window window = SwingUtilities.getWindowAncestor(mainPanel);
window.dispose();
});
}
public String getUserName() {
return userNameField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
// create constraints that help position components in the GridBagLayout-using container
private GridBagConstraints createGBC(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
return gbc;
}
public JPanel getMainPanel() {
return mainPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Login2 login2 = new Login2();
JDialog dialog = new JDialog(null, "Login", ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.add(login2.getMainPanel());
dialog.pack();
dialog.setLocationByPlatform(true);
dialog.setVisible(true);
System.out.println("User Name: " + login2.getUserName());
System.out.println("Password: " + new String(login2.getPassword()));
});
}
}
Recently I've been trying to make a program that takes in a double in the form of a string. It then parses that to a double which goes to another class to be divided to a quarter or a half and then returns that output to a label.
I've been having an issue where when I click a button to actually submit what is inside the text field, the label doesn't change.
I've tried a lot of trial and error and I know I can change the text after doing new JLabel("test") for example. However, there seems to be an issue with my action listener for when the button is pushed. I can't tell if it's not seeing the button as being pushed.
NOTE: I am new to awt event things and swing as a whole, I usually operate just using the output terminal of visual studio code where it's just text and no graphics.
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Dimension;
public class MoneySorterRunner {
private MoneySorter sorter = new MoneySorter();
private String input = "0";
private double money = Double.parseDouble(input);
private static JTextField typeHere = new JTextField();
///labels num1-3 are the labels being changed
private static JLabel num1 = new JLabel(new MoneySorterRunner().sorter.divQuarter(new MoneySorterRunner().money));
private static JLabel num2 = new JLabel(new MoneySorterRunner().sorter.divQuarter(new MoneySorterRunner().money));
private static JLabel num3 = new JLabel(new MoneySorterRunner().sorter.divHalf(new MoneySorterRunner().money));
public static void main(String args[]) {
JFrame frame = new JFrame("Money Calculator - v0.1a");
JPanel panel = new JPanel();
JButton doThing = new JButton("Do a Thing");
doThing.setActionCommand("Do a Thing");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 250);
frame.setLocation(200, 200);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
panel.setLayout(null);
frame.setVisible(true);
JLabel item1 = new JLabel("test");
JLabel item2 = new JLabel("test");
JLabel item3 = new JLabel("test");
item1.setFont(new Font("Arial", Font.PLAIN, 30));
item2.setFont(new Font("Arial", Font.PLAIN, 30));
item3.setFont(new Font("Arial", Font.PLAIN, 30));
num1.setFont(new Font("Arial", Font.PLAIN, 25));
num2.setFont(new Font("Arial", Font.PLAIN, 25));
num3.setFont(new Font("Arial", Font.PLAIN, 25));
Dimension size1 = item1.getPreferredSize();
Dimension size2 = item2.getPreferredSize();
Dimension size3 = item3.getPreferredSize();
panel.add(item1);
panel.add(item2);
panel.add(item3);
panel.add(num1);
panel.add(num2);
panel.add(num3);
panel.add(doThing);
panel.add(typeHere);
item1.setBounds(10, 10, size1.width + 3, size1.height);
item2.setBounds(190, 10, size2.width + 3, size2.height);
item3.setBounds(325, 10, size3.width + 3, size3.height);
num1.setBounds(50, 50, 50, 25);
num2.setBounds(200, 50, 50, 25);
num3.setBounds(350, 50, 50, 25);
doThing.setBounds(250, 150, 100, 25);
typeHere.setBounds(100, 150, 150, 25);
}
public void actionPerformed(ActionEvent event){
String check = event.getActionCommand();
if(check.equals("Do a Thing")){
input = typeHere.getText();
}
if(input != "0"){
num1.setText(sorter.divQuarter(money));
num2.setText(sorter.divQuarter(money));
num3.setText(sorter.divHalf(money));
}
}
}
For those who wanted the MoneySorter.java:
public MoneySorter(){
}
public String divQuarter(double moneyIn){
String answer = Double.toString(moneyIn);
return answer;
}
public String divHalf(double moneyIn){
String answer = Double.toString(moneyIn);
return answer;
}
}
I understand that your program is supposed to do the following.
User enters an amount of money in a JTextField and when she clicks on a JButton the JLabels show the entered amount in dollars, half-dollars and quarters (as per U.S. currency). My answer, below, is based on this understanding.
I don't know if making all the variables static is good or bad but I never use static class member variables in my Swing programs.
Here is my analysis of your code.
private double money = Double.parseDouble(input);
This line of code will be executed precisely once, when you launch class MoneySorterRunner. You want to do this every time the JButton is clicked, hence parsing the text entered into the JTextField should be performed in the actionPerformed method.
JPanel panel = new JPanel();
panel.setLayout(null);
It is almost never needed to set the layout manager to null. You can almost always find an appropriate layout manager or you can place one JPanel within another and use different layout managers for each JPanel in order to get the desired placement of components within the Swing application window.
JButton doThing = new JButton("Do a Thing");
doThing.setActionCommand("Do a Thing");
By default, the text of a JButton is also its action command so no need to explicitly set it.
frame.setLocation(200, 200);
frame.setLocationRelativeTo(null);
These are two different ways to set the location of the JFrame and they do not complement each other. Use one or the other, but not both.
frame.setVisible(true);
Only after you have created all the [GUI] components and added them to the JFrame should you make the JFrame visible. So this should be the last line of the code that creates your GUI.
doThing.setBounds(250, 150, 100, 25);
If you use a layout manager, you never need to call method setBounds.
if(input != "0"){
This is not the way to compare strings. Use method equals as you have done here
if(check.equals("Do a Thing")){
Here is my rewrite of your application. Note that since I could not find the code for class MoneySorter, in your question, I just created my own version of that class. The point is to show how to change the text of the JLabel after clicking on the JButton and not how to create the actual text to display.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MoneySorterRunner implements ActionListener {
private MoneySorter sorter = new MoneySorter();
private JTextField typeHere = new JTextField();
private JLabel num1;
private JLabel num2;
private JLabel num3;
private void createAndShowGui() {
JFrame frame = new JFrame("Money Calculator - v0.1a");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(createLabels(), BorderLayout.PAGE_START);
frame.add(createForm(), BorderLayout.CENTER);
frame.setSize(550, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createForm() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
panel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));
typeHere = new JTextField(10);
panel.add(typeHere);
JButton doThing = new JButton("Do a Thing");
doThing.addActionListener(this);
panel.add(doThing);
return panel;
}
private static JLabel createLabel(String text) {
JLabel label = new JLabel(text);
label.setFont(new Font("Arial", Font.PLAIN, 25));
return label;
}
private JPanel createLabels() {
JPanel panel = new JPanel(new GridLayout());
num1 = createLabel("num1");
panel.add(num1);
num2 = createLabel("num2");
panel.add(num2);
num3 = createLabel("num3");
panel.add(num3);
return panel;
}
public static void main(String args[]) {
new MoneySorterRunner().createAndShowGui();
}
public void actionPerformed(ActionEvent event){
String check = event.getActionCommand();
if(check.equals("Do a Thing")){
String text = typeHere.getText();
if (!text.isEmpty()) {
double money = Double.parseDouble(text);
num1.setText(sorter.divQuarter(money));
num2.setText(sorter.divQuarter(money));
num3.setText(sorter.divHalf(money));
}
}
}
}
class MoneySorter {
public String divQuarter(double money) {
return "divQuarter(" + money + ")";
}
public String divHalf(double money) {
return "divHalf(" + money + ")";
}
}
This is how your GUI looked when I ran your original code (as posted in your question).
This is how the GUI looks when running the code in this answer.
After launching
After entering a value and clicking the JButton
It looks like you forgot to set the ActionListener. You should also change your method to another name, because your method has the same name as the actionPerformed of the ActionListener.
doThing.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new MoneySorterRunner().actionPerformedMethod(e);
}
});
You forgot to add the ActionListener.
In order to fix this, you need to do two things:
Add this statement to your code, preferably near where you create the button (so that it is easier to keep track). -
doThing.addActionListener(this);
When you write "public class", you also need this keyword: implements ActionListener - meaning your class (basically the first line) should look like:
public class MoneySorterRunner implements ActionListener
And that should make it work.
This code is about user inserting text in text field and transfer the text to label then user can choose font style in JComboBox where the text being displayed will changed font if the user choose font.
package hw;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class HW {
public static void main(String[] args) {
/*from this code is adding the frame, label, textfield, panels, panel background color and the location of the labels and textfields*/
String [] cb = {"Comic Sans MS", "Times New Roman", "Arial Black"};
JFrame frames = new JFrame();
frames.setVisible(true);
frames.setSize(700, 500);
frames.setResizable(false);
frames.setLocation(170, 100);
JPanel panels = new JPanel();
frames.add(panels);
panels.setBackground(new Color(40, 136, 168));
panels.setLayout(null);
JTextField tf1 = new JTextField();
panels.add(tf1);
tf1.setBounds(90, 150, 100, 25);
JLabel label1 = new JLabel("ENTER TEXT");
panels.add(label1);
label1.setBounds(100, 30, 150, 100);
JLabel label2 = new JLabel("FONT STYLE");
panels.add(label2);
label2.setBounds(400, 30, 150, 100);
JComboBox combo = new JComboBox(cb);
panels.add(combo);
combo.setBounds(400, 150, 150, 25);
JLabel label3 = new JLabel("");
panels.add(label3);
label3.setBounds(310, 250, 150, 100);
label3.setText("");
/* this part below is the itemlistener and itemevent, i dont know the if this part below is correct because the font in the inserted text wont change but the text being insert in textfield is showing up in the jlabel*/
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event){
String word;
if (event.getStateChange()==ItemEvent.SELECTED){
label3.setText(word=tf1.getText());
label3.setFont(new Font("Comic Sans MS", Font.PLAIN, 14));
}
else if (event.getStateChange()==ItemEvent.SELECTED) {
label3.setText(word=tf1.getText());
label3.setFont(new Font("Times New Roman", Font.PLAIN, 14));
}
else if (event.getStateChange()==ItemEvent.SELECTED) {
label3.setText(word=tf1.getText());
label3.setFont(new Font("Arial Black", Font.PLAIN, 14));
}
/* the else and else if statement is not working, i dont know how to correct this problem*/
}
}
});
}
}
I have trouble correcting this problem, I dont know where is the main source of the problem why fonts wont change if they being choose in JComboBox.
This fixes the multiple logic problems in the itemStateChanged method (and works for each of the fonts). I would typically use an ActionListener for combo boxes, but YMMV.
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
String fontName = combo.getSelectedItem().toString();
if (event.getStateChange() == ItemEvent.SELECTED) {
label3.setText(tf1.getText());
label3.setFont(new Font(fontName, Font.PLAIN, 14));
}
}
});
I am a beginner to java and stuck with the below issue.
The purpose is to display the login window when log out button is pressed.
First JFrame window displayed is "Plain" with 2 fields username and password(I will be adding the log in functionality later)
When I press the submit button the JFrame "NEw Window" is displayed with the button "LOGOUT"
What I would like to do is that when the "LOGOUT" is pressed the "NEw Window" should close and the "Plain" window should open.
Present issue: When "LOGOUT" button is pressed the "NEw Window" is opening up.
Please correct the code so that I get the desired functionality
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class Test implements ActionListener{
JButton submit;
JFrame j;
JFrame jf;
public Test()
{
j = new JFrame("PLAIN");
j.setBounds(500,150,300,400);
j.setVisible(true);
j.setDefaultCloseOperation(j.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
j.add(panel);
panel.setSize(50, 50);
panel.setLayout(null);
JLabel label = new JLabel("User Name");
label.setSize(10,10);
label.setBounds(100, 30, 400, 30);
panel.add(label);
JTextField username = new JTextField(10);
username.setSize(10,10);
username.setBounds(300, 30, 400, 30);
panel.add(username);
JLabel password= new JLabel("Password");
password.setBounds(100, 90, 400, 30);
panel.add(password);
JPasswordField pass = new JPasswordField(10);
pass.setBounds(300, 90, 400, 30);
panel.add(pass);
submit = new JButton("Submit");
submit.setSize(10, 10);
submit.setBounds(300, 160, 200, 40);
panel.add(submit);
submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
j.setVisible(false);
jf = new JFrame("NEw Window");
jf.setVisible(true);
jf.setBounds(500,150,300,400);
JPanel panel2 = new JPanel();
panel2.setLayout(null);
jf.add(panel2);
JButton logout = new JButton("LOGOUT");
logout.setBounds(100, 30, 400, 30);
panel2.add(logout);
logout.addActionListener(this);
jf.setDefaultCloseOperation(j.EXIT_ON_CLOSE);
}
public void actionPerformed1(ActionEvent e1) {
jf.dispose();
j.setVisible(true);
}
public static void main(String args[])
{
new Test();
}
}
Some Points:
Call JFrame#setVisible() in the end after adding all the components.
Never use null layout at all instead use proper Layout Manager.
Read more A Visual Guide to Layout Managers where all the layout manger are described in detail along with sample code.
Use SwingUtilities.invokeLater() to make sure that EDT is initialized properly.
Read more
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
Try with WindowConstants.DISPOSE_ON_CLOSE instead of JFrame.EXIT_ON_CLOSE.
Just put j.setVisible(true) from Test() at the end, after adding all the components.
If you want to make a new form, don't do it in the same class where you already have one because it isn`t right.
Read the book named Clean code. You also have some errors in your code and useless.
I'm working on building a program that uses JFrame. What I want for my end result, is to implement an ActionListener which will remove labels when the user clicks a button. For example: when the user clicks the JButton, one of 5 labels is removed from the frame. When they click the button again, one of the remaining 4 labels is removed...and so on a so forth, until 0 labels remain. Technically, I have the program working as required however, I'm trying to see if there is a way to implement the ActionListener event via a loop as opposed to listing an if statement for each individual label. Thank you so much!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//calls for public class to inherit features of JFrame within Java
public class NoPurchaseReason extends JFrame implements ActionListener {
private int removeText = 0;
JButton btn = new JButton("Select");
JLabel lbl = new JLabel("Found better price");
JLabel lbl1 = new JLabel("Not as shown on website");
JLabel lbl2 = new JLabel("Wrong product");
JLabel lbl3 = new JLabel("Damaged upon delivery");
JLabel lbl4 = new JLabel("None of the above");
public static void main(String[] args) {
JFrame f = new NoPurchaseReason("Please tell us why you wish to return your purchase.");
f.setBounds(300, 100, 500, 500);
f.setVisible(true);
f.setBackground(Color.blue);
}
public NoPurchaseReason(String title) {
super(title);
setLayout(null);
lbl.setBounds(40, 40, 600, 40);
btn.setBounds(320, 10, 80, 20);
lbl.setBounds(100, 40, 100, 20);
lbl1.setBounds(100, 70, 100, 20);
lbl2.setBounds(100, 100, 150, 20);
lbl3.setBounds(100, 130, 100, 20);
lbl4.setBounds(100, 160, 100, 20);
add(btn);
add(lbl);
add(lbl);
add(lbl1);
add(lbl2);
add(lbl3);
add(lbl4);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
removeText++;
if (removeText == 1) {
lbl.setVisible(false);
lbl1.setBounds(100, 40, 100, 20);
lbl2.setBounds(100, 70, 100, 20);
lbl3.setBounds(100, 100, 150, 20);
lbl4.setBounds(100, 130, 100, 20);
}
if (removeText == 2) {
lbl1.setVisible(false);
lbl2.setBounds(100, 40, 100, 20);
lbl3.setBounds(100, 70, 150, 20);
lbl4.setBounds(100, 100, 100, 20);
}
if (removeText == 3) {
lbl2.setVisible(false);
lbl3.setBounds(100, 40, 150, 20);
lbl4.setBounds(100, 70, 100, 20);
}
if (removeText == 4) {
lbl3.setVisible(false);
lbl4.setBounds(100, 40, 100, 20);
}
if (removeText == 5) {
lbl4.setVisible(false);
}
}
}
Learning how to properly use layout managers will save you a lot of trouble in the long run.
You'll also find that people will tell you to adhere to the single responsibility principle, and avoid making classes that violate this principle (e.g., extending JFrame and implementing ActionListener).
You'll also hear folks tell you to prefer using actions over action listeners (if you need to share functionality across multiple components, that is).
A simple way would be to dedicate an entire panel to holding your labels, and simply remove the first label in the panel until there are no more labels. Here's an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class LabelDemo
{
public static void main(String[] args) {
String[] labels = {
"Found better price",
"Not as shown on website",
"Wrong product",
"Damaged upon delivery",
"None of the above"
};
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String s: labels) {
panel.add(new JLabel(s));
}
frame.add(panel);
JButton button = new JButton("Select");
button.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
if (panel.getComponentCount() > 0)
panel.remove(0);
frame.repaint();
}
});
frame.add(button, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
}
Also, you may just have a certain goal in mind that I'm not aware of, but it honestly seems like a list would be better in this case. Here's an example of that as well:
String[] labels = {
"Found better price",
"Not as shown on website",
"Wrong product",
"Damaged upon delivery",
"None of the above"
};
JList<String> list = new JList<>(labels);
int option = JOptionPane.showConfirmDialog(null, list,
"Please tell us why you wish to return your purchase.",
JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String selectedValue = list.getSelectedValue();
System.out.println(selectedValue); // Do something with it.
}