Don't know how to use an external pane for GUI - java

I have the following 2 java classes. I want to make a third class. The third class is supposed to be a tabbed pane which has two tabs. one tab should have the first pane that i put up and the 2nd tab should have the 2nd one I put up. I can't figure it out. Please help me before I break my computer. I've searched everywhere. I've tried to read the oracle documents and it just doesn't click for me I guess. I have read my text over and over and over and........
package Week4;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class OfficeAreaCalculator extends JFrame{
private JFrame mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;
public OfficeAreaCalculator()
{
mainFrame = new JFrame("Office Area Calculator");
exitButton = new JButton("Exit");
lengthLabel = new JLabel("Enter the length of the office:");
widthLabel = new JLabel("Enter the width of the office:");
areaLabel = new JLabel("Office area:");
lengthField = new JTextField(5);
widthField = new JTextField(5);
areaField = new JTextField(5);
areaField.setEditable(false);
calculateButton = new JButton("Calculate");
Container c = mainFrame.getContentPane();
c.setBackground(Color.white);
c.setLayout(new FlowLayout());
c.add(lengthLabel);
c.add(lengthField);
c.add(widthLabel);
c.add(widthField);
c.add(areaLabel);
c.add(areaField);
c.add(calculateButton);
c.add(exitButton);
calculateButton.setMnemonic('C');
exitButton.setMnemonic('X');
mainFrame.setSize(260, 150);
mainFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
CalculateButtonHandler chandler = new CalculateButtonHandler();
calculateButton.addActionListener(chandler);
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
areaField.addFocusListener(fhandler);
mainFrame.setVisible(true);
}
class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(",###.##");
double width, length, area;
String instring;
instring = lengthField.getText();
if (instring.equals(""))
{
instring = ("0");
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if (instring.equals(""))
{
instring = "0";
widthField.setText("0");
}
width = Double.parseDouble(instring);
area = length * width;
areaField.setText(num.format(area));
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if (e.getSource() == lengthField || e.getSource() == widthField)
{
areaField.setText("");
}
else if (e.getSource() == areaField)
{
calculateButton.requestFocus();
}
}
public void focusLost(FocusEvent e)
{
if (e.getSource() == widthField)
{
calculateButton.requestFocus();
}
}
}
public static void main(String arg[])
{
new OfficeAreaCalculator();
}
}
and
package Week4;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.*;
public class DayGUI extends JFrame
{
private JFrame mainFrame;
private JButton cmdGood;
private JButton cmdBad;
public DayGUI(){
mainFrame = new JFrame("Messages");
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
Container c = mainFrame.getContentPane();
c.setBackground(Color.white);
c.setLayout(new FlowLayout());
c.add(cmdGood);
cmdGood.setBackground(Color.green);
c.add(cmdBad);
cmdBad.setBackground(Color.red);
cmdGood.setMnemonic('G');
cmdBad.setMnemonic('B');
mainFrame.setSize(300, 100);
mainFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
mainFrame.setVisible(true);
}
class ButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e){
if (e.getSource() == cmdGood)
JOptionPane.showMessageDialog(null, "Today is a good day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
if (e.getSource() == cmdBad)
JOptionPane.showMessageDialog(null, "Today is a bad day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DayGUI app;
app = new DayGUI();
}
}

You can't add a Jframe to a tabbed pane. if each of your application was a JPanel you could just add them to your JTabbedPane.
each one of your JFrame classes uses a JFrame, and in the frame, each class creates its content.
You can re-arrange your code so that each of your JFrame creates a panel which creates its content just like the Jframe. then the panel is added to the JFrame. your first two applications should still work.
for your third class, use a Jframe, add the JTabbedPane to the Jframe, and then add the two panels created above (one from each of your first two) to your tabbed pane.
the easiest way is probably to accomplish the 3rd class is to just change the first two classes to extend JPanel instead of Jframe.
Then create a class which extends from JFrame, and adds a JTabbedPane which adds the two panels.

Related

JTextField text won't print

as you see I have made a very simple program where I input text on a textfield, then press the button to print it on the console:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Main {
private static class Window extends JFrame {
private static class TextField extends JTextField {
private TextField() {
setVisible(true);
setBounds(5, 0, 190,20);
}
}
public class Button extends JButton implements ActionListener {
private Button() {
setText("print");
addActionListener(this);
setVisible(true);
setBounds(5, 35, 190,20);
}
public void actionPerformed(ActionEvent e) {
TextField textField = new TextField();
String input = textField.getText();
System.out.println(input);
}
}
However, while I click the button, it adds blank lines to the console, without the text I have written in it.
Your actionPerformed method creates a new TextField instance and prints the text from that new instance.
A very simple example that works as intended:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TextAndButtonExample {
public static void main( String[] args ) {
EventQueue.invokeLater(() -> new TextAndButtonExample().start());
}
void start() {
JTextField textField = new JTextField();
JButton button = new JButton(new AbstractAction("Print") {
public void actionPerformed( ActionEvent e ) {
System.out.println(textField.getText());
}
});
JPanel controlPane = new JPanel(new GridLayout(2, 1));
controlPane.add(textField);
controlPane.add(button);
JPanel contentPane = new JPanel();
contentPane.add(controlPane);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Note that I did not extend any Swing components and that I did use a layout manager instead of explicitly setting bounds for components.

Using button in a panel class to call ActionListener in the frame class

I started codig Java last weekend and I've read most of the basic stuff. I'm trying to separate my frame from main method, and panels from the frame so they are all in separate class files. I have trouble calling ActionLister in "Frame1" class with a button (buttonBack) in the "TheGame" class. The button should trigger the Listener which in turn should remove theGame panel and add mainMenu panel to frame1. I know that CardLayout is better suited for swapping panels but i want to learn the limits and workarounds before i go do it the "easy" way, i feel that you learn much more that way.
Here is some of my code:
Main:
public class Main {
public static void main(String[] args){
Frame1 frame1 = new Frame1();
frame1.frame1();
}
}
Frame1:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
class Frame1 {
private JFrame frame1 = new JFrame("Name");
public void frame1() {
TheGame theGame = new TheGame();
MainMenu mainMenu = new MainMenu();
// Frame options
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLocationRelativeTo(null);
// Creating a top menu
JMenuBar menubar = new JMenuBar();
frame1.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
JMenuItem about = new JMenuItem("About");
help.add(about);
// Creating action for the menuitem "exit".
class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
exit.addActionListener(new exitaction());
// Creating listener for the menuitem "about".
class aboutaction implements ActionListener{
public void actionPerformed (ActionEvent e){
JDialog dialogabout = new JDialog();
JOptionPane.showMessageDialog(dialogabout, "Made by: ");
}
}
about.addActionListener(new aboutaction());
// Add the panels, pack and setVisible
theGame.theGame();
mainMenu.mainMenu();
frame1.add(theGame.getGUI());
// This is the ActionListener i have trouble connecting with the buttonBack in the "theGame" class
class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
frame1.remove(theGame.getGUI());
frame1.add(MainMenu.getGUI());
}
}
frame1.pack();
frame1.setVisible(true);
}
public JFrame getGUI() {
return frame1;
}
}
MainMenu:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class MainMenu {
private JPanel mainMenu = new JPanel (new GridBagLayout());
public void mainMenu() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating Label
JLabel introduction = new JLabel("Name");
grid.gridx = 1;
grid.gridy = 3;
mainMenu.add(introduction, grid);
// Creating buttons Start Game, Highscore and Exit Game
JButton buttonNewGame = new JButton("New Game");
buttonNewGame.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 5;
mainMenu.add(buttonNewGame, grid);
JButton buttonHighscore = new JButton("Highscore");
buttonHighscore.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 6;
mainMenu.add(buttonHighscore, grid);
JButton buttonExit = new JButton("Exit Game");
buttonExit.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 7;
mainMenu.add(buttonExit, grid);
}
public JComponent getGUI() {
return mainMenu;
}
}
TheGame:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class TheGame {
private JPanel theGame = new JPanel (new GridBagLayout());
public void theGame() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating a label
JLabel label1 = new JLabel("Press the BACK button to go back to Main Menu");
label1.setVisible(true);
grid.gridx = 1;
grid.gridy = 0;
theGame.add(label1,grid);
// Creating BACK button
JButton buttonBack = new JButton("BACK");
buttonBack.setVisible(true);
grid.gridx = 1;
grid.gridy = 1;
buttonBack.addActionListener(new --); // This is the button i want to connect with the ActionListener on Frame1 class
theGame.add(buttonBack, grid);
}
public JComponent getGUI() {
return theGame;
}
}
I've tried moving the ActionListener outside of methods, inside the Main, declaring it static, but haven't been able to call it anyways. I've also looked at other posts like this: Add an actionListener to a JButton from another class but have not been able to implement it in to my code.
Any help is appreciated.
The best answer -- use MVC (model-view-controller) structure (and CardLayout) for the swapping of your views. If you don't want to do that, then your listener should have a reference to the container that does the swapping, and so that the listener can notify this container that a swap should occur. The container will then call its own code to do the swapping. To do this you need to pass references around including a reference to the main GUI to wherever it is needed. This can get messy, which is why MVC, which is more work, is usually better -- fewer connections/complexity in the long term.
Side note -- don't pass a JDialog into a JOptionPane as a JOptionPane is a specialized JDialog, and you shouldn't have a top level window displaying a top level window. Instead pass in a JPanel.
For example:
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PassRef {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
MyMain mainPanel = new MyMain();
JFrame frame = new JFrame("Pass Reference");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class MyMain extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 450;
private CardLayout cardLayout = new CardLayout();
private MenuView menuView = new MenuView(this);
private ActionView1 actionView1 = new ActionView1(this);
public MyMain() {
setLayout(cardLayout);
add(menuView, MenuView.NAME);
add(actionView1, ActionView1.NAME);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
return new Dimension(PREF_W, PREF_H);
}
}
public void showCard(String key) {
cardLayout.show(this, key);
// or swap by hand if you don't want to use CardLayout
// but remember to revalidate and repaint whenever doing it by hand
}
}
class MenuView extends JPanel {
public static final String NAME = "Menu View";
public MenuView(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder("Menu"));
add(new JButton(new GoToAction("Action 1", ActionView1.NAME, myMain)));
}
}
class ActionView1 extends JPanel {
public static final String NAME = "Action View 1";
public ActionView1(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder(NAME));
add(new JButton(new GoToAction("Main Menu", MenuView.NAME, myMain)));
}
}
class GoToAction extends AbstractAction {
private String key;
private MyMain myMain;
public GoToAction(String name, String key, MyMain myMain) {
super(name);
this.key = key;
this.myMain = myMain;
}
#Override
public void actionPerformed(ActionEvent e) {
myMain.showCard(key);
}
}

How to get a combo box to show on button click in java?

i am trying to get it so when a button is pressed a combo box is displayed in java. here is what i have tried.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class main {
public static void main(String[] args) {
final JFrame testFrame = new JFrame();
testFrame.setSize(300,450);
testFrame.setLocation(150,250);
testFrame.setTitle("My frame");
testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
testFrame.setResizable(true);
testFrame.setVisible(true);
testFrame.setLayout(new FlowLayout());
final JButton testButton = new JButton("show");
testFrame.add(testButton);
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent event) {
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == testButton) {
String[] myArray = {"test","test2"};
JComboBox testingCom = new JComboBox(myArray);
testFrame.add(testingCom);
}
}
}
}
}
Any help would be much appreciated. thank you.
Based in your code, you never addActionListener to your button.
In your ActionListener, you are creating a new instance of a combobox each time actionPerformed is called, and i don't if it's that what you want, you may be interested in if it's visible or not.
So you can change your code like this:
final JButton testButton = new JButton("show");
final JComboBox combo = new JComboBox(new String[]{"test1","test2"});
testButton.addActionListener(new ActionListener(){
// this is anonymous class
#Override
public void actionPerformed(ActionEvent evt){
//then you know that is attached to this button
combo.setVisible(!combo.isVisible());
}
});
combo.setVisible(Boolean.FALSE);
testFrame.add(testButton);
testFrame.add(combo);
Simply set the combo visible or invisible in the ActionListener and then revalidate and repaint its container. e.g.,
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
final JComboBox<String> myCombo = new JComboBox<String>(new String[]{"Foo", "Bar"});
final JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(250, 100));
mainPanel.add(new JButton(new AbstractAction("Toggle Combo") {
#Override
public void actionPerformed(ActionEvent arg0) {
myCombo.setVisible(!myCombo.isVisible());
mainPanel.revalidate();
mainPanel.repaint();
}
}));
mainPanel.add(myCombo);
JOptionPane.showMessageDialog(null, mainPanel);
}
}
Perhaps a cleaner way to do it is to use a CardLayout. If you use this, your components won't be shifting on removal and reviewing of the combo. For example:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Main2 {
public static void main(String[] args) {
final JComboBox<String> myCombo = new JComboBox<String>(new String[]{"Foo", "Bar"});
final CardLayout cardLayout = new CardLayout();
final JPanel cardPanel = new JPanel(cardLayout);
cardPanel.add(myCombo, "combo");
cardPanel.add(new JLabel(), "empty");
final JPanel mainPanel = new JPanel();
mainPanel.add(new JButton(new AbstractAction("Toggle Combo") {
#Override
public void actionPerformed(ActionEvent evt) {
cardLayout.next(cardPanel);
}
}));
mainPanel.add(cardPanel);
JOptionPane.showMessageDialog(null, mainPanel);
}
}

addActionListener on panel. How to map to main frame?

I have 2 panel (2 class, extends from JPanel), 1 frame (1 class, extends from JFrame)
My first panel - WelcomePanel:
package caro;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel {
public WelcomePanel() {
ImageIcon logoImage = new ImageIcon("/home/khanhpq/logo.png");
JButton playButton = new JButton("Play");
JButton exitButton = new JButton("Exit");
JLabel imageLabel = new JLabel(logoImage);
add(imageLabel);
add(playButton);
add(exitButton);
playButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure ?", "Warning", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
}
}
My second panel - BoardPanel:
package caro;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class BoardPanel extends JPanel {
public BoardPanel() {
JPanel boardPanel = new JPanel();
Board board = new Board();
CellButton cellButton[] = new CellButton[144];
GridLayout gridLayout = new GridLayout(12, 12);
boardPanel.setLayout(gridLayout);
for (int i = 0; i < 144; i++) {
cellButton[i] = new CellButton();
boardPanel.add(cellButton[i]);
}
}
}
My main frame - MainFrame
package caro;
import javax.swing.JFrame;
public class MainFrame extends JFrame {
public MainFrame() {
add(new WelcomePanel());
setSize(360, 380);
setVisible(true);
}
public static void main(String[] args) {
MainFrame startFrame = new MainFrame();
}
}
My question: Help me write code, addActionListener on buttons of panels (material example). When i press play button (of WelcomePanel), WelcomePanel is hidden and BoardPanel is show. And, when i exit BoardPanel (close button is pressed, or click x button), WelcomePanel is showed.
My friend recommend use Message and Handle, but I don't know. Please help me. Thanks.
Its better to declare dependencies (Component like buttons, panels, etc...) as fields. In this way they are visible for a third class that is the Controller of them. In next examaple I make MainFrame controlling itself, just an example. Read about Presentation patterns for better pratices.
WelcomePanel.java
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
ImageIcon logoImage;
JButton playButton;
JButton exitButton;
JLabel imageLabel;
public WelcomePanel() {
logoImage = new ImageIcon("/home/khanhpq/logo.png");
playButton = new JButton("Play");
exitButton = new JButton("Exit");
imageLabel = new JLabel(logoImage);
add(imageLabel);
add(playButton);
add(exitButton);
}
}
BoardPanel.java
import javax.swing.JButton;
import javax.swing.JPanel;
public class BoardPanel extends JPanel {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
JButton closeButton;
public BoardPanel() {
closeButton = new JButton();
add(closeButton);
}
}
MainFrame.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame implements ActionListener {
/* Declare your dependecies as fields,
* so you can hold a reference.
*/
WelcomePanel welcomePanel;
BoardPanel boardPanel;
public MainFrame() {
welcomePanel = new WelcomePanel();
boardPanel = new BoardPanel();
add(welcomePanel);
add(boardPanel);
boardPanel.setVisible(false);
boardPanel.closeButton.addActionListener(this);
welcomePanel.playButton.addActionListener(this);
setSize(360, 380);
}
/**
* This class is the controller.
*/
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(boardPanel.closeButton)) {
welcomePanel.setVisible(false);
boardPanel.setVisible(true);
} else if (e.getSource().equals(welcomePanel.playButton)) {
welcomePanel.setVisible(true);
boardPanel.setVisible(false);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame startFrame = new MainFrame();
startFrame.setVisible(true);
}
});
}
}

(Java) Why is this tabbed pane not working correctly?

Note: I've searched all over the web (this site and others) and cannot answer this myself.
Ok guys. I am a new Java programmer, and we just got done covering tabbed panes. This is the state in which I turned in my assignment: it doesn't work, and I can't figure out why. I've changed so much crap around, I can't keep it straight in my head anymore, but I know it's probably something incredibly simple.
I apologize for the length of the code, but I'm trying to give you the entirety of my code so you can tell me where I jacked it up.
Thanks in advance. -- Also, I'm aware there are other Warnings (i.e. unused imports), but I'm not worried about those. And, this will not affect my grade (as I said, already submitted), but I want to know wtf I did wrong!
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.awt.Color;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JComponent;
public class TabbedPane1 extends JPanel
{
public TabbedPane1()
{
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
}
public static void main(String[] args)
{
JFrame myFrame = new JFrame("Tabbed Programs");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(new TabbedPane1(), BorderLayout.CENTER);
myFrame.pack();
myFrame.setVisible(true);
}
class DayGui extends JPanel
{
private JPanel mainFrame;
private JButton cmdGood;
private JButton cmdBad;
public DayGui()
{
mainFrame = new JPanel();
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
Container myContainer = mainFrame;
myContainer.setLayout(new FlowLayout());
myContainer.add(cmdGood);
myContainer.add(cmdBad);
cmdGood.setMnemonic('G');
cmdBad.setMnemonic('B');
mainFrame.setSize(300, 100);
myContainer.setBackground(Color.blue);
cmdGood.setBackground(Color.cyan);
cmdBad.setBackground(Color.cyan);
/*mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});*/
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
//mainFrame.setVisible(true);
}
class ButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == cmdGood)
JOptionPane.showMessageDialog(null, "Today is a good day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
if(e.getSource() == cmdBad)
JOptionPane.showMessageDialog(null, "Today is a bad day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
class OfficeAreaCalculator extends JPanel
{
private JPanel mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;
public OfficeAreaCalculator()
{
mainFrame = new JPanel();
exitButton = new JButton("Exit");
calculateButton = new JButton("Calculate");
lengthField = new JTextField(5);
widthField = new JTextField(5);
lengthLabel = new JLabel("Enter the length of the office:");
widthLabel = new JLabel("Enter the width of the office:");
areaLabel = new JLabel("Office area:");
areaField = new JTextField(5);
areaField.setEditable(false);
Container c = mainFrame;
c.setLayout(new FlowLayout());
c.setBackground(Color.green);
c.add(lengthLabel);
c.add(lengthField);
c.add(widthLabel);
c.add(widthField);
c.add(areaLabel);
c.add(areaField);
c.add(calculateButton);
c.add(exitButton);
calculateButton.setMnemonic('C');
exitButton.setMnemonic('x');
mainFrame.setSize(260, 150);
/*mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});*/
CalculateButtonHandler chandler = new CalculateButtonHandler();
calculateButton.addActionListener(chandler);
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
areaField.addFocusListener(fhandler);
//mainFrame.setVisible(true);
}
class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(",###.##");
double width, length, area;
String instring;
instring = lengthField.getText();
if(instring.equals(""))
{
instring = ("0");
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if(instring.equals(""))
{
instring = ("0");
widthField.setText("0");
}
width = Double.parseDouble(instring);
area = length * width;
areaField.setText(num.format(area));
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if(e.getSource() == lengthField || e.getSource() == widthField)
{
areaField.setText("");
}
else if(e.getSource() == areaField)
{
calculateButton.requestFocus();
}
}
public void focusLost(FocusEvent e)
{
if(e.getSource() == widthField)
{
calculateButton.requestFocus();
}
}
}
}
}
You added your JTabbedPane on JPanel.
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
Since JPanel has a FlowLayout as a default, you have this issue. Set layout of your JPanelto BorderLayout and problem will be solved.
setLayout(new BorderLayout()); //Here
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
EDIT:
Also, avoid extending your classes with swing components if you don't want to override methods or define new ones. Prefer composition instead of that. I had that same bad habbit.
For example, instead of extending tour TabbedPane1 class with JPanel, it would be better to just create a method which returns customized JTabbedPane. Something like this:
public JTabbedPane getTabbedPane() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
return tabbedPane;
}
To call it:
myFrame.add(new TabbedPane1().getTabbedPane(), BorderLayout.CENTER);
This way your class will be "opened" for inheritance.

Categories

Resources