Creating a Layout in Java [duplicate] - java

This question already has answers here:
How I can do swing complex layout Java [closed]
(1 answer)
Java GUI Layouts
(5 answers)
Closed 5 years ago.
[I am trying a create a layout like a picture below. I am new to Java programming.]When I am trying to run this. There is no error or anything and nothing displays. Console stops automatically. Kindly help me.
package completeJavaReference;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
------------------------------------------------------------------------
public class tryingProject extends JFrame {
public static final long serialVersionUID = 1L;//Eclipse added
public static JLabel carname;
public static JLabel price, make, year, trim, category, VIN, model,bodytype;
public static JLabel dealerinfo, ID, URL, Name;
public static JTextField priceTextField, makeTextField, yearTextField,
trimTextField, categoryTextField, VINTextField, modelTextField,
bodytypeTextField;
private static JTextField dealerinfoTextField, IDTextField, URLTextField,
NameTextField;
public void createComponents() {
carname = new JLabel("Honda Civic");
price = new JLabel("Price: ");
make = new JLabel("Make: ");
year = new JLabel("Year:");
trim = new JLabel("Trim:");
category = new JLabel("Category:");
VIN = new JLabel("VIN:");
model = new JLabel("Model:");
bodytype = new JLabel("Body Type");
priceTextField = new JTextField(10);
makeTextField = new JTextField(10);
yearTextField = new JTextField(10);
trimTextField = new JTextField(10);
categoryTextField = new JTextField(10);
VINTextField = new JTextField(10);
modelTextField = new JTextField(10);
bodytypeTextField = new JTextField(10);
dealerinfo = new JLabel("Dealer Info");
ID = new JLabel("Dealer ID:");
URL = new JLabel("URL:");
Name = new JLabel("Dealer Name");
dealerinfoTextField = new JTextField(10);
IDTextField = new JTextField(10);
URLTextField = new JTextField(10);
NameTextField = new JTextField(10);
}
public void createLayout(){
JFrame frame = new JFrame("Vehicle Window");
JPanel Panel1 = new JPanel(new FlowLayout());
JPanel Panel2 = new JPanel(new GridLayout(4, 3));
JPanel Panel3 = new JPanel(new FlowLayout());
Panel1.add(carname);
Panel2.add(price);
Panel2.add(priceTextField);
Panel2.add(make);
Panel2.add(makeTextField);
Panel2.add(year);
Panel2.add(yearTextField);
Panel2.add(trim);
Panel2.add(trimTextField);
Panel2.add(category);
Panel2.add(categoryTextField);
Panel2.add(VIN);
Panel2.add(VINTextField);
Panel2.add(model);
Panel2.add(modelTextField);
Panel2.add(year);
Panel2.add(yearTextField);
Panel3.add(dealerinfo);
Panel3.add(dealerinfoTextField);
Panel3.add(ID);
Panel3.add(IDTextField);
Panel3.add(URL);
Panel3.add(URLTextField);
Panel3.add(Name);
Panel3.add(NameTextField);
frame.getContentPane().add(Panel1);
frame.getContentPane().add(Panel2);
frame.getContentPane().add(Panel3);
frame.setTitle("Vechicle Details");
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new tryingProject();
}
}

Related

GUI Card Layout- Action Listener not working [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I only have the first button set up to work. It was working fine until I updated panel one to have additional panels (oneTwo,oneThree, etc.). I did this because I have to make the program look like this
=> Example
but now when i click the first button it no longer switched to card two. I cant figure it out.
Here is my code
public class AddressBook implements ActionListener {
static CardLayout contentPaneLayout;
static JButton B1= new JButton("Create a New Address"), B2= new JButton("Load Contacts"), B3= new JButton("Add New Contacts"),
B4= new JButton("View/Delete Contacts"), B5= new JButton("Backup Contacts"), B6= new JButton("Exit"), B7 = new JButton ("Cancel");
static JTextField TF1 = new JTextField(13), TF2 = new JTextField (13);
static JLabel L1 = new JLabel ("Use The Buttons Below To Manage Contacts",JLabel.CENTER), L2 = new JLabel ("This is Card 2"), L3 = new JLabel("Username:",JLabel.CENTER),
L4 = new JLabel("Number of Contacts:",JLabel.CENTER);;
static Container contentPane;
public void actionPerformed(ActionEvent e) {
Object click = e.getSource();
if (click==B1) contentPaneLayout.show(contentPane,"Card 2");
if (click==B6) System.exit(0);
if (click==B7) contentPaneLayout.show(contentPane, "Card 1");
}
public static void main(String[] args) {
JFrame frm = new JFrame("Address Book");
contentPane = frm.getContentPane();
contentPane.setLayout(new CardLayout());
JPanel one = new JPanel (new GridLayout( 5,5 ));
JPanel two = new JPanel (new GridLayout(4,6));
JPanel oneTwo = new JPanel(new FlowLayout());
JPanel oneThree = new JPanel(new GridLayout(2,3,6,5));
JPanel oneFour = new JPanel(new GridLayout());
JPanel oneFive = new JPanel(new GridLayout());
one.add (L1);
oneTwo.add (L3);
oneTwo.add (TF1);
TF1.setEditable(false);
TF2.setEditable(false);
oneTwo.add(L4);
oneTwo.add(TF2);
one.add(oneFive);
one.add(oneTwo);
oneThree.add(B1); oneThree.add(B2);oneThree.add(B3);oneThree.add(B4);oneThree.add(B5);oneThree.add(B6);
one.add(oneFour);
one.add(oneThree);
two.add(L2);
two.add(B7);
contentPane.add("Card 1", one);
contentPane.add("Card 2", two) ;
//contentPaneLayout.show(contentPane, "Card 1");
ActionListener AL= new AddressBook();
B1.addActionListener(AL); B7.addActionListener(AL); B6.addActionListener(AL);
frm.pack();
frm.setSize(550,250);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
You have a NullPointerException
contentPaneLayout.show(contentPane, "Card 2");
contentPaneLayout is never assigned a value.
This is exacerbated by the over zealous use of static
A little bit of rework and you have a slightly better solution
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
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.JPanel;
import javax.swing.JTextField;
public class AddressBook implements ActionListener {
private CardLayout contentPaneLayout;
private JButton b1 = new JButton("Create a New Address"), b2 = new JButton("Load Contacts"), b3 = new JButton("Add New Contacts"),
b4 = new JButton("View/Delete Contacts"), b5 = new JButton("Backup Contacts"), b6 = new JButton("Exit"), b7 = new JButton("Cancel");
private JTextField tf1 = new JTextField(13), tf2 = new JTextField(13);
private JLabel l1 = new JLabel("Use The Buttons Below To Manage Contacts", JLabel.CENTER), l2 = new JLabel("This is Card 2"), l3 = new JLabel("Username:", JLabel.CENTER),
l4 = new JLabel("Number of Contacts:", JLabel.CENTER);
private Container contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new AddressBook();
}
});
}
public AddressBook() {
JFrame frm = new JFrame("Address Book");
contentPane = frm.getContentPane();
contentPaneLayout = new CardLayout();
contentPane.setLayout(contentPaneLayout);
JPanel one = new JPanel(new GridLayout(5, 5));
JPanel two = new JPanel(new GridLayout(4, 6));
JPanel oneTwo = new JPanel(new FlowLayout());
JPanel oneThree = new JPanel(new GridLayout(2, 3, 6, 5));
JPanel oneFour = new JPanel(new GridLayout());
JPanel oneFive = new JPanel(new GridLayout());
one.add(l1);
oneTwo.add(l3);
oneTwo.add(tf1);
tf1.setEditable(false);
tf2.setEditable(false);
oneTwo.add(l4);
oneTwo.add(tf2);
one.add(oneFive);
one.add(oneTwo);
oneThree.add(b1);
oneThree.add(b2);
oneThree.add(b3);
oneThree.add(b4);
oneThree.add(b5);
oneThree.add(b6);
one.add(oneFour);
one.add(oneThree);
two.add(l2);
two.add(b7);
contentPane.add("Card 1", one);
contentPane.add("Card 2", two);
//contentPaneLayout.show(contentPane, "Card 1");
b1.addActionListener(this);
b7.addActionListener(this);
b6.addActionListener(this);
frm.pack();
frm.setSize(550, 250);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object click = e.getSource();
System.out.println("...");
if (click == b1) {
contentPaneLayout.show(contentPane, "Card 2");
}
if (click == b6) {
System.exit(0);
}
if (click == b7) {
contentPaneLayout.show(contentPane, "Card 1");
}
}
}
The important change is in the constructor...
contentPaneLayout = new CardLayout();
contentPane.setLayout(contentPaneLayout);

Commands are running twice in Java actionperformed

I created an utility that will be used within the firewall zone to get Websphere MQ contents using Java with Swing, since I'm not sure where the defect lies, I've posted almost the entire code apart from the redundant part:
package testbox;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class MainFrame extends JFrame implements ActionListener
{
JLabel lblqname = new JLabel("Please enter the queue name");
JTextField txtqname = new JTextField(25);
JLabel lblqcur = new JLabel("where curdeth greater than");
JTextField txtqcurdfil = new JTextField(5);
JLabel lblchlname = new JLabel("Please enter the Channel name");
JTextField txtchlname = new JTextField(30);
JLabel lblchs = new JLabel("where status is: ");
JTextField txtchs = new JTextField(8);
public String ID;
public String pwdValue;
public String qname;
public int cdepth;
public String chlname;
public String chlstatus;
public String cmdissue;
JTextArea out = new JTextArea();
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
public MainFrame()
{
JLabel jUserName = new JLabel("ID");
JTextField userName = new JTextField();
JLabel jPassword = new JLabel("Password");
JTextField password = new JPasswordField();
Object[] ob = {jUserName, userName, jPassword, password};
int result = JOptionPane.showConfirmDialog(null, ob, "Please input password for Login", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
ID = userName.getText();
pwdValue = password.getText();
final JFrame frame = new JFrame("Environment Choice");
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("QAQmgrList", makeQAPanel());
frame.getContentPane().add(tabbedPane);
}
}
public JPanel makeQAPanel()
{
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
GridBagConstraints gbc_QMGR2 = new GridBagConstraints();
gbc_QMGR2.insets = new Insets(0, 0, 5, 5);
gbc_QMGR2.gridx = 1;
gbc_QMGR2.gridy = 2;
p.add(QMGR2, gbc_QMGR2);
QMGR2.addActionListener(this);
return p;
}
public void createSubframe()
{
final JFrame subframe = new JFrame("Object Choice");
subframe.setSize(1000, 500);
subframe.getContentPane().setLayout(new GridLayout(1, 1));
out.setText(null);
out.setLineWrap(true);
out.setCaretPosition(out.getDocument().getLength());
out.setEditable (false);
JScrollPane jp = new JScrollPane(out);
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel queue = new JPanel();
queue.add(lblqname);
txtqname.setText(null);
queue.add(txtqname);
queue.add(lblqcur);
txtqcurdfil.setText(null);
queue.add(txtqcurdfil);
txtqname.addActionListener(this);
txtqcurdfil.addActionListener(this);
JPanel chl = new JPanel();
chl.add(lblchlname);
txtchlname.setText(null);
chl.add(txtchlname);
chl.add(lblchs);
txtchs.setText(null);
chl.add(txtchs);
txtchlname.addActionListener(this);
txtchs.addActionListener(this);
tabbedPane.addTab("Queues", queue);
tabbedPane.addTab("Channels", chl);
subframe.getContentPane().add(tabbedPane);
subframe.getContentPane().add(jp);
tabbedPane.setVisible(true);
subframe.setVisible(true);
}
public static void main(String[] args)
{SwingUtilities.invokeLater(new Runnable(){ public void run() { #SuppressWarnings("unused") MainFrame m = new MainFrame();}});}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == QMGR1|| e.getSource() == QMGR2)
{createSubframe();}
if (e.getSource() == txtqname){qname = txtqname.getText();}
if (e.getSource() == txtqcurdfil)
{
cdepth = Integer.parseInt(txtqcurdfil.getText());
cmdissue = "qn has value messages";
cmdissue = cmdissue.replace("qn", ""+qname+"");
cmdissue = cmdissue.replace("value", ""+cdepth+"");
System.out.println(cmdissue);
cmdissue = null;
}
if (e.getSource() == txtchlname){chlname = txtchlname.getText(); chlname=null;}
if (e.getSource() == txtchs)
{
chlstatus = txtchs.getText();
cmdissue = "chln is chls";
cmdissue = cmdissue.replace("chln", ""+chlname+"");
cmdissue = cmdissue.replace("chls", ""+chlstatus+"");
System.out.println(cmdissue);
}
}
}
I'm getting the expected outcome for the code:
Running for first time
Say I close this object choice panel and open a new instance, irrespective of which choice I make the command runs twice:
Running for the second time
The iteration repeats. Say I make a choice for the fourth or fifth time, the command runs 4/5 times.
I understood the fact that the somehow it is initializing the objects for the number of times I run it, and it needs to be reset after I close the panel. But I'm not sure how/where to get this done.
Apologies for the lengthy code posted, since I wanted to be sure that people can point the mistake that has been committed.
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 2;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
Looks like you are trying to add the same component to the panel twice in two different grid locations. You can't do this.
You need to:
create two different component, or
get rid of one of the components.
Edit:
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
You create the buttons as instance variables.
But then in the makeQAPanel() method you add the actionListener to the button.
QMGR1.addActionListener(this);
...
QMGR2.addActionListener(this);
So every time you invoke that method the actionListener gets added again.
The actionListener should be added in the constructor of you class so it is only added once.
#jesper,
someone explained to me the constructor part of it:
package testbox;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class MainFrame extends JFrame implements ActionListener
{
JLabel lblqname = new JLabel("Please enter the queue name");
JTextField txtqname = new JTextField(25);
JLabel lblqcur = new JLabel("where curdeth greater than");
JTextField txtqcurdfil = new JTextField(5);
JLabel lblchlname = new JLabel("Please enter the Channel name");
JTextField txtchlname = new JTextField(30);
JLabel lblchs = new JLabel("where status is: ");
JTextField txtchs = new JTextField(8);
public String ID;
public String pwdValue;
public String qname;
public int cdepth;
public String chlname;
public String chlstatus;
public String cmdissue;
JTextArea out = new JTextArea();
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
public MainFrame()
{
QMGR1.addActionListener(this);
QMGR2.addActionListener(this);
txtqname.addActionListener(this);
txtqcurdfil.addActionListener(this);
txtchlname.addActionListener(this);
txtchs.addActionListener(this);
JLabel jUserName = new JLabel("ID");
JTextField userName = new JTextField();
JLabel jPassword = new JLabel("Password");
JTextField password = new JPasswordField();
Object[] ob = {jUserName, userName, jPassword, password};
int result = JOptionPane.showConfirmDialog(null, ob, "Please input password for Login", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
ID = userName.getText();
pwdValue = password.getText();
final JFrame frame = new JFrame("Environment Choice");
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("QAQmgrList", makeQAPanel());
frame.getContentPane().add(tabbedPane);
}
}
public JPanel makeQAPanel()
{
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
GridBagConstraints gbc_QMGR2 = new GridBagConstraints();
gbc_QMGR2.insets = new Insets(0, 0, 5, 5);
gbc_QMGR2.gridx = 1;
gbc_QMGR2.gridy = 2;
p.add(QMGR2, gbc_QMGR2);
return p;
}
public void createSubframe()
{
final JFrame subframe = new JFrame("Object Choice");
subframe.setSize(1000, 500);
subframe.getContentPane().setLayout(new GridLayout(1, 1));
out.setText(null);
out.setLineWrap(true);
out.setCaretPosition(out.getDocument().getLength());
out.setEditable (false);
JScrollPane jp = new JScrollPane(out);
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel queue = new JPanel();
queue.add(lblqname);
txtqname.setText(null);
queue.add(txtqname);
queue.add(lblqcur);
txtqcurdfil.setText(null);
queue.add(txtqcurdfil);
JPanel chl = new JPanel();
chl.add(lblchlname);
txtchlname.setText(null);
chl.add(txtchlname);
chl.add(lblchs);
txtchs.setText(null);
chl.add(txtchs);
tabbedPane.addTab("Queues", queue);
tabbedPane.addTab("Channels", chl);
subframe.getContentPane().add(tabbedPane);
subframe.getContentPane().add(jp);
tabbedPane.setVisible(true);
subframe.setVisible(true);
}
public static void main(String[] args)
{SwingUtilities.invokeLater(new Runnable(){ public void run() { #SuppressWarnings("unused") MainFrame m = new MainFrame();}});}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == QMGR1|| e.getSource() == QMGR2)
{createSubframe();}
if (e.getSource() == txtqname){qname = txtqname.getText();}
if (e.getSource() == txtqcurdfil)
{
cdepth = Integer.parseInt(txtqcurdfil.getText());
cmdissue = "qn has value messages";
cmdissue = cmdissue.replace("qn", ""+qname+"");
cmdissue = cmdissue.replace("value", ""+cdepth+"");
System.out.println(cmdissue);
cmdissue = null;
}
if (e.getSource() == txtchlname){chlname = txtchlname.getText(); chlname=null;}
if (e.getSource() == txtchs)
{
chlstatus = txtchs.getText();
cmdissue = "chln is chls";
cmdissue = cmdissue.replace("chln", ""+chlname+"");
cmdissue = cmdissue.replace("chls", ""+chlstatus+"");
System.out.println(cmdissue);
}
}
}
Worked like a charm.. THanks for pointing it out

JLabel not appearing on panel

For class I'm supposed to be creating an application that first lets you choose which value you'd like to calculate, then asks to enter the appropriate info. Then when you click "calculate", it SHOULD display the answer. For some reason my JLabel that should be displaying the answer isn't showing up. I've been searching for a solution, but every thing I do, nothing appears after you click "calculate". I am a novice, please help :(
package decay.application;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DecayApplication implements ActionListener {
JFrame frame;
JPanel content;
JLabel prompt1, prompt2, prompt3, prompt4, displayFinal, displayIntitial, displayConstant, choose;
JTextField enterFinal, enterInitial, enterConstant, enterElapsed;
JButton finButton, inButton, conButton, calculate1, calculate2, calculate3;
public DecayApplication(){
frame = new JFrame("Decay Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new JPanel();
content.setLayout(new GridLayout(0, 2, 10, 5));
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
choose = new JLabel("Which would you like to calculate?");
content.add(choose);
finButton = new JButton("Final Amount");
finButton.setActionCommand("finalAmount");
finButton.addActionListener(this);
content.add(finButton);
inButton = new JButton("Initial Amount");
inButton.setActionCommand("initialAmount");
inButton.addActionListener(this);
content.add(inButton);
conButton = new JButton("Constant");
conButton.setActionCommand("constant");
conButton.addActionListener(this);
content.add(conButton);
frame.setContentPane(content);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){new DecayApplication();}
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
}
}
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
DecayApplication decay = new DecayApplication();
}
}
Here's your method actionPerformed:
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
//here should the if-loop end, because here is the end of instructions which should be called after clicking on the button
}
//and here the second if-loop
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}

trouble with creating JTable to display data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am doing this payroll project for school.
The idea is for the user to input the employee's name, work hour, hourly rate, and select department from the ComboBox.
There will display 3 buttons, "Add More", "Display Result", and "exit".
"Add More" button will store the input into several arryalist and set the textfield to blank to allow more input.
"Display Result" will generate a JTable at the bottom JPanel to display the employee's name, department, and weekly salary.
I am running into the problem of nothing shows up after hitting the "Display Result" button. Maybe I have misunderstand the purpose of the button event, but I am really confused right now. Please help!
Here is a photobucket directURL PrtSc of the UI, hope it helps.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class PayrollFrame extends JFrame
{
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame()
{
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new GridLayout(3,1));
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel);
add(buttonPanel);
add(outputPanel);
setVisible(true);
}
private void buildInputPanel()
{
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel()
{
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel()
{
outputPanel = new JPanel();
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][2]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add More")
{
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
}
else if(e.getActionCommand()=="Display Result")
{
printData();
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString)
{
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if(tempHour<=40)
{
salary.add(Double.toString(tempHour * tempRate));
}
else
{
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Let's start with...
if (e.getActionCommand() == "Add More") {
Is not how you compare Strings in Java, you need to use the equals method instead, something like...
if ("Add More".equals(e.getActionCommand())) {
for example
Next you do...
add(inputPanel);
add(buttonPanel);
add(outputPanel);
which, when using a BorderLayout, adds each of the components to the default position within the BorderLayout, you need to provide position constraints for each component, otherwise strange things begin to happen, for example...
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(outputPanel, BorderLayout.SOUTH);
I just realised that you're using a GridLayout, personally, I think you'll get a better result from BorderLayout, but that's me
And then you create a new instance of resultTable and outputPanel, but you never add outputPanel to anything...
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][1]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
A better idea would be to create resultTable, wrap in a JScrollPane and add it to your screen.
When you want to "print" the data, create a new TableModel and apply it to the JTable
For example...
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
Take a look at How to Use Tables and How to Use Scroll Panes for more details
Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class PayrollFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
PayrollFrame frame = new PayrollFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame() {
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel);
add(outputPanel, BorderLayout.SOUTH);
setVisible(true);
}
private void buildInputPanel() {
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel() {
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
TableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add More".equals(e.getActionCommand())) {
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
} else if ("Display Result".equals(e.getActionCommand())) {
printData();
} else if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString) {
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if (tempHour <= 40) {
salary.add(Double.toString(tempHour * tempRate));
} else {
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Thanks for #MadProgrammer 's help! His reply helps me to fix many problems I have, and really tried to explain things to me. After consulting with my instructor, I have successfully compile and run my program by editing the printData method.
private void printData()
{
DefaultTableModel model = new DefaultTableModel(columnNames,name.size());
resultTable.setModel(model);
for(int i=0; i<name.size(); i++)
{
resultTable.setValueAt(name.get(i),i,0);
resultTable.setValueAt(department.get(i),i,1);
resultTable.setValueAt(salary.get(i),i,2);
}
}

DesignGridLayout goes out of boundaries

My problem is this code producing a Swing GUI, goes out of display bounds in my laptop. Why?
It's using DesignGridLayout as layout library.
This is a code taken from answer in: Why does my components go out of boundaries, please help me to align it with the necessary code
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import net.java.dev.designgridlayout.DesignGridLayout;
public class Demo {
private void createAndShowGUI() {
JLabel i5l1 = new JLabel("FREIGHT DETAILS");
JLabel i5l2 = new JLabel("Date : ");
JLabel i5l3 = new JLabel("Vehicle No. : ");
JLabel i5l4 = new JLabel("From : ");
JLabel i5l5 = new JLabel("Item : ");
JLabel i5l6 = new JLabel("Quantity : ");
JLabel i5l7 = new JLabel("Kg.");
JLabel i5l8 = new JLabel("Rate : Rs.");
JLabel i5l15 = new JLabel("SALE DETAILS");
JLabel i5l16 = new JLabel("Cash Sales : Rs. ");
JLabel i5l17 = new JLabel("Credit : Rs. ");
JLabel i5l18 = new JLabel("EXPENSES");
JLabel i5l19 = new JLabel("Food & Tea : Rs. ");
JLabel i5l20 = new JLabel("Wages : Rs. ");
JLabel i5l21 = new JLabel("Miscellaneous Expenses : Rs. ");
JTextField i5t1 = new JTextField(20);
JTextField i5t2 = new JTextField(20);
JTextField i5t3 = new JTextField(20);
JTextField i5t4 = new JTextField(20);
JTextField i5t11 = new JTextField(20);
JTextField i5t12 = new JTextField(20);
JTextField i5t13 = new JTextField(20);
JTextField i5t14 = new JTextField(20);
JComboBox i5cb1 = new JComboBox<>();
JComboBox i5cb2 = new JComboBox<>();
JComboBox i5cb3 = new JComboBox<>();
JButton i5b1 = new JButton("Save");
JButton i5b2 = new JButton("Reset");
JButton i5b3 = new JButton("Close");
JSeparator i5sep1 = new JSeparator();
JSeparator i5sep2 = new JSeparator();
JSeparator i5sep3 = new JSeparator();
JSeparator i5sep4 = new JSeparator();
JSeparator i5sep5 = new JSeparator();
JSeparator i5sep6 = new JSeparator();
Object[] columnNames = new Object[]{"Column # 1", "Column # 2", "Column # 3", "Column # 4"};
DefaultTableModel model = new DefaultTableModel(columnNames, 10);
JTable table = new JTable(model);
JScrollPane i5t1sp1 = new JScrollPane(table);
JPanel freightPanel = new JPanel();
DesignGridLayout layout1 = new DesignGridLayout(freightPanel);
layout1.row().left().add(i5sep1).fill().withOwnRowWidth();
layout1.row().center().add(i5l1);
layout1.row().left().add(i5sep2).fill().withOwnRowWidth();
layout1.row().grid(i5l2).add(i5t1);
layout1.row().grid(i5l3).add(i5t2);
layout1.row().grid(i5l4).add(i5cb1);
layout1.row().grid(i5l5).add(i5cb2);
layout1.row().grid(i5l6).add(i5t3).add(i5l7);
layout1.row().grid(i5l8).add(i5t4);
layout1.row().left().add(i5sep5).fill().withOwnRowWidth();
layout1.row().center().add(i5l18);
layout1.row().left().add(i5sep6).fill().withOwnRowWidth();
layout1.row().grid(i5l19).add(i5t12);
layout1.row().grid(i5l20).add(i5t13);
layout1.row().grid(i5l21).add(i5t14);
JPanel salePanel = new JPanel();
DesignGridLayout layout2 = new DesignGridLayout(salePanel);
layout2.row().left().add(i5sep3).fill().withOwnRowWidth();
layout2.row().center().add(i5l15);
layout2.row().left().add(i5sep4).fill().withOwnRowWidth();
layout2.row().grid(i5l16).add(i5t11);
layout2.row().grid(i5l17).add(i5cb3);
layout2.row().grid().add(i5t1sp1);
JInternalFrame internalFrame = new JInternalFrame("Daily Analysis",true,true, true, true);
DesignGridLayout mainLayout = new DesignGridLayout(internalFrame.getContentPane());
mainLayout.row().grid().add(freightPanel).add(salePanel);
mainLayout.row().left().add(new JSeparator()).fill().withOwnRowWidth();
mainLayout.row().center().add(i5b1).add(i5b2).add(i5b3);
internalFrame.pack();
internalFrame.setVisible(true);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(internalFrame);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().createAndShowGUI();
}
});
}
}
Well, why not?
pack() makes the frames take the size they need to display all their subcomponents properly (according to their preferred size and fulfilling min/max restrictions), If they have a lot to show and/or your resolution is not big enough the window may end up being out of bounds of your screen. This would be a surprising issue if, say, the frame was maximized.

Categories

Resources