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);
Related
I need to insert the window with the tabbed called "First panel, Second panel, Third panel, Fourth panel" into the window named "Animation".
What should I do so that at the end it looks like: a window that has an animation box with four tabs, a Text box and a User input box?
First class called "Main" :
import java.awt.*;
import javax.swing.*;
public class Main {
JFrame frame = new JFrame("Demo");
JPanel panel = new JPanel();
JLabel square1 = new JLabel("Animation");
JLabel square2 = new JLabel("Text");
JTextField square3 = new JTextField("User Input");
public Main() {
panel.setLayout(new GridLayout(2,2,3,3));
panel.add(square1);
panel.add(square2);
panel.add(square3);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(600,400);
frame.setVisible(true);
}
public static void main(String[] args) {
Tabbed tp = new Tabbed();
tp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
tp.setSize(600,400);
tp.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
}
});
}
}
'Second class called "Tabbed" :'
import javax.swing.*;
public class Tabbed extends JFrame{
private static final long serialVersionUID = 1L;
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
JPanel thirdPanel = new JPanel();
JPanel fourPanel = new JPanel();
JLabel firstLabel = new JLabel("First!");
JLabel secondLabel = new JLabel("Second!");
JLabel thirdLabel = new JLabel("Third!");
JLabel fourLabel = new JLabel("Fourth!");
JTabbedPane tabbedPane = new JTabbedPane();
public Tabbed(){
firstPanel.add(firstLabel);
secondPanel.add(secondLabel);
thirdPanel.add(thirdLabel);
fourPanel.add(fourLabel);
tabbedPane.add("First panel",firstPanel);
tabbedPane.add("Second panel",secondPanel);
tabbedPane.add("Third panel",thirdPanel);
tabbedPane.add("Fourth panel",fourPanel);
add(tabbedPane);
}
}
Here's how I want to combine the two windows :
So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:
I am having trouble finding a way to invoke an action listener that returns the value of the button clicked in the text area at the bottom.
I made the buttons using a for loop and did not expressly give the buttons a name so I do not know how to reference them when trying to incorporate an ActionListener.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
buttonGrid.add(new JButton(val));
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}
I created an action listener to put the value in the text area at the bottom of the GUI.
I fixed a few problems with your code.
In the main method, I called the SwingUtilities invokeLater method to put the Swing GUI on the Event Dispatch thread (EDT). Swing components must be created and updated on the EDT.
The name of a Java class must start with a capital letter.
It's safer to put your Swing components on a JPanel, rather than add them directly to a JFrame.
I separated the code that creates the JFrame from the code that creates the JPanels. It should be easier for any reader of your code, including yourself, to understand what's going on.
In the createMainPanel method, I grouped the code so that everything having to do with the buttonGrid JPanel, to take one instance, is in one place in the code.
I added the action listener to the code that creates the buttonGrid JPanel.
I wrote action listener code that updates the JTextArea with the left clicked button label.
Here's the corrected code.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
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.JTextArea;
import javax.swing.SwingUtilities;
public class Buttoner implements ActionListener {
// JFrame
private JFrame frame = new JFrame("Button Game");
// Make JPanels
private JPanel panelLabel = new JPanel();
private JPanel buttonGrid = new JPanel(new GridLayout(0, 10));
private JPanel bottomPanel = new JPanel();
// JLabel
private JLabel label1 = new JLabel("The Button Game");
private JTextArea jta;
public Buttoner() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Change label color
label1.setForeground(Color.RED);
// add Label
panelLabel.add(label1);
panel.add(panelLabel, BorderLayout.NORTH);
// add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton button = new JButton(val);
button.addActionListener(this);
buttonGrid.add(button);
}
panel.add(buttonGrid, BorderLayout.CENTER);
// Add JText Area to bottom JPanel
String num = "value";
jta = new JTextArea(num, 1, 1);
jta.setEditable(false);
bottomPanel.add(jta);
panel.add(bottomPanel, BorderLayout.SOUTH);
return panel;
}
public static void main(String args[]) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new Buttoner();
}
};
SwingUtilities.invokeLater(runnable);
}
public void actionPerformed(ActionEvent a) {
JButton button = (JButton) a.getSource();
jta.setText(button.getText());
}
}
Try creating an array of buttons and add the newly created button to the array. See comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
private JButton buttons[] = new JButton[60]; //create an array of button for future reference
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton btn = new JButton(val);
btn.addActionListener(this); //add an actionListener right away
buttons[i] = btn; //add the button in the array for future reference
buttonGrid.add(btn);
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}
I am trying to create a tic tac toe GUI that needs to be set up as follows:
1) The frame is a grid made of 2 panes, left pane with a 9 button grif that acts as the board
2) The right pane pane is divided into two more panes 1 below the other. Based on the symbol the user chooses using the radio buttons, a click on the gameboard must display either "X" or "O".
Since my mouse listener code is in a separate class I am not sure how I can get what the user clicked.
Here is my code. Please give me a nudge in the right direction to overcome this issue.
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package samples;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSplitPane;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
/**
*
* #author saikrishnan.srivat
*/
public class TicTacToe extends JFrame {
/*declare the components of the window*/
JPanel iconPanel;
JPanel tictactoeBoard;
JPanel emptyPanel;
JLabel chooseLabel;
JRadioButton xButton;
JRadioButton oButton;
ButtonGroup bg;
JButton resetButton;
JButton exitButton;
JButton undoButton;
JSplitPane rightPane;
JSplitPane pane;
MouseAdapterMod mam;
public TicTacToe() {
iconPanel = new JPanel();
tictactoeBoard = new JPanel();
emptyPanel = new JPanel();
chooseLabel = new JLabel("Choose your symbol :");
xButton = new JRadioButton("X");
oButton = new JRadioButton("O");
bg = new ButtonGroup();
bg.add(xButton);
bg.add(oButton);
/*add the label and the radio buttons too the empty panel*/
emptyPanel.add(chooseLabel);
emptyPanel.add(xButton);
emptyPanel.add(oButton);
emptyPanel.setLayout(new FlowLayout());
/*add the exit,undo and reset buttons to the icon panel*/
iconPanel.setLayout(new GridLayout(3, 1, 3, 3));
resetButton = new JButton("Reset");
exitButton = new JButton("Exit");
undoButton = new JButton("Undo Move");
iconPanel.add(resetButton);
iconPanel.add(exitButton);
iconPanel.add(undoButton);
/*Set layout of the tictactoe board and add the game buttons to it */
tictactoeBoard.setLayout(new GridLayout(3, 3));
/* Mouse adapter object that listens to the buttons in the tic tac toe board */
mam = new MouseAdapterMod();
for (int i = 0; i < 9; i++) {
JButton button = new JButton("");
button.addMouseListener(mam);
tictactoeBoard.add(button);
}
/*add the icon panel and the empty panel to the right pane*/
rightPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, iconPanel, emptyPanel);
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tictactoeBoard, rightPane);
add(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
//setMaximumSize(new Dimension(500, 500));
setMinimumSize(new Dimension(700, 500));
setLocationRelativeTo(null);
pack();
setTitle("Tic Tac Toe");
setLocationRelativeTo(null);
setVisible(true);
}
}
class MouseAdapterMod extends MouseAdapter {
/*Set 'X' or 'O' based the selected radio button- how to achieve this? */
public void mousePressed(MouseEvent e) {
//JButton button = (JButton)e.getSource();
//button.setText("");
}
}
You can create a variable within your MouseAdapterMod, and assign whatever you need (e.g. the GUI) to it (or a reference of a JButton) through the constructor.
You can then use that to access any information you need during runtime clicking.
Example:
Note: Use getter methods as you wish.
class MouseAdapterMod extends MouseAdapter {
/*Set 'X' or 'O' based the selected radio button- how to achieve this? */
JRadioButton xButton;
public MouseAdapterMod(JRadioButton xButton)
{
this.xButton = xButton;
}
public void mousePressed(MouseEvent e) {
JButton button = (JButton)e.getSource();
if(xButton.isSelected())
button.setText("X");
else
button.setText("O");
}
}
/**
*
* #author saikrishnan.srivat
*/
public class TicTacToe extends JFrame {
/*declare the components of the window*/
JPanel iconPanel;
JPanel tictactoeBoard;
JPanel emptyPanel;
JLabel chooseLabel;
JRadioButton xButton;
JRadioButton oButton;
ButtonGroup bg;
JButton resetButton;
JButton exitButton;
JButton undoButton;
JSplitPane rightPane;
JSplitPane pane;
MouseAdapterMod mam;
public static void main(String args[])
{
new TicTacToe();
}
public TicTacToe() {
iconPanel = new JPanel();
tictactoeBoard = new JPanel();
emptyPanel = new JPanel();
chooseLabel = new JLabel("Choose your symbol :");
xButton = new JRadioButton("X");
oButton = new JRadioButton("O");
bg = new ButtonGroup();
bg.add(xButton);
bg.add(oButton);
/*add the label and the radio buttons too the empty panel*/
emptyPanel.add(chooseLabel);
emptyPanel.add(xButton);
emptyPanel.add(oButton);
emptyPanel.setLayout(new FlowLayout());
/*add the exit,undo and reset buttons to the icon panel*/
iconPanel.setLayout(new GridLayout(3, 1, 3, 3));
resetButton = new JButton("Reset");
exitButton = new JButton("Exit");
undoButton = new JButton("Undo Move");
iconPanel.add(resetButton);
iconPanel.add(exitButton);
iconPanel.add(undoButton);
/*Set layout of the tictactoe board and add the game buttons to it */
tictactoeBoard.setLayout(new GridLayout(3, 3));
/* Mouse adapter object that listens to the buttons in the tic tac toe board */
mam = new MouseAdapterMod(xButton);
for (int i = 0; i < 9; i++) {
JButton button = new JButton("");
button.addMouseListener(mam);
tictactoeBoard.add(button);
}
/*add the icon panel and the empty panel to the right pane*/
rightPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, iconPanel, emptyPanel);
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tictactoeBoard, rightPane);
add(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
//setMaximumSize(new Dimension(500, 500));
setMinimumSize(new Dimension(700, 500));
setLocationRelativeTo(null);
pack();
setTitle("Tic Tac Toe");
setLocationRelativeTo(null);
setVisible(true);
}
}
My suggestion is to use an array of JButtons combined with ActionListener.
Try out the following quick SSCCE I just wrote and see if it will give you some good ideas:
(Once you click any of the 9 buttons, the console shall write the button number)
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
class test extends JFrame implements ActionListener
{
JButton button[] = new JButton[9];
public test()
{
init();
initializeAndAddButtons();
}
private void init()
{
this.setLayout(new GridLayout(3, 1, 3, 3));
this.setSize(600,600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setTitle("Test");
}
private void initializeAndAddButtons()
{
for(int i = 0; i < 9;i++)
{
button[i] = new JButton(String.valueOf(i));
button[i].addActionListener(this);
add(button[i]);
}
}
public void actionPerformed(ActionEvent e)
{
JButton tempButton = (JButton) e.getSource();
System.out.println(tempButton.getText());
}
}
public class main
{
public static void main(String args[])
{
new test().setVisible(true);
}
}
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.