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

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

Related

Can someone help me how to make the button from another frame work?

Can someone help with this one? it's a system where you log in and another frame pops up. In that frame you can put 2 words and the frame will tell if the works are the same or not. But the button does not work for some reason. I've been doing this for 4 days and I really need some help.
Code
public class Userinter implements ActionListener {
//first frame
private static JLabel userLabel;
private static JTextField userText;
private static JLabel passwordLabel;
private static JPasswordField passwordText;
private static JButton button;
private static JLabel success;
//second frame
private static JLabel label1;
private static JLabel label2;
private static JTextField WordNum1;
private static JTextField WordNum2;
private static JButton button2;
private static JLabel success2;
public static void main(String[] args) {
//frame
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
//username
userLabel = new JLabel("Username");
userLabel.setBounds(80,80,80,25);
panel.add(userLabel);
userText = new JTextField(20);
userText.setBounds(180,80,165,25);
panel.add(userText);
//password
passwordLabel = new JLabel("password");
passwordLabel.setBounds(80,150,80,25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(180,150,165,25);
panel.add(passwordText);
//button
button = new JButton("Login");
button.setBounds(80,190,80,25);
button.addActionListener((ActionListener) new Userinter());
panel.add(button);
success = new JLabel("set");
success.setBounds(80,250,300,25);
panel.add(success);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String user = userText.getText();
String password = passwordText.getText();
if (user.equals("Gal") && password.equals("Skr")){
// second frame
JPanel Panel2 = new JPanel();
JFrame frame2 = new JFrame();
frame2.setSize(400,300);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setVisible(true);
frame2.add(Panel2);
Panel2.setLayout(null);
label1 = new JLabel("Set word/number here:");
label1.setBounds(10,20,200,25);
Panel2.add(label1);
WordNum1 = new JTextField();
WordNum1.setBounds(100,50,165,25);
Panel2.add(WordNum1);
label2 = new JLabel("Set word/number here:");
label2.setBounds(10,90,200,25);
Panel2.add(label2);
WordNum2 = new JTextField();
WordNum2.setBounds(100,130,165,25);
Panel2.add(WordNum2);
JButton Button2 = new JButton("Check");
Button2.setBounds(100,200,80,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e1) {
String word = WordNum1.getText();
String word2 = WordNum2.getText();
if(word.equals(word2)){
success2.setText("yes");
}
}
});
Panel2.add(Button2);
success = new JLabel("set");
success.setBounds(80,250,300,25);
Panel2.add(success);
}else
success.setText("incorrect username or/and password.");
}
}
You really need to take a look at Laying Out Components Within a Container, it is going to save you a lot of time and head aches.
import java.awt.CardLayout;
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.EventListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
private LoginPane loginPane;
private WordPane wordPane;
private CardLayout cardLayout;
public MainPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
loginPane = new LoginPane();
loginPane.addLoginListener(new LoginPane.LoginListener() {
#Override
public void didLoginSuccessfully() {
cardLayout.show(MainPane.this, "words");
}
#Override
public void didCancelLogin() {
SwingUtilities.windowForComponent(MainPane.this).dispose();
}
});
wordPane = new WordPane();
add(loginPane, "login");
add(wordPane, "words");
}
}
public class WordPane extends JPanel {
public WordPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = gbc.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
add(new JLabel("Set word/number here:"), gbc);
gbc.gridy++;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.LINE_END;
add(new JLabel("First word:"), gbc);
gbc.gridy++;
add(new JLabel("Second word:"), gbc);
gbc.gridx++;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
JTextField firstWordField = new JTextField(10);
JTextField secondWordField = new JTextField(10);
add(firstWordField, gbc);
gbc.gridy++;
add(secondWordField, gbc);
JButton checkButton = new JButton("Check");
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = gbc.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
add(checkButton, gbc);
checkButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (firstWordField.getText().equals(secondWordField.getText())) {
JOptionPane.showMessageDialog(WordPane.this, "Words match", "Match", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(WordPane.this, "Words do not match", "Does Not Match", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
public class LoginPane extends JPanel {
public interface LoginListener extends EventListener {
// Probably should pass in the User which was authenticiated,
// but I'll leave that to you to figure out
public void didLoginSuccessfully();
public void didCancelLogin();
}
private JTextField userNameField;
private JPasswordField passwordField;
private JButton loginButton;
private JButton cancelButton;
public LoginPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(8, 8, 8, 8);
add(new JLabel("User name:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
DocumentListener documentListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
fieldsDidChange();
}
#Override
public void removeUpdate(DocumentEvent e) {
fieldsDidChange();
}
#Override
public void changedUpdate(DocumentEvent e) {
fieldsDidChange();
}
};
userNameField.getDocument().addDocumentListener(documentListener);
passwordField.getDocument().addDocumentListener(documentListener);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
add(userNameField, gbc);
gbc.gridy++;
add(passwordField, gbc);
loginButton = new JButton("Login");
loginButton.setEnabled(false);
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
performLogin();
}
});
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
performCancel();
}
});
JPanel buttonPane = new JPanel(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = gbc.HORIZONTAL;
buttonPane.add(loginButton, gbc);
gbc.gridx++;
buttonPane.add(cancelButton, gbc);
gbc = new GridBagConstraints();
gbc.gridy = 2;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(buttonPane, gbc);
}
public void addLoginListener(LoginListener listener) {
listenerList.add(LoginListener.class, listener);
}
public void removeLoginListener(LoginListener listener) {
listenerList.remove(LoginListener.class, listener);
}
protected void fireDidLoginSuccessfully() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
System.out.println(listeners.length);
if (listeners.length == 0) {
return;
}
for (LoginListener listener : listeners) {
listener.didLoginSuccessfully();
}
}
protected void fireDidCancel() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
if (listeners.length == 0) {
return;
}
for (LoginListener listener : listeners) {
listener.didCancelLogin();
}
}
protected void fieldsDidChange() {
if (userNameField.getText().length() > 0 && passwordField.getPassword().length > 0) {
loginButton.setEnabled(true);
} else {
loginButton.setEnabled(false);
}
}
protected void performLogin() {
// Peform the authentication
// In a production system, it would be fesible to have this
// done via a different class passed into this class
fireDidLoginSuccessfully();
}
protected void performCancel() {
fireDidCancel();
}
}
}
As to you "question"
This...
button.addActionListener((ActionListener) new Userinter());
is going to generate a disconnection between what is displayed on the UI and what you code is going to executing against, as you have two instance of Userinter

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

Cant set textLabel because it contradicts parseDouble

I have an ItemListener that looks like this:
private class Listener implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
calculate();
}
}
At the bottom of my calculate() method, I set these labels like this:
subtotalLbl.setText("\t\t\t\t\t\t\t\tSubtotal:\t\t\t\t\t\t\t\t\t " + String.valueOf(determinedSubTotal + priceIncrease) + "\t\t\t\t\t\t\t\t\t");
taxLbl.setText("\t\t\t\t\t\t\t\tTax:\t\t\t\t\t\t\t\t\t " + String.valueOf(determinedTax + priceIncrease) + "\t\t\t\t\t\t\t\t\t");
totalLbl.setText("\t\t\t\t\t\t\tTotal:\t\t\t\t\t\t\t\t\t " + String.valueOf(determinedTotal + priceIncrease) + "\t\t\t\t\t\t\t\t\t");
Then I have an ActionListener that uses the text from the totalLbl for parseDouble
private class BtnClicked implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String input = totalLbl.getText().trim();
Double parsedString = Double.parseDouble(input) * 0.20;
Object src = e.getSource();
if(src == submit)
{
JOptionPane.showMessageDialog(null,"Thank you for your order - the tip will be " + fmt.format(parsedString), "Thank you" , JOptionPane.INFORMATION_MESSAGE);
}
else if(src == cancel)
{
JOptionPane.showMessageDialog(null,"Order was canceled" ,"Order Canceled" , JOptionPane.INFORMATION_MESSAGE);
}
}
Obviously the program is crashing at the line inside of the BtnClicked's actionPerformed method where parseDouble(input) is at, because the totalLbl JLabel has "Total:" in it.. where else would I set this or how would I work around this? The "Total:" is required. (can't use split() )
Here's a screenshot of what the entire JFrame looks like, program crashes when clicking the submit button:
Create two JLables, one which says Total: the other which actually holds the total value.
So your total calculation would look more like...
totalLblText.setText("Total:");
totalLbl.setText(String.valueOf(determinedTotal + priceIncrease));
Then you won't need to care.
You should make better use of your layout managers in order to support the formatting your trying to achieve rather than using formatting characters like \t, these will always end up in a mess
Updated with layout example
This simple example demonstrates how you might use a layout managers (and a technique known as compound layouts) and relieve the need to try and use a single label for displaying more information then it should...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout {
public static void main(String[] args) {
new TestLayout();
}
public TestLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField numberOfPizzas;
private JCheckBox pepperoni;
private JCheckBox sausage;
private JCheckBox peppers;
private JCheckBox onions;
private JCheckBox mushrooms;
private JCheckBox extracheese;
private JLabel lblSubTotal;
private JLabel lblTax;
private JLabel lblTotal;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
JPanel header = new JPanel();
JPanel extras = new JPanel(new GridBagLayout());
JPanel totals = new JPanel(new GridBagLayout());
add(header, gbc);
gbc.gridy++;
add(extras, gbc);
gbc.gridy++;
add(totals, gbc);
numberOfPizzas = new JTextField(5);
header.add(new JLabel("Number of pizzas"));
header.add(numberOfPizzas);
gbc = new GridBagConstraints();
pepperoni = new JCheckBox("Pepperoni");
sausage = new JCheckBox("Sausage");
peppers = new JCheckBox("Peppers");
onions = new JCheckBox("Onions");
mushrooms = new JCheckBox("mushrooms");
extracheese = new JCheckBox("Extra Cheeses");
JCheckBox left[] = new JCheckBox[] {pepperoni, peppers, mushrooms};
JCheckBox right[] = new JCheckBox[] {sausage, onions, extracheese};
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 0;
gbc.gridy = 0;
add(left, extras, 0, 1, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
add(right, extras, 0, 1, gbc);
gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(2, 12, 2, 12);
totals.add(new JLabel("Subtotal:"), gbc);
gbc.gridy++;
totals.add(new JLabel("Tax:"), gbc);
gbc.gridy++;
totals.add(new JLabel("Total:"), gbc);
gbc.weightx = 0;
gbc.gridx = 1;
gbc.gridy = 0;
lblSubTotal = new JLabel("8.0");
lblTax = new JLabel("0.78");
lblTotal = new JLabel("8.78");
totals.add(lblSubTotal, gbc);
gbc.gridy++;
totals.add(lblTax, gbc);
gbc.gridy++;
totals.add(lblTotal, gbc);
}
protected void add(JComponent[] comps, JComponent parent, int deltaX, int deltaY, GridBagConstraints gbc) {
for (JComponent comp : comps) {
parent.add(comp, gbc);
gbc.gridy += deltaY;
gbc.gridx += deltaX;
}
}
}
}
Lots of different ways to do this, the easiest is probably:
String[] parts = totalLbl.getText().split(":");
String input = parts[1].trim();
Double parsedString = Double.parseDouble(input) * 0.20;
you can do this
str = str.replaceAll("\\D+","");
this will delete non digits from the string
so you would want it to be like this
Double parsedString = Double.parseDouble(input.replaceAll("\\D+","")*0.20);
You can use separate widgets for the label and the value. E.g. The total label, create a JLabel object and set the text with static value "Total:", then for the total value, create a JTextField object and set the text with the actual value. When submitting, get the value from the textfield instead of from the label. Don't forget to call setEditable(false) to the textfield because the textfield is meant to display the value only, not to accept input.

Java GUI: How do I have more than one button on a row using GridBagLayout

I'm fairly new to java and I'm having a problem trying to put more than one button on a row,
at the moment I'm adding both buttons to the panel, but I don't know how to separate their x locations, i.e. they are both being added directly on to of each other.
Do I need to create a new layout or can I find a solution using what I have at the moment?
public class Question1 {
public static void main (String[] args){
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame{
MyFrame(String title){
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = 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);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf,cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JButton b = new JButton("Submit");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
b = new JButton("Cancel");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
this.pack();
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE) ;
this.setVisible(true);
}
Just increment the gridx value:
JButton b = new JButton("Submit");
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
b = new JButton("Cancel");
cButton.gridx++;
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
Also you need to use the constraints created when adding your component to the grid bag layout using container.
e.g.,
import java.awt.*;
import javax.swing.*;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
private static final int GAP = 2;
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
JTextField tf = new JTextField(20);
mainPanel.add(tf, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
JButton b = new JButton("Submit");
mainPanel.add(b, gbc);
b = new JButton("Cancel");
gbc.gridx++;
mainPanel.add(b, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
Try the following code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = 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);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf, cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JPanel demoPanel = new JPanel();
JButton b = new JButton("Submit");
gbLayout.setConstraints(demoPanel, cButton);
demoPanel.add(b);
b = new JButton("Cancel");
// gbLayout.setConstraints(b,cButton);
demoPanel.add(b);
mainPanel.add(demoPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
I have just put the two buttons inside a JPanel and put the JPanel inside the GridBagLayout Panel !

Passing data between classes in CardLayout

Please have a look at the following code
WizardPanel.java
package wizardGUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WizardPanel extends JDialog
{
private JPanel cardPanel, buttonPanel;
private JButton next,previous;
private CardLayout c1;
private FileSelector fileSelector;
private DelemeterSelector delemeterSelector;
private int count = 1;
public WizardPanel()
{
//Intializing instance variables
fileSelector = FileSelector.getInstance();
delemeterSelector = DelemeterSelector.getInstance();
cardPanel = new JPanel();
c1 = new CardLayout();
cardPanel.setLayout(c1);
cardPanel.add(fileSelector,"1");
cardPanel.add(delemeterSelector,"2");
c1.show(cardPanel, "1");;
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
next = new JButton("Next");
next.addActionListener(new NextButtonAction());
previous = new JButton("Previous");
buttonPanel.add(next);
buttonPanel.add(previous);
//Creating the GUI
this.setLayout(new BorderLayout());
this.add(cardPanel,"Center");
this.add(buttonPanel,"South");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setResizable(true);
this.pack();
this.setVisible(true);
}
private class NextButtonAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
c1.show(cardPanel, "2");
}
}
}
FileSelector.java
package wizardGUI;
/*This is the first panel is wazard GUI. Using this window user can select the correct file
which contains the data required to create the table
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FileSelector extends JPanel
{
private JLabel fileName, description;
private JTextField fileTxt;
private JButton browse;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private static FileSelector instance = null;
private FileSelector()
{
//Intializing instance variables
fileName = new JLabel("File Name: ");
description = new JLabel("Specify the source of the data");
fileTxt = new JTextField(10);
browse = new JButton("Browse");
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
//Creating GUI
this.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.BOTH;
this.add(description,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0,10,0,0);
this.add(locationPanel(),gbc);
this.setBorder(BorderFactory.createEmptyBorder());
}
private JPanel locationPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(fileName);
panel.add(fileTxt);
panel.add(browse);
return panel;
}
public static FileSelector getInstance()
{
if(instance==null)
{
instance = new FileSelector();
}
return instance;
}
}
DelemeterSelector.java
/*This is the second windows in wizard
This class is designed to let the user to select the delemeter to break information */
package wizardGUI;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class DelemeterSelector extends JPanel
{
private JLabel description;
private JRadioButton tabBtn, semicolanBtn, commaBtn, spaceBtn;
private JTextArea txtArea;
private JScrollPane scroll;
private ButtonGroup btnGroup;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private static DelemeterSelector instance = null;
private DelemeterSelector()
{
//Initializing instance variables
description = new JLabel("What delemeter separates your fields? Select the appropreiate delemeter");
tabBtn = new JRadioButton("Tab");
semicolanBtn = new JRadioButton("Semicolan");
commaBtn = new JRadioButton("Comma");
spaceBtn = new JRadioButton("Space");
btnGroup = new ButtonGroup();
btnGroup.add(tabBtn);
btnGroup.add(semicolanBtn);
btnGroup.add(commaBtn);
btnGroup.add(spaceBtn);
txtArea = new JTextArea(20,70);
scroll = new JScrollPane(txtArea);
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
this.setLayout(gbl);
//Creating the GUI
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20,0,0,0);
this.add(description,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20,0,0,0);
this.add(radioPanel(),gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(10,0,0,0);
gbc.fill = GridBagConstraints.BOTH;
this.add(scroll,gbc);
}
private JPanel radioPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(tabBtn);
panel.add(semicolanBtn);
panel.add(commaBtn);
panel.add(spaceBtn);
panel.setBorder(BorderFactory.createTitledBorder("Choose the Delimeter that seperates your fields"));
return panel;
}
public static DelemeterSelector getInstance()
{
if(instance == null)
{
instance = new DelemeterSelector();
}
return instance;
}
}
Main.java
package wizardGUI
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame
{
public Main()
{
new WizardPanel().setVisible(true);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Main();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
In here, we have only two buttons "Next" and "Previous" and they are commong for all the JPanels because it appears in "South" of 'WizardPanel' while other JPanels are in center.
Now, lets take "FileSelector". Guess I selected a file using the browse button.
Now how can I send this information to the next panel? which means to "DelemeterSelector" ?. I have only 2 'COMMON' buttons "Next" and "previous" which are located in ANOTHER CLASS.
I don't think writing business logic (getting selected file from 'FileSelector' and sending it to 'DelemeterSelector') inside that "Next" or "Previous" button's actionListener is a good idea. Because, I have to access another class, get it data and send it to the next JPanel (next class). There will be more JPanels, so this will be really hard and failing for sure.
I thought of adding "Next" and "Previous" buttons to each and every JPanel rather than the common ones. But then the problem is moving from one panel to another, because the reference to CardLayout is missing.
Please help me to find a correct and efficient way pass data from one class to another class, in this wizard. Thanks.
PS:
I don't want to do condition checking in "Next" buttons action class and let it hold all the actions. For an example, see the following EXAMPLE CODE snippet
//NON TESTED, NON COMPILED EXAMPLE CODE.
private class NextButtonAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(fileSelector.isVisible(true))
{
//Access FileSelector
// Get the Data
// send data into delemeter class
}
else if(delemeterSelector.isVisible(true))
{
//Access delemeterSelector
// Get the Data
// send data into other class
}
else if(SOME_OTHER_CLASS.isVisible(true))
{
//Access delemeterSelector
// Get the Data
// send data into other class
}
}
}
Lunch break is over, so all I have time for is to post sample code, but I'll try to come back to explain it before the end of the day:
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
public class MainGui {
public MainGui() {
new WizardPanel().setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new MainGui();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class WizardPanel extends JDialog {
private JPanel cardPanel, buttonPanel;
private JButton next, previous;
private CardLayout c1;
private SimpleModel simpleModel = new SimpleModel();
private FileSelector fileSelector;
private DelemeterSelector delemeterSelector;
private int count = 1;
public WizardPanel() {
fileSelector = FileSelector.getInstance();
delemeterSelector = DelemeterSelector.getInstance();
fileSelector.setModel(simpleModel); //!!
delemeterSelector.setModel(simpleModel); //!!
cardPanel = new JPanel();
c1 = new CardLayout();
cardPanel.setLayout(c1);
cardPanel.add(fileSelector, "1");
cardPanel.add(delemeterSelector, "2");
c1.show(cardPanel, "1");
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
next = new JButton("Next");
next.addActionListener(new NextButtonAction());
previous = new JButton("Previous");
buttonPanel.add(next);
buttonPanel.add(previous);
// Creating the GUI
this.setLayout(new BorderLayout());
this.add(cardPanel, "Center");
this.add(buttonPanel, "South");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setResizable(true);
this.pack();
this.setVisible(true);
}
private class NextButtonAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
// c1.show(cardPanel, "2");
c1.next(cardPanel); //!!
}
}
}
class FileSelector extends JPanel {
private JLabel fileName, description;
private JTextField fileTxt;
private JButton browse;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private SimpleModel simpleModel;
private static FileSelector instance = null;
private FileSelector() {
// Intializing instance variables
fileName = new JLabel("File Name: ");
description = new JLabel("Specify the source of the data");
fileTxt = new JTextField(10);
browse = new JButton("Browse");
browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (simpleModel != null) {
simpleModel.setFileText(fileTxt.getText());
}
}
});
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
// Creating GUI
this.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.BOTH;
this.add(description, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0, 10, 0, 0);
this.add(locationPanel(), gbc);
this.setBorder(BorderFactory.createEmptyBorder());
}
public void setModel(SimpleModel simpleModel) {
this.simpleModel = simpleModel;
}
private JPanel locationPanel() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(fileName);
panel.add(fileTxt);
panel.add(browse);
return panel;
}
public static FileSelector getInstance() {
if (instance == null) {
instance = new FileSelector();
}
return instance;
}
}
class DelemeterSelector extends JPanel {
private JLabel description;
private JRadioButton tabBtn, semicolanBtn, commaBtn, spaceBtn;
private JTextArea txtArea;
private JScrollPane scroll;
private ButtonGroup btnGroup;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private SimpleModel simpleModel;
private static DelemeterSelector instance = null;
private DelemeterSelector() {
description = new JLabel(
"What delemeter separates your fields? Select the appropreiate delemeter");
tabBtn = new JRadioButton("Tab");
semicolanBtn = new JRadioButton("Semicolan");
commaBtn = new JRadioButton("Comma");
spaceBtn = new JRadioButton("Space");
btnGroup = new ButtonGroup();
btnGroup.add(tabBtn);
btnGroup.add(semicolanBtn);
btnGroup.add(commaBtn);
btnGroup.add(spaceBtn);
txtArea = new JTextArea(20, 70);
scroll = new JScrollPane(txtArea);
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
this.setLayout(gbl);
// Creating the GUI
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20, 0, 0, 0);
this.add(description, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20, 0, 0, 0);
this.add(radioPanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(10, 0, 0, 0);
gbc.fill = GridBagConstraints.BOTH;
this.add(scroll, gbc);
}
private JPanel radioPanel() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(tabBtn);
panel.add(semicolanBtn);
panel.add(commaBtn);
panel.add(spaceBtn);
panel.setBorder(BorderFactory
.createTitledBorder("Choose the Delimeter that seperates your fields"));
return panel;
}
//!!
public void setModel(final SimpleModel simpleModel) {
this.simpleModel = simpleModel;
simpleModel.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (SimpleModel.FILE_TEXT.equals(evt.getPropertyName())) {
txtArea.append("File Text: " + simpleModel.getFileText() + "\n");
}
}
});
}
public static DelemeterSelector getInstance() {
if (instance == null) {
instance = new DelemeterSelector();
}
return instance;
}
}
class SimpleModel {
public static final String FILE_TEXT = "file text";
private SwingPropertyChangeSupport pcSupport =
new SwingPropertyChangeSupport(this);
private String fileText;
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
public void setFileText(String fileText) {
String oldValue = this.fileText;
String newValue = fileText;
this.fileText = fileText;
pcSupport.firePropertyChange(FILE_TEXT, oldValue , newValue);
}
public String getFileText() {
return fileText;
}
}
Edit explanation of code:
This is a gross simplification of the Model-View-Controller or MVC design pattern since it is nothing more than model and view. The model holds the data and logic that the GUI works with and is essentially the "brains" of the program while the GUI is little more than a dumb display of the information.
The model here is quite simple and only holds one String field called fileText. It has setters and getters for this field, and the most interesting thing about it is the setter is wired so that it will notify any listeners that want to know if this field is ever changed. This process of using PropertyChangeSupport and allowing for PropertyChangeListeners means the the fileText field is a "bound" property.
Both of your JPanels have fields to hold a reference to the same SimpleModel object, and this model is set via a setter method, setModel(...).
fileSelector.setModel(simpleModel); // !!
delemeterSelector.setModel(simpleModel); // !!
I let the FileSelector object set the fileText field if its JButton is pressed:
browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (simpleModel != null) {
simpleModel.setFileText(fileTxt.getText());
}
}
});
I have the DelemeterSelector class add a PropertyChangeListener to the model so that it is notified whenever the fileText field's value is changed, and can respond to it as it sees fit:
public void setModel(final SimpleModel simpleModel) {
this.simpleModel = simpleModel;
simpleModel.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (SimpleModel.FILE_TEXT.equals(evt.getPropertyName())) {
txtArea.append("File Text: " + simpleModel.getFileText() + "\n");
}
}
});
}
Note that the model class has no idea what the GUI does with the information it holds, and that's a good thing as it means that "coupling" is fairly loose.

Categories

Resources