java swing panel problems - java

I am having problems adding a panel to my main JFrame and hiding it right away, only making it visilble when a button it pressed. here is my code. Looking for any insight as to what the problem is. Also the label I try to add to the panel doesnt show up either.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cis2430_a4;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Tristan
*/
public class MainWindow extends JFrame implements ActionListener{
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
public MainWindow()
{
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
JLabel intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
add(intro2, BorderLayout.CENTER);
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600,400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
add(addPanel, BorderLayout.CENTER);
addPanel.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent ae)
{
/*String menuChoice = ae.getActionCommand();
if (menuChoice.equals("Add")){
addPanel.setVisible(true);
}*/
add(addPanel);
//addPanel.setVisible(true);
}
}

I have no issue with your example.
You may want to...
1- Make sure you've launched your UI in the context of the Event Dispatching Thread
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) {
}
MainWindow frame = new MainWindow();
frame.setVisible(true);
}
});
}
2- Try calling repaint after addPanel.setVisible(true)
3- Try calling invalidate after addPanel.setVisible(true) but before repaint if that doesn't work.
Much better solution is to use Card Layout for this kind of work
UPDATED
After spending some time reading through the code, what I think you seem to be concerned about is the fact that you're "intro" label isn't showing up...
This easily explained. Only one component can exists at any given position within a BorderLayout, so when you add you addPanel, even though it's invisible, it will clobber the intro2 label (effectively removing it from the container).
Below is an example using CardLayout
public class CardWindow extends JFrame implements ActionListener {
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
private JPanel cardPane;
private CardLayout cardLayout;
private final JLabel intro2;
public CardWindow() {
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
cardPane = new JPanel((cardLayout = new CardLayout()));
add(cardPane, BorderLayout.CENTER);
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
cardPane.add(intro2, "intro");
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600, 400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
addPanel.setVisible(false);
cardPane.add(addPanel, "Add");
cardLayout.show(cardPane, "intro");
}
#Override
public void actionPerformed(ActionEvent ae) {
String menuChoice = ae.getActionCommand();
System.out.println(menuChoice);
if (menuChoice.equals("Add")) {
cardLayout.show(cardPane, "Add");
}
}
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) {
}
CardWindow frame = new CardWindow();
frame.setVisible(true);
}
});
}
}

Labels are showing up because you have added a panel after adding the labels on the frame so basically the panels are overlapping the labels.
Also to show different panels you can use
panel.setVisible(true); //For the panel you want to show and false for others
or you can use CardLayout which makes panels as cards and shows one of them at a time.

Just edited the code a little but it seems to work -
public class MainWindow extends JFrame implements ActionListener{
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.setVisible(true);
}
public MainWindow()
{
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
JLabel intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
add(intro2, BorderLayout.CENTER);
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600,400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
add(addPanel, BorderLayout.CENTER);
addPanel.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent ae)
{
String menuChoice = ae.getActionCommand();
if (menuChoice.equals("Add")){
addPanel.setVisible(true);
}
add(addPanel);
//addPanel.setVisible(true);
}
}

Related

after pressing a button it should open a JPanel

package garage;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* #author Jela
*/
public class VehicleParts extends JPanel {
public VehicleParts() {
//super();
//JPanel container = new JPanel();
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JButton buttonOne = new JButton("Parts");
JButton buttonTwo = new JButton("Stock");
JButton buttonThree = new JButton("Supplier");
add(buttonOne);
add(buttonTwo);
add(buttonThree);
}
}
When pressing buttonOne, it should open up a jpanel on the same frame and should be able to go back to the frame, but somehow the buttons are not showing up. THis is not my main class. If anyone has some tips, please help. It should work something like this
Stock | Parts | Supplier |
-
-
PANEL 1 -
-
-
-
-
"Previous" "NEXT" -
========================== =
If pressing a button like next it should go to panel 2, under the parts tab
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
This is my main class
package garage;
import java.awt.CardLayout;
import java.awt.Dimension;
import javax.swing.*;
/**
*
* #author Jela
*/
public class Garage extends JPanel {
JFrame frame = new JFrame("Garage Management System");
final static JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel();
final static CustomerAccounts customerPanel = new CustomerAccounts();
final static DiagnosisAndRepair diagnosisPanel = new DiagnosisAndRepair();
final static ScheduledMaintenance maintenancePanel = new ScheduledMaintenance();
final static VehicleParts partsPanel = new VehicleParts();
final static VehicleRecords recordsPanel = new VehicleRecords();
CardLayout cl = new CardLayout();
public Garage(){
tabbedPane.addTab("CustomerAccounts", customerPanel);
tabbedPane.addTab("DiagnosisAndRepair", diagnosisPanel);
tabbedPane.addTab("ScheduledMaintenance", maintenancePanel);
tabbedPane.addTab("VehicleParts", partsPanel);
tabbedPane.addTab("VehicleRecords", recordsPanel);
//add(tabbedPane);
frame.setSize(new Dimension(800,600));
frame.add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
Garage g = new Garage();
}
}
This is because you are stacking a new card on top of the current card every time you add another card.
card1.add(buttonOne);
card1.add(buttonTwo);
card1.add(buttonThree);
Doing this will display the last card added.
From java docs:
http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html
It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.
Something like this should work:
public class Cards() {
private JPanel cardPanel;
Cards() {
cardPanel = makeCardPanel();
}
private JPanel makeCardPanel() {
JPanel card1 = new JPanel();
JButton button1 = new JButton("button1");
JButton button2 = new JButton("button1");
JButton button3 = new JButton("button1");
card1.add(button1);
card1.add(button2);
card1.add(button3);
JPanel card2 = new JPanel();
JButton buttonA = new JButton("buttonA");
card2.add(buttonA);
// Repeat the above for the cards and buttons
JPanel cardPanel = new JPanel(new CardLayout());
cardPanel.add(card1, "First Card");
cardPanel.add(card2, "Second Card");
// Add the rest of the cards.
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((CardLayout)cardPanel.getLayout()).show(cardPanel, "Second Card");
}
});
buttonA.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((CardLayout)mainPanel.getLayout()).show(cardPanel, "First Card");
}
});
return cardPanel;
}
public JPanel getCardPanel() { return cardPanel; }
}
And then in your Garage() do:
public Garage(){
Cards cards = new Cards();
tabbedPane.addTab("CustomerAccounts", customerPanel);
tabbedPane.addTab("DiagnosisAndRepair", diagnosisPanel);
tabbedPane.addTab("ScheduledMaintenance", maintenancePanel);
tabbedPane.addTab("VehicleParts", partsPanel);
tabbedPane.addTab("VehicleRecords", recordsPanel);
frame.setLayout(new FlowLayout());
frame.setSize(new Dimension(800,600));
frame.add(tabbedPane);
frame.add(cards.getCardPanel());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
after you add the buttons to the panel you need to do the followings:
frame.pack();
frame.setVisible(true);

Java JButton it is not running truly

I added a jbutton with eclipse but it is not seeing correctly. How do I fix it?
this is screen shot:
public class GUITest // test class
{
// block the warnings
public static void main(String[] args) //main
{
System.out.println("start of main");
/* stackoverflow want to add more details */
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
System.out.println("end of main");
/* stackoverflow want to add more details */
}
public static class Action implements ActionListener //actionlistener
{
public void actionPerformed (ActionEvent e)
{ /* stackoverflow want to add more details */
JFrame frame2 = new JFrame("Clicked");
frame2.setVisible(true);
frame2.setSize(200,200);
JLabel label = new JLabel("You clicked me!");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label); // some more details
}
}
}
I have used this and It will working fine. Can you please check your Graphics Driver or other things.
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;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Ashwin Parmar
*/
public class GUITest {
public static void main(String[] args) {
System.out.println("Start");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
frame.setVisible(true);
System.out.println("End");
}
public static class Action implements ActionListener{
#Override
public void actionPerformed(ActionEvent ae) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
JFrame frame2 = new JFrame("Clicked");
frame2.setSize(200,200);
JLabel label = new JLabel("You have clicked me!");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
frame2.setVisible(true);
}
}
}
Always create and modify the UI from within the context of the Event Dispatching Thread
Wherever possible, call setVisible last, after you have established the basic UI. You will be required to call revalidate and repaint if you add components after the window is made visible.
For example...
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();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Do the same thing within your ActionListener.
See Initial Threads for more details

How can I open a JPanel from a menu?

I'm trying to create a menu and from it I need to open a JPanel. How can I do that?
I want to the user to press "individual details" for example and then for it to open an area where i can add buttons and textfields.
public class Payroll{
public static void main(String[] args) {
JFrame frame = new JFrame(" Payroll ");
//create the employees details menu
JMenu employees = new JMenu("Employees");
employees.setMnemonic(KeyEvent.VK_E);
// add employees items
JMenuItem details = new JMenuItem("Individual Details");
details.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
/**********missing code is here, how can i open a JPanel from here?**/
}
});
employees.add(details);
//menu bar
JMenuBar menuBar = new JMenuBar( );
menuBar.add(employees);
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(700,550);
frame.setVisible(true);
}
}
you can create a another class which has a jpanel and fields for take userinput .and then create a instance of it inside menuitem actionPerformed event...
for example ;
this is the class which has panel
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyPanel {
public MyPanel() {
JFrame f=new JFrame();
f.setSize(300,200);
f.setLayout(new GridLayout(1, 1));
JPanel p=new JPanel();
p.setLayout(new GridLayout(3, 1, 2, 2));
JTextField t1=new JTextField(20);
p.add(t1);
f.add(p);
f.setVisible(true);
}
}
and make a instance of it inside event ..
public class Payroll{
public static void main(String[] args) {
JFrame frame = new JFrame(" Payroll ");
JMenu employees = new JMenu("Employees");
employees.setMnemonic(KeyEvent.VK_E);
// add employees items
JMenuItem details = new JMenuItem("Individual Details");
details.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
MyPanel panel=new MyPanel(); // call MyPanel here
}
});
employees.add(details);
//menu bar
JMenuBar menuBar = new JMenuBar( );
menuBar.add(employees);
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(700,550);
frame.setVisible(true);
}
}
You can try like below,
JPanel panel = new JPanel();
JButton okButton = new JButton("OK");
panel.add(okButton);
JButton cancelButton = new JButton("Cancel");
panel.add(cancelButton);
frame.add(panel);

How to clear JFrame area by clicking another sub menu of JMenuBar in java Swing?

the code is there for clearing the Frame area by clicking the sub menu(sub_menu_purchase and sub_menu_sale) of main menu.
public void clear()
{
Graphics g = getGraphics();
Dimension d = getSize();
g.setColor(Color.WHITE);
g.fillRect(0,0,d.width,d.height);
}
void sale()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblform =new JLabel("From Party : ");
lblto =new JLabel("To Party : ");
txtto=new JTextField();
txtfrom=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblto.setBounds(50,135,80,25);
txtto.setBounds(140,135,200,25);
lblform.setBounds(50,170,80,25);
txtfrom.setBounds(140,170,100,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblto);
add(lblform);
add(txtto);
add(txtfrom);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
void purchase()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblparty =new JLabel("Party Name: ");
txtparty=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblparty.setBounds(50,135,80,25);
txtparty.setBounds(140,135,200,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblparty);
add(txtparty);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
public void actionPerformed(ActionEvent event) //set up actionlistening
{
Object source=event.getSource();
if (source.equals(sub_menu_purchase))
{ clear();
purchase();
}
if (source.equals(sub_menu_sale))
{ clear();
sale();
}
}
But it is not clear the area and override to one another.
what code should I write?
There's a lot I would do differently from what you're doing, including
Don't get a component's Graphics via getGraphics(). The Graphics object thus obtained will not persist, and so it is not useful for making stable changes to a GUI's appearance.
Don't clear the GUI's graphics but rather change the view. Even if your code worked, the components would not have been removed from the GUI with your code. They would still exist and still sit on the GUI -- not good.
A CardLayout would work well for allowing you to swap a container's view, and is often used to swap JPanels, each holding its own GUI.
Avoid null layout and using setBounds(...) as this will lead to creation of GUI's that are a "witch" to upgrade and maintain and that look bad on all platforms except for one. Better to nest JPanels, each using its own simple layout, to achieve complex, beautiful and easy to maintain and improve GUI's.
Read/study the Swing tutorials as all of this is well explained there.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UglyGui2 {
private static final String SALE = "Sale";
private static final String PURCHASE = "Purchase";
private JMenuItem sub_menu_sale = new JMenuItem(SALE);
private JMenuItem sub_menu_purchase = new JMenuItem(PURCHASE);
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
public UglyGui2() {
cardPanel.add(new JLabel(), "");
cardPanel.add(createSalePanel(), SALE);
cardPanel.add(createPurchasePanel(), PURCHASE);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(new JButton("Reset"));
buttonPanel.add(new JButton("Save"));
buttonPanel.add(new JButton("Print"));
buttonPanel.add(new JLabel());
buttonPanel.add(new JButton("Cancel"));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.add(cardPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.PAGE_END);
}
private JComponent createSalePanel() {
JPanel salePanel = new JPanel(new GridBagLayout());
salePanel.add(new JLabel("Sales"));
salePanel.add(new JTextField(10));
return salePanel;
}
private JComponent createPurchasePanel() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Purchases"));
topPanel.add(new JTextField(10));
JPanel purchasePanel = new JPanel(new BorderLayout());
purchasePanel.add(topPanel, BorderLayout.PAGE_START);
purchasePanel.add(new JScrollPane(new JTextArea(30, 60)), BorderLayout.CENTER);
return purchasePanel; }
private Component getMainPanel() {
return mainPanel;
}
private JMenuBar getJMenuBar() {
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, e.getActionCommand());
}
};
sub_menu_purchase.addActionListener(aListener);
sub_menu_sale.addActionListener(aListener);
JMenu menu = new JMenu("Menu");
menu.add(sub_menu_purchase);
menu.add(sub_menu_sale);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
private static void createAndShowGui() {
UglyGui2 uglyGui = new UglyGui2();
JFrame frame = new JFrame("Ugly Gui Example");
frame.setJMenuBar(uglyGui.getJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(uglyGui.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

actionlistener not responding in java calculator

please see calculator interface code below, from my beginners point of view the "1" should display when it's pressed but evidently i'm doing something wrong. any suggestiosn please?
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*A Class that operates as the framework for a calculator.
*No calculations are performed in this section
*/
public class CalcFrame extends JPanel
{
private CalcEngine calc;
private JFrame frame;
private JTextField display;
private JLabel status;
/**
* Constructor for objects of class GridLayoutExample
*/
//public CalcFrame(CalcEngine engine)
//{
//frame.setVisible(true);
// calc = engine;
// makeFrame();
//}
public CalcFrame() {
makeFrame();
calc = new CalcEngine();
}
class ButtonListener implements ActionListener {
ButtonListener() {
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("1")) {
System.out.println("1");
}
}
}
/**
* This allows you to quit the calculator.
*/
// Alows the class to quit.
private void quit()
{
System.exit(0);
}
// Calls the dialog frame with the information about the project.
private void showAbout()
{
JOptionPane.showMessageDialog(frame,
"Declan Hodge and Tony O'Keefe Group Project",
"About Calculator Group Project",
JOptionPane.INFORMATION_MESSAGE);
}
// ---- swing stuff to build the frame and all its components ----
/**
* The following creates a layout of the calculator frame.
*/
private void makeFrame()
{
frame = new JFrame("Group Project Calculator");
makeMenuBar(frame);
JPanel contentPane = (JPanel)frame.getContentPane();
contentPane.setLayout(new BorderLayout(8, 8));
contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10));
/**
* Insert a text field
*/
display = new JTextField(8);
contentPane.add(display, BorderLayout.NORTH);
//Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(4, 5));
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
contentPane.add(new JButton("9"));
contentPane.add(new JButton("8"));
contentPane.add(new JButton("7"));
contentPane.add(new JButton("6"));
contentPane.add(new JButton("5"));
contentPane.add(new JButton("4"));
contentPane.add(new JButton("3"));
contentPane.add(new JButton("2"));
contentPane.add(new JButton("1"));
contentPane.add(new JButton("0"));
contentPane.add(new JButton("+"));
contentPane.add(new JButton("-"));
contentPane.add(new JButton("/"));
contentPane.add(new JButton("*"));
contentPane.add(new JButton("="));
contentPane.add(new JButton("C"));
contentPane.add(new JButton("CE"));
contentPane.add(new JButton("%"));
contentPane.add(new JButton("#"));
//contentPane.add(buttonPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
/**
* Create the main frame's menu bar.
* The frame that the menu bar should be added to.
*/
private void makeMenuBar(JFrame frame)
{
final int SHORTCUT_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu menu;
JMenuItem item;
// create the File menu
menu = new JMenu("File");
menubar.add(menu);
// create the Quit menu with a shortcut "Q" key.
item = new JMenuItem("Quit");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { quit(); }
});
menu.add(item);
// Adds an about menu.
menu = new JMenu("About");
menubar.add(menu);
// Displays
item = new JMenuItem("Calculator Project");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { showAbout(); }
});
menu.add(item);
}
}
That's a lot of code!
You don't actually create a ButtonListener let alone add one to a button.
You need to register the action listener with the button.
//Step 1.
JButton b1 = new JButton("1");
//Step2 register
b1.addActionListener(new ButtonListener());
EDIT
Start by declaring the Buttons as in step 1 above. Then in the content pane you need to add the button similar to the way you are adding the buttons right now.
contentPane.add(b1);
Now the button should display.

Categories

Resources