JButton listener not firing - java

I seperated my codes into MVC model and now my confirm button action listener is not printing the username and password even though I added a Actionlistener for it. please help thanks.
Codes
LoginDialog.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class LoginDialog extends JDialog {
private JLabel nameLabel;
private JLabel passwordLabel;
private JTextField usernameTF;
private JPasswordField passwordTF;
private JButton confirmBtn;
private JButton cancelBtn;
private JPanel topPanel;
private JPanel buttonPanel;
private GridBagConstraints gbc;
public LoginDialog() {
this.setTitle("Authentication");
topPanel = new JPanel(new GridBagLayout());
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
nameLabel = new JLabel("Name : ");
passwordLabel = new JLabel("Password : ");
usernameTF = new JTextField();
passwordTF = new JPasswordField();
confirmBtn = new JButton("Confirm");
cancelBtn = new JButton("Cancel");
buttonPanel.add(confirmBtn);
buttonPanel.add(cancelBtn);
gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0;
topPanel.add(nameLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
topPanel.add(usernameTF, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
topPanel.add(passwordLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
topPanel.add(passwordTF, gbc);
this.add(topPanel);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public void showLoginDialog() {
LoginDialog ld = new LoginDialog();
ld.setSize(400, 150);
ld.setVisible(true);
ld.setLocationRelativeTo(null);
}
public String getUsername() {
return usernameTF.getText();
}
public String getPassword() {
return new String(passwordTF.getPassword());
}
public void confirmBtnListner(ActionListener listener) {
confirmBtn.addActionListener(listener);
}
}
Controller.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller {
private LoginDialog loginDialog;
public Controller(LoginDialog loginDialog) {
this.loginDialog = loginDialog;
loginDialog.showLoginDialog();
loginDialog.confirmBtnListner(new BtnListener());
}
class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(loginDialog.getUsername());
System.out.println(loginDialog.getPassword());
}
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog();
new Controller(loginDialog);
}
}

You are having two instances of LoginDialog class.
One you are creating in your controller and the other one is in your LoginDialog#showLoginDialog() method.
Let's list them:
1st instance - In the controller class named `loginDialog`
2nd instance - In the `LoginDialog` class named `ld`
Here ld is an object created within loginDialog object. But they are two different JDialog objects. When you call
loginDialog.showLoginDialog()
another object ld is created from within the method. The JDialog refered is set to visible by:
ld.setVisible(true)
So now,
Object `ld` is visible
And Object `loginDialog` is NOT yet visible as you havent done `loginDialog.setVisible(true)` yet.
Now are adding the ActionListener to the button within loginDialog object, which is not yet visible. While there is no ActionListener added to the Button within ld object.
Final conclusion:
Object ld is visible, but button within it has NO ActionListener.
Object loginDialog is NOT yet visible. But the button within it has an ActionListener.
The button you are clicking is a part of ld object which has NO action listener associated to it.
The button which has an ActionListener associated to it is a part of loginDialog object which is NOT visible.
Wanna check if I am right?
Just add these lines in your controller constructor:
loginDialog.setVisible(true);
loginDialog.setSize(400, 150);
loginDialog.setLocationRelativeTo(null);
I won't give you the full solution as we don't spoonfeed here on stack overflow. So it's a challange for you to adjust your code accordingly. :)

The method showLoginDialog() creates a new instance of your dialog, which does not have the actionlistener.
fix: don't create a new instance - use the one you have.
public void showLoginDialog() {
setSize(400, 150);
setVisible(true);
setLocationRelativeTo(null);
}

Related

Trying to do a JTable which adds data from a JTextField

I'm trying to do code that adds a row to a JTable. I type but nothing shows up. My showMessageDialog also has an error.
Does anyone know how I can rewrite the code?
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import static javax.swing.JOptionPane.showMessageDialog;
public class JTABEL extends Component {
private JPanel panel1;
private JLabel Name;
private JLabel Age;
private JLabel Class;
private JTextField enterNameTextField;
private JTextField Agefield;
private JTextField EnterClassField;
private JTable Table;
private JButton saveButton;
public JTABEL() {
saveButton.addActionListener(this::actionPerformed);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Jtable");
frame.setContentPane(new JTABEL().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void actionPerformed(ActionEvent e) {
if (enterNameTextField.getText().equals("") || Agefield.getText().equals("") ||
EnterClassField.getText().equals("")) {
showMessageDialog(this, "please Enter all Data");
} else {
String data[] = {enterNameTextField.getText(), Agefield.getText(),
EnterClassField.getText()};
DefaultTableModel tableModel = (DefaultTableModel) Table.getModel();
tableModel.addRow(new Object[]{enterNameTextField.getText(), Agefield.getText(),
EnterClassField.getText()});
showMessageDialog(this, "Add Data Successfully");
enterNameTextField.setText("");
Agefield.setText("");
EnterClassField.setText("");
}
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
I created the following GUI.
Here's the same GUI after adding a couple of students.
Explanation
The model–view–controller (MVC) pattern is useful when creating a Swing application. The name implies that you create the model first, then the view, then the controller.
An application model is made up of one or more plain Java getter/setter classes.
A Swing view is one JFrame with one or more JPanels. The view displays the contents of the model. The view does not modify the model.
Each Swing ActionListener is a controller. The controllers update the model.
Model
I created two model classes. The Student class holds a name, age, and class.
The JTableModel class holds the DefaultTableModel for the JTable.
View
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
I created a JFrame and two JPanels. One JPanel holds the JTable and the other JPanel holds the add student form. The JFrame has a default BorderLayout. I placed the table JPanel in the center and the form JPanel on the east side.
The table JPanel uses a BorderLayout. The JTable is placed inside of a JScrollPane. The JScrollPane is placed inside of the table JPanel in the center.
The form JPanel uses a GridBagLayout to create a form structure JPanel.
Complete explanations of all the Swing layout managers can be found in the Oracle tutorial.
Controller
The anonymous JButton ActionListener checks to see if the fields have been typed. If so, a Student instance is created and passed to the application model. If not, an error display pops up.
Code
Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class JTableExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JTableExample());
}
private final JTableModel model;
private JFrame frame;
private JTextField nameField, ageField, classField;
public JTableExample() {
this.model = new JTableModel();
}
#Override
public void run() {
frame = new JFrame("JTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTablePanel(), BorderLayout.CENTER);
frame.add(createAddPanel(), BorderLayout.EAST);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTablePanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTable table = new JTable(model.getTableModel());
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private JPanel createAddPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("Name:");
panel.add(label, gbc);
gbc.gridx++;
nameField = new JTextField(20);
panel.add(nameField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("Age:");
panel.add(label, gbc);
gbc.gridx++;
ageField = new JTextField(20);
panel.add(ageField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("Class:");
panel.add(label, gbc);
gbc.gridx++;
classField = new JTextField(20);
panel.add(classField, gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton button = new JButton("Add Student");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String name = nameField.getText().trim();
String ageString = ageField.getText().trim();
String level = classField.getText().trim();
if (name.isEmpty() || ageString.isEmpty() || level.isEmpty()) {
JOptionPane.showMessageDialog(
frame, "Please enter all information");
return;
}
int age = getAge(ageString);
if (age > 0) {
model.addStudent(new Student(name, age, level));
clearInputFields();
}
}
private int getAge(String ageString) {
int age = -1;
try {
age = Integer.valueOf(ageString);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(
frame, "Please enter a numeric age");
}
return age;
}
private void clearInputFields() {
nameField.setText("");
ageField.setText("");
classField.setText("");
nameField.requestFocus();
}
});
panel.add(button, gbc);
frame.getRootPane().setDefaultButton(button);
return panel;
}
public class JTableModel {
private final DefaultTableModel tableModel;
public JTableModel() {
this.tableModel = new DefaultTableModel();
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("Class");
}
public void addStudent(Student student) {
Object[] rowData = new Object[3];
rowData[0] = student.getName();
rowData[1] = student.getAge();
rowData[2] = student.getLevel();
tableModel.addRow(rowData);
}
public DefaultTableModel getTableModel() {
return tableModel;
}
}
public class Student {
private final int age;
private final String level, name;
public Student(String name, int age, String level) {
this.name = name;
this.age = age;
this.level = level;
}
public int getAge() {
return age;
}
public String getLevel() {
return level;
}
public String getName() {
return name;
}
}
}

ActionListener, List Issue

I am running into an issue with my program. The objective is to collect input (movie name, media type and the year) and append it to a list when "add movie" is clicked. Then when the "show movies" button is clicked the list will display in the text area. I'm not sure what I am missing or what I've done wrong.
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MovieDatabase extends JFrame implements ActionListener{
//create LinkedList of Movie Objects
LinkedList<Movie> list = new LinkedList<Movie>();
//JPanel for input movie
private JPanel inputJPanel;
//JLable and JTextField for Movie Name
private JLabel movieJLabel;
private JTextField movieJTextField;
//JLable and JTextField for Media
private JLabel mediaJLabel;
private JTextField mediaJTextField;
//JLable and JTextField for Release Year
private JLabel yearJLabel;
private JTextField yearJTextField;
//JButton to add movie to a list
private JButton addJButton;
//JButton to show movie in text area
private JLabel showJLabel;
private JButton showJButton;
//JTextArea to display movies from list
private JTextArea showJTextArea;
private JPanel listJPanel;
//no argument constructor
public MovieDatabase(){
createUserInterface();
}
//create GUI window with components
private void createUserInterface(){
//get content pane window and set layout to null - no layout manager
Container contentPane = getContentPane();
contentPane.setLayout(null);
//set up input panel
inputJPanel = new JPanel();
inputJPanel.setLayout(null);
inputJPanel.setBorder(new TitledBorder("Input Movie")); //anonymous object
inputJPanel.setBounds(20,4,260,178);// (x,y,w,h)
contentPane.add(inputJPanel);
//set up input panel
showJLabel = new JLabel();
showJLabel.setLayout(null);
showJLabel.setText("Movies: ");
showJLabel.setBounds(300,0,260,25);// (x,y,w,h)
contentPane.add(showJLabel);
//set up payment JTextArea here
showJTextArea = new JTextArea();
showJTextArea.setBounds(300,30,300,145);// (x,y,w,h)
showJTextArea.setEditable(false);
contentPane.add(showJTextArea);
//show movies JButton
showJButton = new JButton();
showJButton.setBounds(480,175,110,30);
showJButton.setText("Show Movies");
contentPane.add(showJButton);
//movie name JLabel
movieJLabel = new JLabel();
movieJLabel.setBounds(10,24,100,21);// (x,y,w,h)
movieJLabel.setText("Movie Name:");
inputJPanel.add(movieJLabel);
//movie name JTextField
movieJTextField = new JTextField();
movieJTextField.setBounds(104,24,120,21);
movieJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputJPanel.add(movieJTextField);
//media name JLabel
mediaJLabel = new JLabel();
mediaJLabel.setBounds(10,54,100,21);// (x,y,w,h)
mediaJLabel.setText("Media:");
inputJPanel.add(mediaJLabel);
//media name JTextField
mediaJTextField = new JTextField();
mediaJTextField.setBounds(104,54,120,21);
mediaJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputJPanel.add(mediaJTextField);
//year name JLabel
yearJLabel = new JLabel();
yearJLabel.setBounds(10,84,100,21);// (x,y,w,h)
yearJLabel.setText("Release Year:");
inputJPanel.add(yearJLabel);
//year name JTextField
yearJTextField = new JTextField();
yearJTextField.setBounds(104,84,80,21);
yearJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputJPanel.add(yearJTextField);
//add movie JButton
addJButton = new JButton();
addJButton.setBounds(92,138,94,24);
addJButton.setText("Add Movie");
inputJPanel.add(addJButton);
//set window properties
setTitle("Movie"); //set title bar
setSize(625, 250);//window size
setVisible(true); //display window
addJButton.addActionListener(this);
showJButton.addActionListener(this);
}
public void addButtonactionPerformed(ActionEvent e){
String movieName = movieJTextField.getText();
String media = mediaJTextField.getText();
int year = Integer.parseInt(yearJTextField.getText());
//create instance of Movie
Movie movie = new Movie(movieName, media, year);
list.add(movie);
movieJTextField.setText("");
mediaJTextField.setText("");
yearJTextField.setText("");
}
private void showButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
showJTextArea.setText("");
String str = String.format("%-20s%-20s%-20s\n", "Year", "Media", "Title");
showJTextArea.append(str);
for (Movie movie : list) {
str = String.format("%-20s%-19s%-22s\n", Integer.toString(movie.year), movie.media, movie.name);
showJTextArea.append(str);
}
}
}
class Movie{
String name;
String media;
int year;
public Movie(String n, String m, int y){
name = n;
media = m;
year = y;
}
public class MovieGUI {
public static void main(String[] args) {
MovieDatabase application = new MovieDatabase();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//close and stop application
}
}
null layouts are going to come back to haunt you. There is no such thing as "pixel perfect" layouts, there are just to many variables associated with the differences in the way things get rendered between different hardware and OSs to even consider making this choice.
Take the time to learn how to use the layout managers Laying Out Components Within a Container
You've not implemented the requirements for ActionListener (showButtonActionPerformed suggests that you're using something like Netbeans form editor).
Maybe you should take a look at How to Write an Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons
You might also want to look at How to Use Tables
To my mind, you need to take a slightly different tact and focus on separating the areas of responsibility. Collecting the movie information has nothing with either storing the results or displaying them, so I'd have those separated into it's own container, so you can more easily manage it.
This leads to the question of, "how do you notify interested parties when a user 'adds' a movie?". Interestingly, you're somewhat already familiar with the concept.
Essentially, you use a "listener" or, as it's more commonly known, an "observer pattern". This allows you to notify interested parties that something has happened, in this case, a user has created a new movie.
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MovieManagerPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Movie {
String name;
String media;
int year;
public Movie(String n, String m, int y) {
name = n;
media = m;
year = y;
}
public String getName() {
return name;
}
public String getMedia() {
return media;
}
public int getYear() {
return year;
}
}
public class MovieManagerPane extends JPanel {
private JTextArea moviesTextArea;
private List<Movie> movies = new ArrayList<>(32);
public MovieManagerPane() {
setLayout(new BorderLayout());
moviesTextArea = new JTextArea(20, 40);
String str = String.format("%-20s%-20s%-20s\n", "Year", "Media", "Title");
moviesTextArea.append(str);
MoviePane moviePane = new MoviePane();
moviePane.setBorder(new CompoundBorder(new TitledBorder("Input Movie"), new EmptyBorder(4, 4, 4, 4)));
moviePane.addMovieListener(new MoviePane.MovieListener() {
#Override
public void movieWasAdded(MoviePane source, Movie movie) {
movies.add(movie);
String str = String.format("%-20s%-20s%-20s\n", movie.getYear(), movie.getMedia(), movie.getName());
moviesTextArea.append(str);
}
});
add(moviePane, BorderLayout.LINE_START);
add(moviesTextArea);
}
}
public class MoviePane extends JPanel {
public static interface MovieListener extends EventListener {
public void movieWasAdded(MoviePane source, Movie movie);
}
//JLable and JTextField for Movie Name
private JLabel movieJLabel;
private JTextField movieJTextField;
//JLable and JTextField for Media
private JLabel mediaJLabel;
private JTextField mediaJTextField;
//JLable and JTextField for Release Year
private JLabel yearJLabel;
private JTextField yearJTextField;
//JButton to add movie to a list
private JButton addJButton;
public MoviePane() {
setLayout(new GridBagLayout());
movieJLabel = new JLabel("Movie Name:");
mediaJLabel = new JLabel("Media:");
yearJLabel = new JLabel("Release Year:");
movieJTextField = new JTextField(10);
mediaJTextField = new JTextField(10);
yearJTextField = new JTextField(10);
addJButton = new JButton("Add Movie");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = gbc.EAST;
gbc.insets = new Insets(4, 4, 4, 4);
add(movieJLabel, gbc);
gbc.gridy++;
add(mediaJLabel, gbc);
gbc.gridy++;
add(yearJLabel, gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = gbc.WEST;
add(movieJTextField, gbc);
gbc.gridy++;
add(mediaJTextField, gbc);
gbc.gridy++;
add(yearJTextField, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 1;
gbc.anchor = gbc.SOUTH;
add(addJButton, gbc);
addJButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
// Use a JSpinner or JFornattedTextField to avoid this
int year = Integer.parseInt(yearJTextField.getText());
Movie movie = new Movie(movieJTextField.getText(), mediaJTextField.getText(), year);
fireMovieWasAdded(movie);
} catch (NumberFormatException exp) {
JOptionPane.showMessageDialog(MoviePane.this, "Invalid year", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
public void addMovieListener(MovieListener listener) {
listenerList.add(MovieListener.class, listener);
}
public void removeMovieListener(MovieListener listener) {
listenerList.remove(MovieListener.class, listener);
}
protected void fireMovieWasAdded(Movie movie) {
MovieListener[] listeners = listenerList.getListeners(MovieListener.class);
if (listeners.length == 0) {
return;
}
for (MovieListener listener : listeners) {
listener.movieWasAdded(this, movie);
}
}
}
}
You may also want to take a look at How to Use Spinners and How to Use Formatted Text Fields for dealing with "non-string" input

java frame not changing colour

I am unable to change the colour of my frame in Java code below. I know the code to change it would be frame.getContentPane().setBackground(Color.gray); However, this is not working for me, I am not sure what is the reason behind this, but if you are able to solve the problem do let me know, thank you.
public class UserLoginPage implements ActionListener {
//Put all JLabels,Frames and buttons here etc
JPanel panel = new JPanel();
JFrame frame = new JFrame();
JLabel userLabel = new JLabel("Username");
JLabel passwordLabel = new JLabel("Password");
JTextField userText = new JTextField();
JTextField passwordText = new JTextField();
JButton loginButton = new JButton("Login");
//Label for successful login
JLabel success = new JLabel();
//Default Constructor to add the frames and panels etc
public UserLoginPage(){
panel.setLayout(null);
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);
userText.setBounds(100,20,165,25);
panel.add(userText);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
loginButton.setBounds(10,80,80,25);
loginButton.addActionListener(this);
panel.add(loginButton);
success.setBounds(10,110,300,25);
panel.add(success);
//success.setText();
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.gray);
frame.setVisible(true);
frame.add(panel);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UserLoginPage();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
String user = userText.getText();
String password = passwordText.getText();
System.out.println(user + ", " + password);
if(user.equals("Jackson") && password.equals("1234")){
JOptionPane.showMessageDialog(frame,"Login successful");
}
else{
JOptionPane.showMessageDialog(frame,"Invalid password or username");
}
}
}
You're adding panel, a JPanel to your JFrame, and since JFrame's contentPane uses a BorderLayout, this JPanel (which is opaque), will completely cover the contentPane, preventing visualization of the contentPane's background.
Solution:
Either make the panel not-opaque via panel.setOpaque(false); so that now its container's colors or images will show through
or leave it default opaque give it and not the contentPane the background color of choice.
Unrelated issue is here:
panel.setLayout(null)
You really don't want to be doing this for many reasons, including because this will make your GUI work well / look nice on only one platform. It also makes it very hard to upgrade and enhance the GUI later.
For example, and incorporating some of Andrew Thompson's suggestions, here is an example login GUI that is geared towards creating a JPanel, one that in this example is placed into a modal JDialog (similar to a JOptionPane but with more flexibility) and displayed. The code uses GridBagLayout along with GridBagConstraints when adding components to place them where I want them to be in a pleasing way that works on all platforms, and that allows ease and flexibility should I want to add more components:
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class UserLoginPanel extends JPanel {
private static final Color BACKGROUND = new Color(200, 200, 200);
private JTextField userText = new JTextField(15);
private JPasswordField passwordText = new JPasswordField(15);
LoginAction loginAction = new LoginAction(this, "Login", KeyEvent.VK_L);
JButton loginButton = new JButton(loginAction);
public UserLoginPanel() {
super(new GridBagLayout());
setBackground(BACKGROUND);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
int insetGap = 4;
gbc.insets = new Insets(insetGap, insetGap, insetGap, insetGap);
add(new JLabel("User Name:"), gbc);
gbc.gridx = 1;
add(userText, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(new JLabel("Password"), gbc);
gbc.gridx = 1;
add(passwordText, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
add(loginButton, gbc);
insetGap = 8;
setBorder(BorderFactory.createEmptyBorder(insetGap, insetGap, insetGap, insetGap));
}
public String getUserName() {
return userText.getText();
}
public char[] getPassword() {
return passwordText.getPassword();
}
public static void main(String[] args) {
UserLoginPanel loginPanel = new UserLoginPanel();
JDialog dialog = new JDialog(null, "User Login", ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.add(loginPanel);
dialog.pack();
dialog.setLocationByPlatform(true);
dialog.setVisible(true);
}
}
#SuppressWarnings("serial")
class LoginAction extends AbstractAction {
private UserLoginPanel loginPanel;
public LoginAction(UserLoginPanel loginPanel, String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, KeyEvent.VK_L);
this.loginPanel = loginPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String userName = loginPanel.getUserName();
char[] password = loginPanel.getPassword();
System.out.println("User Name: " + userName);
System.out.println("Password: " + new String(password));
Component source = (Component) e.getSource();
if (source != null) {
Window window = SwingUtilities.getWindowAncestor(source);
if (window != null) {
window.dispose();
}
}
}
}

Java GUI, trying to position radio buttons and check boxes

So I'm trying to create a series of radio buttons and check boxes that are displayed as follows:
Radio Button
Check Box
Radio Button
Check Box
Radio Button
However, I'm still in the learning process for java and I was wondering if anyone could solve this problem. At the moment the buttons and boxes are being displayed in the correct location, however the first radio button ("Times") is not being displayed for some reason. If you could perhaps describe the reason and a possible solution that'd be great.
Thanks
Updated Code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Question2 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Font Chooser");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints gbc = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
gbc.gridx = 0;
gbc.gridy = 1;
JCheckBox cb = new JCheckBox("Bold");
gbLayout.setConstraints(cb, gbc);
mainPanel.add(cb);
gbc.gridy = 3;
gbLayout.setConstraints(cb, gbc);
cb = new JCheckBox("Italic");
mainPanel.add(cb);
gbc.gridx = 1;
gbc.gridy = 0;
JRadioButton rb = new JRadioButton("Times");
gbLayout.setConstraints(rb, gbc);
mainPanel.add(rb, gbc);
gbc.gridy = 2;
gbLayout.setConstraints(rb, gbc);
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
gbc.gridy = 4;
gbLayout.setConstraints(rb, gbc);
rb = new JRadioButton("Courier");
mainPanel.add(rb, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
Here's the problem, you are saying each height is 3 high, but really each cell is 1.
cRadioButton.gridheight = 3; // change this to 1
Here's the full source, and I did make some of the suggested changes from the other answer because at some point you will want to do something different (different action listener implementation for each type of button).
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class MyFrame1 extends JFrame {
MyFrame1(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints gbc = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
gbc.gridx = 0;
gbc.gridy = 1;
JCheckBox italic = new JCheckBox("Italic");
gbLayout.setConstraints(italic, gbc);
mainPanel.add(italic);
JCheckBox bold = new JCheckBox("Bold");
gbc.gridy = 3;
gbLayout.setConstraints(bold, gbc);
mainPanel.add(bold);
gbc.gridx = 1;
gbc.gridy = 0;
JRadioButton times = new JRadioButton("Times");
gbLayout.setConstraints(times, gbc);
mainPanel.add(times, gbc);
gbc.gridy = 2;
JRadioButton helv = new JRadioButton("Helvatica");
gbLayout.setConstraints(helv, gbc);
mainPanel.add(helv, gbc);
gbc.gridy = 4;
JRadioButton courier = new JRadioButton("Courier");
gbLayout.setConstraints(courier, gbc);
mainPanel.add(courier, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
MyFrame1 f = new MyFrame1("Font Chooser");
f.init();
}
}
It seems like you keep reassigning the same object, which may be leading to your overlapping. Instead of
JRadioButton rb = new JRadioButton("Times");
//...
newPanel.add(rb);
rb = new JRadioButton("Helvatica");
//...
newPanel.add(rb);
//and so on
try something like
JRadioButton times = new JRadioButton("Times");
JRadioButton helva = new JRadioButton("Helvatica");
//...
newPanel.add(times);
newPanel.add(helva);

How to close dialog window on the button click [duplicate]

This question already has answers here:
Button for closing a JDialog
(5 answers)
Closed 9 years ago.
I've created Dialog using awt and swing. In this form I hafe JTextField and okButton which is JButton. How to make the Dialog window hide on clicking okButton?
Here is my class's code:
public class QueueDialog extends JFrame implements ActionListener {
private static final long SerialVersionUID = 1L;
private static JTextField field = new JTextField(15);
private Sender sender;
private String incommingMessagesFolderUrl = "/etc/dlp/templates";
public QueueDialog() throws Exception {
sender = new Sender();
// field.setSize(60, 15);
JButton okButton = new JButton("ok");
final JLabel label = new JLabel("Enter the name of queue:");
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);
gbc.insets = new Insets(2, 0, 2, 0);
gbc.gridy = 0;
gbc.gridx = 0;
gbag.setConstraints(label, gbc);
gbc.gridy = 1;
gbc.gridx = 0;
gbag.setConstraints(field, gbc);
gbc.gridy = 2;
gbc.gridx = 0;
gbag.setConstraints(okButton, gbc);
add(okButton);
add(field);
add(label);
setTitle("Queue name");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ok")) {
// label.setText(field.getText());
send(field.getText());
}
}
});
}
}
As I mentioned in my comment (i.e, the very first comment) setVisible(false) is working absolutely fine on click of Ok button
Please Check this code again Where I have addd the statement in action listener. Just now did it to prove the solution is correct> I was not following this post hoping you must have got your answer in the comment itself
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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;
public class QueueDialog extends JFrame implements ActionListener {
private static final long SerialVersionUID = 1L;
private static JTextField field = new JTextField(15);
//private Sender sender;
private String incommingMessagesFolderUrl = "/etc/dlp/templates";
public QueueDialog() throws Exception {
// sender = new Sender();
// field.setSize(60, 15);
JButton okButton = new JButton("ok");
final JLabel label = new JLabel("Enter the name of queue:");
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);
// gbc.insets = new Insets(2, 0, 2, 0);
gbc.gridy = 0;
gbc.gridx = 0;
gbag.setConstraints(label, gbc);
gbc.gridy = 1;
gbc.gridx = 0;
gbag.setConstraints(field, gbc);
gbc.gridy = 2;
gbc.gridx = 0;
gbag.setConstraints(okButton, gbc);
add(okButton);
add(field);
add(label);
setTitle("Queue name");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ok")) {
System.out.println("Hello");
setVisible(false);
// label.setText(field.getText());
// send(field.getText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) throws Exception {
QueueDialog diag = new QueueDialog();
}
}

Categories

Resources