I am currently working on making a digital school planner and want to use multiple JButtons inside a JTabbedPane. But I am currently having a problem where even one button takes up the whole pane and would like a solution to this.
I have created a test program that mirrors how i am coding my main program:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class tabTest extends JFrame {
private static final long serialVersionUID = 5101892517858668104L;
private JFrame frame;
private int WIDTH = 450;
private int HEIGHT = 600;
private JTabbedPane tab;
public tabTest() {
frame = new JFrame();
// frame.setUndecorated(true);
/****************************************************
* Set up frame
*****************************************************/
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocation(50, 50);
frame.getContentPane().setBackground(Color.GRAY);
frame.getContentPane().setLayout(null);
/******************************************************
* Set up Tabbed pane and buttons
******************************************************/
tab = new JTabbedPane();
tab.setBounds(20, 50, 400, 500);
tab.setBackground(Color.white);
tab.setFocusable(false);
JButton tabButton1 = new JButton("test");
tab.addTab("Week 1", tabButton1);
tab.addTab("Week 2", null);
tab.addTab("Week 3", null);
tab.addTab("Week 4", null);
frame.getContentPane().add(tab);
frame.setVisible(true);
}
public static void main(String[] args) {
new tabTest();
}
}
i have tried using BorderLayout.POSITION and it chucked up error after error any alternate solution would be great :)
Your tabbedPane can only hold one "object". If you add a button, your pane is full. However you can add a container with more room to the pane. For example a JPanel. The JPanel can now hold as many "objects" as you want and can use it's own LayoutManager.
JPanel moreButtons = new JPanel();
moreButtons.add(new JButton("test1"));
moreButtons.add(new JButton("test2"));
moreButtons.add(new JButton("test3"));
moreButtons.add(new JButton("test4"));
tab.addTab("Week 1", moreButtons);
Also you crete and initialize your whole GUI inside the constructor. It might be cleaner to define a second methode like initializeGUI() to seperate the creation of the object and the initilazation of your GUI. Also you should seperate the GUI-thread and the Main-thread, by using invokeLater
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Gui g = new Gui();
g.initalizeGUI();
Gui.setVisible(true);
}
});
}
There is no need to extend JFrame and to create a seperate JFrame inside your JFrame. Remove the extends JFrame or the creation of your JFrame inside the class. You can access the JFrame mehtodes from inside your extended class.
public class MyFrame extends JFrame {
public MyFrame () {
/**
* Set up frame
*/
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setLocation(50, 50);
getContentPane().setBackground(Color.GRAY);
getContentPane().setLayout(null);
}
}
Add another container like JPanel inside your JTabbedPane like this:
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // you can change layout according to your need.
p.add(tabButton1);
tab.addTab("Week 1", panel);
tab.addTab("Week 2", null);
tab.addTab("Week 3", null);
tab.addTab("Week 4", null);
Add all your components to the JPanel that you want to show on the tabs.
Related
I'm trying to learn Java and JFrames. I put together this simple app where the Main class launches the MainGui class. MainGui will contain a bunch of buttons that each does something different (right now it only has the canadaFlagButton). I have no problem getting the window for MainGui to open with the button I created.
However, when I click the canadaFlagButton, it is supposed to launch a new window but instead, nothing happens.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainGui extends JFrame implements ActionListener {
JButton canadaFlagButton;
MainGui() {
canadaFlagButton = new JButton("Canada Flag");
canadaFlagButton.setBounds(100, 100, 200, 50);
canadaFlagButton.setFocusable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 600);
this.setLayout(null);
this.add(canadaFlagButton);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==canadaFlagButton) {
CanadaFlag window1 = new CanadaFlag();
}
}
}
//Can I draw the Canadian flag?
This is the CanadaFlag class:
import javax.swing.*;
import java.awt.*;
public class CanadaFlag extends JFrame {
CanadaFlag() {
//creating label for maple leaf
JLabel leafLabel = new JLabel();
ImageIcon leaf = new ImageIcon("mapleleaf.png");
leafLabel.setIcon(leaf);
leafLabel.setVerticalAlignment(JLabel.CENTER);
leafLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel redLeftPanel = new JPanel();
redLeftPanel.setBackground(Color.red);
redLeftPanel.setBounds(0, 0, 400, 1000);
JPanel redRightPanel = new JPanel();
redRightPanel.setBackground(Color.red);
redRightPanel.setBounds(1000, 0, 400, 1000);
JPanel whiteMiddlePanel = new JPanel();
whiteMiddlePanel.setBackground(Color.white);
whiteMiddlePanel.setBounds(400, 0, 600, 1000);
whiteMiddlePanel.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setSize(1400, 1000);
this.setVisible(true);
this.add(redLeftPanel);
this.add(redRightPanel);
this.add(whiteMiddlePanel);
whiteMiddlePanel.add(leafLabel);
}
}
An application should only have a single main JFrame. If you need other windows then you would typically use a JDialog.
Swing was designed to be used with layout manager. If you are trying to learn Swing then check out the Swing tutorial on Layout Managers for more information and working example.
it is supposed to launch a new window but instead, nothing happens
You never add the ActionListener to the button.
canadaFlagButton.addActionListener( this );
The tutorial also has a section on How to Use Buttons that contains a working example. I suggest you keep a reference to the tutorial for examples of all Swing basics.
I am writing some Java code that allows the user to see a frame with JLabel, JTextField and JButton.
I want the JLabel to be called "Count" and I have a problem with FlowLayout.
I want the interface to look like this:
Instead, I have this:
This is my code:
package modul1_Interfate_Grafice;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Exercitiu04 implements ActionListener {
private JFrame frame;
private JLabel labelCount;
private JTextField tfCount;
private JButton buttonCount;
private int count = 0;
public void go() {
frame = new JFrame("Java Counter");
labelCount = new JLabel("Counter");
labelCount.setLayout(new FlowLayout());
frame.getContentPane().add(BorderLayout.CENTER, labelCount);
tfCount = new JTextField(count + " ", 10);
tfCount.setEditable(false);
labelCount.add(tfCount);
buttonCount = new JButton("Count");
labelCount.add(buttonCount);
buttonCount.addActionListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 150);
frame.setLocation(400, 200);
}
#Override
public void actionPerformed(ActionEvent event) {
count++;
tfCount.setText(count + "");
}
public static void main(String[] args) {
Exercitiu04 a = new Exercitiu04();
a.go();
}
}
Solve it.
Instead of labelCount.setLayout(new FlowLayout());` i should have had
frame.setLayout(new FlowLayout());
From description of JLabel class,
JLabel is:
A display area for a short text string or an image, or both.
But here: labelCount.add(tfCount) and here labelCount.add(buttonCount) you're trying to put a textfield and a button into a label. In this case, positions of button and textfield are controlled by FlowLayout but position of the text in the label is not.
Instead of this, you should put all of your elements in common JPanel, like this:
...
frame = new JFrame("Java Counter");
frame.setLayout(new BorderLayout());
JPanel wrapper = new JPanel(); // JPanel has FlowLayout by default
labelCount = new JLabel("Counter");
labelCount.setLayout(new FlowLayout());
wrapper.add(labelCount);
tfCount = new JTextField(count + " ", 10);
tfCount.setEditable(false);
wrapper.add(tfCount);
buttonCount = new JButton("Count");
buttonCount.addActionListener(this);
wrapper.add(buttonCount);
frame.add(BorderLayout.CENTER, wrapper);
...
And, like MasterBlaster said, you should put swing methods in EDT.
There are only two things you should know about FlowLayout:
a) It is a default layout manager of the JPanel component
b) It is good for nothing.
This trivial layout cannot be achieved with FlowLayout.
When doing layouts in Swing, you should familiarize yourself
with some powerful layout managers. I recommend MigLayout and
GroupLayout.
package com.zetcode;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
Simple UI with a MigLayout manager.
Author Jan Bodnar
Website zetcode.com
*/
public class MigLayoutCounterEx extends JFrame {
public MigLayoutCounterEx() {
initUI();
}
private void initUI() {
JLabel lbl = new JLabel("Counter");
JTextField field = new JTextField(10);
JButton btn = new JButton("Count");
createLayout(lbl, field, btn);
setTitle("Java Counter");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout());
add(arg[0]);
add(arg[1]);
add(arg[2]);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutCounterEx ex = new MigLayoutCounterEx();
ex.setVisible(true);
});
}
}
The example is trivial. You just put the three components into the
cells.
Screenshot:
You shouldn't use setSize when dealing with FlowLayout. Instead use pack(). It makes the window just about big enough to fit all your components in. That should tidy things up for you
I'm trying to do a little program that use some buttons and text field.
I was able to create window with JPanel but don't have idea how to add button and text field
The code I'm using is:
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,SZEROKOSC,WYSOKOSC);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
panel.add(this);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextField pole = new JTextField(10);
JButton przycisk = new JButton("teasda");
przycisk.setPreferredSize(new Dimension(300, 350));
przycisk.setLayout(new BorderLayout());
panel.add(przycisk);
przycisk.setVisible(true);
pole.setBounds (300,300,200,200);
pole.setLayout(null);
pole.setVisible(true);
panel.add(pole);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
// addMouseListener(this);
}
You need to use the layout properly, when using border layout you need to tell it which border to use (, BorderLayout.NORTH or something), check out the tutorials at oracles page.
P.S. Think of how your naming your fields etc. Naming something "przycisk" just gives me a reason not to read the code further.
Thank You for help and sorry for Polish names(fixed already).
I was able to add Text Area with scroll.
Looks like problem was in panel.add(this); putted before button and text field.
From my understanding if panel.add(this) is set before panel.add(pole); then panel.add(this) is set in front and pole is added but not seen.
Below my actual working code:
...
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,WIDTH,HEIGHT);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextArea pole = new JTextArea();
pole.setLayout(null);
pole.setLineWrap(true);
//pole.setBackground(Color.BLACK);
pole.setEditable(false);
JScrollPane scroll = new JScrollPane(pole);
scroll.setBounds(25,250,500,300);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll);
panel.add(this);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
addMouseListener(this);
}
...
This code is from this site: Example of Java GUI
//Imports are listed in full to show what's being used
//could just import javax.swing.* and java.awt.* etc..
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GuiApp1 {
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
new GuiApp1();
}
public GuiApp1()
{
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Example GUI");
guiFrame.setSize(300,250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//Options for the JComboBox
String[] fruitOptions = {"Apple", "Apricot", "Banana"
,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
//Options for the JList
String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish", "Shallot", "Spinach", "Swede"
, "Turnip"};
//The first JPanel contains a JLabel and JCombobox
final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Fruits:");
JComboBox fruits = new JComboBox(fruitOptions);
comboPanel.add(comboLbl);
comboPanel.add(fruits);
//Create the second JPanel. Add a JLabel and JList and
//make use the JPanel is not visible.
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
JList vegs = new JList(vegOptions);
vegs.setLayoutOrientation(JList.HORIZONTAL_WRAP);
listPanel.add(listLbl);
listPanel.add(vegs);
JButton vegFruitBut = new JButton( "Fruit or Veg");
//The ActionListener class is used to handle the
//event that happens when the user clicks the button.
//As there is not a lot that needs to happen we can
//define an anonymous inner class to make the code simpler.
vegFruitBut.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
//When the fruit of veg button is pressed
//the setVisible value of the listPanel and
//comboPanel is switched from true to
//value or vice versa.
listPanel.setVisible(!listPanel.isVisible());
comboPanel.setVisible(!comboPanel.isVisible());
}
});
//The JFrame uses the BorderLayout layout manager.
//Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
guiFrame.add(listPanel, BorderLayout.CENTER);
guiFrame.add(vegFruitBut,BorderLayout.SOUTH);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
}
For the future i will recommend you to use the extends JFrame so you can only write a gui like this without initialize a JFrame:
public class CalculatorGUI extends JFrame {
public CalculatorGUI() {
setTitle("Calculator");
setBounds(300, 300, 220, 200);
}}
I suggest you check out a couple of tutorials about how to create a Java Gui or sth.
I am trying to make a JFrame with a button in it, but my button doesnt have my wanted text! I'm setting it in the button constructor AND afterwards with setText, but it still doesnt show up! Also, the button fills the whole frame, is there a way to make it not stick to the edges of the JFrame?
import javax.swing.*;
public class main
{
public static void main(String[] args)
{
JFrame mainWindow = new JFrame("8 Game");
mainWindow.setSize(200, 200);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setSize(30, 30);
eightButton.setBounds(5, 5, 25, 25);
eightButton.setContentAreaFilled(false);
eightButton.setAction(new buttonAction());
mainWindow.add(eightButton);
mainWindow.setVisible(true);
}
}
Why does it work for me and not you? (with the FlowLayout suggested by others
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class main
{
public static void main(String[] args)
{
JFrame mainWindow = new JFrame("8 Game");
mainWindow.setLayout(new FlowLayout(FlowLayout.CENTER));
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(200, 200);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setSize(30, 30);
eightButton.setBounds(5, 5, 25, 25);
//eightButton.setAction(new buttonAction());
//eightButton.setContentAreaFilled(false);
mainWindow.add(eightButton);
mainWindow.setVisible(true);
}
}
EDIT
an Action needs a title. If you don't specify one, the button will have no title. If you did this
eightButton.setAction(new buttonAction(), "8");
it would work.
Use a layout manager that respects the component's preferred size
mainWindow.setLayout(new FlowLayout(FlowLayout.CENTER));
Swing components expect a layout manager context when they are added to a window.
The default layout is BorderLayout, which is why you're getting that odd behavior. With only a single element, BorderLayout fills the pane with that element.
Try something like FlowLayout or AbsoluteLayout (or null)
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Use another LayoutManager default frame's layout manager is BorderLayout that if you add a component without specification will add to the center. You can use FlowLayout. See example with SwingUtilities.invokeLater you ensure that will run in EDT.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame mainWindow = new JFrame("8 Game");
mainWindow .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setLayout(new FlowLayout());
mainWindow.setLocationRelativeTo(null);
JButton eightButton = new JButton("8");
eightButton.setText("8");
eightButton.setContentAreaFilled(false);
eightButton.setAction(new buttonAction());
mainWindow.add(eightButton);
mainWindow.pack();
mainWindow.setVisible(true);
}
});
}
Take a look of more complete correct examples in official tutorials How to use Buttons
For my homework extra credit I am creating a JTabbedPane and adding two Jpanels. I feel like I am very close, but it still does not compile. When I run it, both JPanels open, but the JTabbedPane does not. I get a lot of Unknown Source errors. I suspect that at this point my issue in in the JPanels themselves because they started out being JFrames and I have tried (unsuccessfully I think) to convert the JFrames to JPanels.
JTabbedPaneAssignment is supposed to create the JTabbedPane and populate the two panes with the apps DayGui on one tab and OfficeAreaCalculator on the other. I only include the JTabbedPaneAssignment and DayGui classes here. I apologize if its too much code, I have trimmed off a lot of what I consider extraneous, but there may still be too much.
Here is the calling class JTabbedPaneAssignment
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTabbedPaneAssignment extends JPanel
{
public JTabbedPaneAssignment()
{
//super(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
DayGui pnlDay = new DayGui();
OfficeAreaCalculator pnlOffice = new OfficeAreaCalculator ();
this.add(tabbedPane);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
tabbedPane.add(panel1,"First panel");
tabbedPane.add(panel2,"Second panel");
//JComponent panel1 = makeTextPanel("Pane #1");
panel1.setPreferredSize(new Dimension(300, 150));
tabbedPane.addTab("DayGui", panel1);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
//JComponent panel2 = makeTextPanel("Pane #2");
panel2.setPreferredSize(new Dimension(410, 50));
tabbedPane.addTab("OfficeAreaCalculator", panel2);
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
add(tabbedPane);
}
protected JComponent makeTextPanel(String text)
{
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
// Create JTabbedPane
private static void createAndShowGUI()
{
// Create and set up the window.
JFrame frame = new JFrame("JTabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTabbedPaneAssignment(), BorderLayout.CENTER);
JTabbedPane DayGui = new JTabbedPane();
JTabbedPane OfficeAreaCalculator = new JTabbedPane();
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Here is DayGui class. It started out as a JFrame, but I am trying to convert it to a JPanel. I think my issue is in this section of code, but I don't know
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//public class DayGui extends JPanel
public class DayGui extends JPanel
{
private JPanel dayPanel;
private JButton cmdGood;
private JButton cmdBad;
public DayGui()
{
//dayPanel = new JPanel("Messages");
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
Container c = dayPanel.getRootPane();
c.setLayout(new FlowLayout());
c.add(cmdGood);
c.add(cmdBad);
dayPanel.setSize(300, 150);
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
dayPanel.setVisible(true);
dayPanel.getRootPane().setBackground(Color.CYAN);
}
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);
}
}
}
You have been very ambiguous with your question, and you've posted way more code than anyone here has time to trawl through.
I've made a very small but working JTabbedPane example for you to see the smallest amount of work you need to get it working.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class JTabbedPaneExample extends JFrame{
public JTabbedPaneExample(String title){
super(title);
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panelOne = new JPanel();
JPanel panelTwo = new JPanel();
tabbedPane.add(panelOne,"First panel");
tabbedPane.add(panelTwo,"Second panel");
add(tabbedPane);
}
public static void main(String[] args){
new JTabbedPaneExample("JTP Example").setVisible(true);
}
}
Then running, this code looks like:
If you repeat the same process in your code, and you've still got errors, then the problem is not with your JTabbedPane, but something else.
Okay, here goes a second time. Now you've got the DayGui class up, we notice that you're trying to use dayPanel before you've initialised it. i.e. nowhere do you say dayPanel = new JPanel();. This resulted in a NullPointerException being thrown in your code, screwing up your normal course of exection. Fix this and your DayGui class would run fine at runtime.
Among your codebase, you also do some very funky things, namely start using something but never getting around to finishing it up. An example of this is you extending JPanel, but resorting to using a member variable of type JPanel to do the rest of the work. The suggestion is to scrap the instance variable all together and use the methods you've inherited from extending JPanel.
Now lets move onto your JTabbedPaneAssignment class. Although not terrible, the code is not very readable and it repeats itself in many places (adding your tabbedpanel multiple times). If you were to take this code further into a larger project, maintenance and debugging would quickly become a problem.
For the purposes of showing you how much clutter you had in your code, I've quickly rewritten your provided code to be compilable, and should roughly do what you're working on.
JTabbedPaneAssignment:
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class JTabbedPaneAssignment extends JPanel
{
public JTabbedPaneAssignment()
{
final JTabbedPane tabbedPane = new JTabbedPane();
final DayPanel dayPanel = new DayPanel();
final JPanel officePanel = new JPanel();
tabbedPane.add("DayGui", dayPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
tabbedPane.add("OfficeAreaCalculator", officePanel);
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
add(tabbedPane);
}
// Create JTabbedPane
private static void createAndShowGUI()
{
// Create and set up the window.
JFrame frame = new JFrame("JTabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTabbedPaneAssignment(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
DayGui - renamed as DayPanel:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class DayPanel extends JPanel {
public DayPanel() {
super();
setBackground(Color.CYAN);
final JButton goodButton = new JButton("Good");
final JButton badButton = new JButton("Bad");
ActionListener listener = new DayPanel.ButtonsHandler();
goodButton.addActionListener(listener);
badButton.addActionListener(listener);
add(goodButton);
add(badButton);
}
class ButtonsHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
final String command = ((JButton) e.getSource()).getActionCommand();
if (command.equals("Good")) {
showMessage("Today is a good day!");
} else if (command.equals("Bad")) {
showMessage("Today is a bad day!");
}
}
// Show popup message
private void showMessage(String message) {
JOptionPane.showMessageDialog(null, message,
"Event Handler Message", JOptionPane.INFORMATION_MESSAGE);
}
}
}
So what is different in these? Basically, I've removed your NullPointerException you were getting in DayGui. Any other changes I've made are with the intention than you try and keep your code clutter free, so you really know what is going on in your code.
Hope this helps.
When I run it, both JPanels open, but the JTabbedPane does not. I get
a lot of Unknown Source errors.
Well, based on your code and your import section:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
This lines won't compile (unless DayGUI and OfficeAreaCalculator classes are in the same package than your JTabbedPaneAssignment class):
DayGui pnlDay = new DayGui();
OfficeAreaCalculator pnlOffice = new OfficeAreaCalculator ();
This is the only error I've got trying to compile and run your example. I changed lines below:
tabbedPane.addTab( "DayGui", new JPanel());
tabbedPane.addTab("Office Calculator", new JPanel());
And it worked like a charm.
Update
Based on your recent edit (adding your DayGui class, thank you) you have couple of mistakes in your code.
DayGui : this class extends of JPanel so you need to add your components directly on this class, you don't need this panel:
private JPanel dayPanel;
You need to set the layout manager, buttons and background directly on DayGuiclass, like this:
public DayGui() {
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
setLayout(new FlowLayout());
add(cmdGood);
add(cmdBad);
setSize(300, 150);
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
setBackground(Color.CYAN);
}
JTabbedPaneAssignment : I think you're trying to add panel1 and panel2 as tabs but you use add method instead addTab:
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
tabbedPane.add(panel1,"First panel");
tabbedPane.add(panel2,"Second panel");
Also this line:
tabbedPane.addTab("DayGui", panel1);
Should be:
tabbedPane.addTab("DayGui", pnlDay);
Finally in this line you are adding panel2 for a second time and that's not correct:
tabbedPane.addTab("OfficeAreaCalculator", panel2); //I'd comment this line
If you make suggested changes you'll see something like this (BTW the CYAN color almost made me blind :P):
Hope this be helpful and sorry for the extension.