Can't re-add the same panel - java

This is driving me insane. I'm trying to change the panels when you click on 3 different buttons and it works, but for one panel - only once.
If you click addPerson - the Person panel shows,
If you then click addCD - the CD panel shows; (same for view store)
If you then click on addPerson - it doesn't work. It throws a nullpointer exception.
Even if you click on addCD/viewstore and THEN add Person it shows but it just won't show a second time.
In a test file, I created a GUI with an add and remove: if I clicked add it threw the null pointer exception but if I just added it already and compiled, it was fine...
/* PERSON PANEL */
public JPanel create_PersonPnl()
{
personPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
personPnl.setBackground(Color.WHITE);
personPnl.setPreferredSize(minPnl);
/* VERTICAL BOX for Person boxes */
Box personBox = Box.createVerticalBox();
personBox.setBorder(new TitledBorder(new LineBorder(Color.DARK_GRAY), "Person"));
/* Horizontal Box for Name Lbl & TF */
Box nameBox = Box.createHorizontalBox();
nameBox.add(Box.createHorizontalStrut(10));
nameLbl = new JLabel("Name: ");
nameBox.add(nameLbl);
nameBox.add(Box.createHorizontalStrut(5));
nameTF = new JTextField();
nameBox.add(nameTF);
nameBox.add(Box.createHorizontalStrut(10));
personBox.add(nameBox);
personBox.add(Box.createVerticalStrut(10));
Box limitBox = Box.createHorizontalBox();
limitBox.add(Box.createHorizontalStrut(10));
limitLbl = new JLabel("CD Limit: ");
limitBox.add(limitLbl);
limitTF = new JFormattedTextField();
limitBox.add(limitTF);
limitBox.add(Box.createHorizontalStrut(10));
personBox.add(limitBox);
personBox.add(Box.createVerticalStrut(10));
personBox.add(addPersonBtn = new JButton("Add Person"));
personBox.add(Box.createVerticalStrut(10));
personList = new JList(temp);
personList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollp = new JScrollPane(personList);
scrollp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollp.setSize(100, 45);
personBox.add(scrollp);
personBox.add(Box.createVerticalStrut(10));
Box optionsBox = Box.createHorizontalBox();
editPrsnBtn = new JButton("Edit");
editPrsnBtn.addActionListener(this);
optionsBox.add(editPrsnBtn);
removePrsnBtn = new JButton("Remove");
removePrsnBtn.addActionListener(this);
optionsBox.add(removePrsnBtn);
personBox.add(optionsBox);
personPnl.add(personBox);
return personPnl;
}
This is what is in my ActionPerformed method.
if(e.getSource() == addPersonBtn)
{
changePnl.removeAll();
changePnl.add(create_PersonPnl());
changePnl.revalidate();
System.out.println("PersonPnl added");
}
if(e.getSource() == addCDBtn)
{
changePnl.removeAll();
changePnl.add(create_CDPnl());
changePnl.revalidate();
}
if(e.getSource() == viewStoreBtn)
{
changePnl.removeAll();
changePnl.add(create_StorePnl());
changePnl.revalidate();
}
Only code for ChangePnl.
changePnl = new JPanel();
changePnl.setBackground(Color.WHITE);
defaultPnl = new JPanel();
defaultPnl.setBackground(Color.WHITE);
defaultPnl.add(new JLabel("Welcome to the CD Store"));
defaultPnl.add(new JLabel("Click an option from the left"));
changePnl.add(defaultPnl);
The S.O.P was to debug to see what was being run.. and that only prints once and that's it unless I take out .add(create_PersonPnl()); so I've narrowed it but I don't have a clue since it works the first time.
Thank in advance!
Separate test file to prove it's create_PersonPnl()
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class Test implements ActionListener
{
JButton add, remove;
JButton addPersonBtn, editPrsnBtn, removePrsnBtn;
JFrame frame;
JFormattedTextField limitTF;
JLabel nameLbl, limitLbl;
JList personList;
JPanel TotalGUI, welcomePnl, mainPnl, imagePnl, changePnl, defaultPnl, cdPnl, storePnl;
JPanel personPnl;
JScrollPane scrollp;
JTextField nameTF;
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
Dimension minPnl = new Dimension(300, 400);
/* Test for JList */
String[] temp = {"1", "2", "3", "4", "1", "2", "3", "4","1", "2", "3", "4","1", "2", "3", "4" };
public Test()
{
frame = new JFrame("CD Store");
frame.setExtendedState(JFrame.NORMAL);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack(); //sets size based on components size in TotalGUI
//frame.setJMenuBar(create_MenuBar());
//frame.setMinimumSize(minDim);
frame.setSize(725, 550);
//set frame location (central to screen)
int fw = frame.getSize().width;
int fh = frame.getSize().height;
int fx = (dim.width-fw)/2;
int fy = (dim.height-fh)/2;
frame.getContentPane().add(create_Content_Pane());
frame.setVisible(true);
//moves the frame to the centre
frame.setLocation(fx, fy);
}
public JPanel create_Content_Pane()
{
JPanel TotalGUI = new JPanel();
TotalGUI.add(remove = new JButton("Remove"));
remove.addActionListener(this);
TotalGUI.add(add = new JButton("Add")); <- this crashes when selected
add.addActionListener(this);
//TotalGUI.add(create_PersonPnl()); <- works just fine
return TotalGUI;
}
public JPanel create_PersonPnl()
{
personPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
personPnl.setBackground(Color.WHITE);
personPnl.setPreferredSize(minPnl);
/* VERTICAL BOX for Person boxes */
Box personBox = Box.createVerticalBox();
personBox.setBorder(new TitledBorder(new LineBorder(Color.DARK_GRAY), "Person"));
/* Horizontal Box for Name Lbl & TF */
Box nameBox = Box.createHorizontalBox();
nameBox.add(Box.createHorizontalStrut(10));
nameLbl = new JLabel("Name: ");
nameBox.add(nameLbl);
nameBox.add(Box.createHorizontalStrut(5));
nameTF = new JTextField();
nameBox.add(nameTF);
nameBox.add(Box.createHorizontalStrut(10));
personBox.add(nameBox);
personBox.add(Box.createVerticalStrut(10));
Box limitBox = Box.createHorizontalBox();
limitBox.add(Box.createHorizontalStrut(10));
limitLbl = new JLabel("CD Limit: ");
limitBox.add(limitLbl);
limitTF = new JFormattedTextField();
limitBox.add(limitTF);
limitBox.add(Box.createHorizontalStrut(10));
personBox.add(limitBox);
personBox.add(Box.createVerticalStrut(10));
personBox.add(addPersonBtn = new JButton("Add Person"));
personBox.add(Box.createVerticalStrut(10));
personList = new JList(temp);
personList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollp = new JScrollPane(personList);
scrollp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollp.setSize(100, 45);
personBox.add(scrollp);
personBox.add(Box.createVerticalStrut(10));
Box optionsBox = Box.createHorizontalBox();
editPrsnBtn = new JButton("Edit");
editPrsnBtn.addActionListener(this);
optionsBox.add(editPrsnBtn);
removePrsnBtn = new JButton("Remove");
removePrsnBtn.addActionListener(this);
optionsBox.add(removePrsnBtn);
personBox.add(optionsBox);
personPnl.add(personBox);
return personPnl;
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == remove)
{
TotalGUI.removeAll();
TotalGUI.revalidate();
}
if(e.getSource() == add)
{
TotalGUI.add(create_PersonPnl());
TotalGUI.revalidate();
}
}
}

In your method
public JPanel create_Content_Pane()
{
JPanel TotalGUI = new JPanel();
TotalGUI.add(remove = new JButton("Remove"));
remove.addActionListener(this);
TotalGUI.add(add = new JButton("Add")); <- this crashes when selected
add.addActionListener(this);
//TotalGUI.add(create_PersonPnl()); <- works just fine
return TotalGUI;
}
The NullPointerException occurs because your private field TotalGUI is null... Remove the JPanel declaration in front of TotalGUI = new JPanel(); That will solve the null pointer problem. This probably solves only your problem in the test scenario... To solve the problem in your original scenario it would be nice to have the complete source code of the class..

Related

Java Nesting Panels Transparency issue with alpha value

I'm a third grade computer engineer student and I'm trying to do a game project. I added a background image to my JFrame. And I tried to make the other panels transparent which I added to frame. I use alpha value for this, Ex: new Color(0,0,0,125). I olso use cardLayout in my program and for every calling a new segment or new page at the center panel; alphavalue takes the whole panels transparency and implement it to the selected panel and it creates a problem. Example : I have 7 buttons at left panel and when I click crimes button, crime panel comes to the center panel and left panel comes inside of center panel with buttons again(transparently).
I have 16 classes, so I only added main class.
Sorry for bad grammar. I hope you can understand me and help me.
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class TheMafia {
public static ImageIcon scale(ImageIcon i,int x,int y) {
Image img = i.getImage();
Image newimg = img.getScaledInstance(x,y,Image.SCALE_SMOOTH);
i = new ImageIcon(newimg);
return i;
}
public static void setButton (JButton b,int x,int y) {
b.setPreferredSize(new Dimension(x,y));
b.setBackground(Color.gray);
b.setForeground(Color.white);
b.setBorder(new LineBorder(Color.black,1));
b.setFont(new Font("Serif",Font.BOLD,18));
}
public static void main(String[] args) {
ImageIcon home2 = new ImageIcon("home.jpg");
home2 = scale(home2,1366,768);
JFrame theMafia = new JFrame();
theMafia.setTitle("The Mafia Game - Best game in the world!");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
theMafia.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theMafia.setContentPane(new JLabel(home2));
theMafia.setLayout(new BorderLayout());
//theMafia.setLayout(new FlowLayout());
//theMafia.setExtendedState(JFrame.MAXIMIZED_BOTH);
theMafia.setSize(800,700);
theMafia.setLocationRelativeTo(null);
theMafia.setVisible(true);
p1.setBackground(new Color(0,0,0,35));
p2.setBackground(new Color(0,0,0,65));
p1.setPreferredSize(new Dimension(250,150));
p2.setPreferredSize(new Dimension(250,150));
//theMafia.add(p1);
//theMafia.add(p2);
// kullanıcı oluşturuldu
User u1 = new User();
// suçlar oluşturuldu
Crime c1 = new Crime();
c1.setName("Yaşlı Kadın");
c1.setDifficulty(5);
c1.setStrength(1);
c1.setMoney(11);
Crime c2 = new Crime();
c2.setName("Dükkan Hırsızlığı");
c2.setDifficulty(10);
c2.setStrength(3);
c2.setMoney(67);
Crime c3 = new Crime();
c3.setName("Araba Hırsızlığı");
c3.setDifficulty(20);
c3.setStrength(6);
c3.setMoney(133);
// suçun seçilmesi
final JPanel crimes = new JPanel(new CardLayout());
//crimes.setBackground(new Color(0,0,0,65));
ImageIcon suçişle = new ImageIcon("suçişle.jpg");
suçişle = scale(suçişle,50,50);
JButton yap = new JButton("Suçu işle!",suçişle);
setButton(yap,100,65);
JPanel crime1 = new JPanel(new GridLayout(2,1));
crime1.setBackground(new Color(0,0,0,35));
crime1.setForeground(Color.white);
JLabel crime1Info = new JLabel("Suç : "+c1.getName()+"\n Para : "+c1.getMoney()+"\n Yapabilme ihtimali : "+c1.getCapable()+"\n Güç : "+c1.getStrength());
crime1Info.setFont(new Font("Serif",Font.BOLD,15));
crime1.add(crime1Info);
crime1.add(yap);
JPanel crime2 = new JPanel(new GridLayout(2,1));
crime2.setBackground(new Color(0,0,0,35));
crime2.setForeground(Color.white);
JLabel crime2Info = new JLabel("Suç : "+c2.getName()+"\n Para : "+c2.getMoney()+"\n Yapabilme ihtimali : "+c2.getCapable()+"\n Güç : "+c2.getStrength());
crime2Info.setFont(new Font("Serif",Font.BOLD,15));
crime2.add(crime2Info);
crime2.add(yap);
JPanel crime3 = new JPanel();
crime3.setBackground(new Color(0,0,0,35));
crime3.setForeground(Color.white);
JLabel crime3Info = new JLabel("Suç : "+c3.getName()+"\n Para : "+c3.getMoney()+"\n Yapabilme ihtimali : "+c3.getCapable()+"\n Güç : "+c3.getStrength());
crime2Info.setFont(new Font("Serif",Font.BOLD,15));
crime3.add(crime3Info);
crime3.add(yap);
crimes.add(crime1,c1.getName());
crimes.add(crime2,c2.getName());
crimes.add(crime3,c3.getName());
String crimesNames [] = {c1.getName(),c2.getName(),c3.getName()};
JComboBox crimesbox = new JComboBox(crimesNames);
crimesbox.setEditable(false);
crimesbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout) (crimes.getLayout());
cl.show(crimes,(String)evt.getItem());
}
});
// menu
final JPanel menus = new JPanel(new CardLayout());
//menus.setBackground(new Color(0,0,0,35));
// crime
JPanel crime = new JPanel(new BorderLayout());
crime.setBackground(new Color(0,0,0,35));
crime.add(crimesbox,BorderLayout.PAGE_START);
crime.add(crimes,BorderLayout.SOUTH);
ImageIcon crimeimage = new ImageIcon("thief.png");
crimeimage = scale(crimeimage,50,50);
final JButton crimeButton = new JButton("Suçlar",crimeimage);
setButton(crimeButton,178,76);
crimeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (menus.getLayout());
if (e.getSource() == crimeButton) {
cl.show(menus,"suç");
}
}
});
// weapon shop
JPanel weaponShop = new JPanel();
//weaponShop.setBackground(new Color(0,0,0,125));
final JButton weaponShopButton = new JButton("Silah Dükkanı");
setButton(weaponShopButton,178,76);
// building
JPanel buildingPanel = new JPanel();
//buildingPanel.setBackground(new Color(0,0,0,125));
final JButton buildingButton = new JButton("Binalar");
setButton(buildingButton,178,76);
// nightlife
JPanel nightLife = new JPanel();
//nightLife.setBackground(new Color(0,0,0,35));
final JButton nightLifeButton = new JButton("Gece Hayatı");
setButton(nightLifeButton,178,76);
// treatment center
JPanel treatmentCenter = new JPanel();
//treatmentCenter.setBackground(new Color(0,0,0,35));
final JButton treatmentCenterButton = new JButton("Tedavi Merkezi");
setButton(treatmentCenterButton,178,76);
// casino
JPanel casinoPanel = new JPanel();
//casinoPanel.setBackground(new Color(0,0,0,35));
final JButton casinoButton = new JButton("Gazino");
setButton(casinoButton,178,76);
// home page
JPanel home = new JPanel();
home.setBackground(new Color(0,0,0,35));
ImageIcon homeimage = new ImageIcon("home.jpg");
homeimage = scale(homeimage,1200,800);
JLabel homelabel= new JLabel();
home.add(homelabel);
ImageIcon homeicon = new ImageIcon("home_icon.png");
homeicon = scale(homeicon,50,50);
final JButton homeButton = new JButton("Home",homeicon);
setButton(homeButton,178,76);
homeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (menus.getLayout());
if (e.getSource() == homeButton) {
cl.show(menus,"home");
}
}
});
menus.add(home,"home");
menus.add(crime,"suç");
menus.add(weaponShop,"silahDükkanı");
menus.add(buildingPanel,"bina");
menus.add(nightLife,"geceHayatı");
menus.add(treatmentCenter,"TedaviMerkezi");
menus.add(casinoPanel,"gazino");
Color grisi=new Color(13,13,13);
JPanel menusButton = new JPanel(new GridLayout(10,1));
//menusButton.setBackground(grisi);
menusButton.add(homeButton);
menusButton.add(crimeButton);
menusButton.add(weaponShopButton);
menusButton.add(buildingButton);
menusButton.add(nightLifeButton);
menusButton.add(treatmentCenterButton);
menusButton.add(casinoButton);
menusButton.setOpaque(false);
theMafia.add(menusButton,BorderLayout.WEST);
theMafia.add(menus,BorderLayout.CENTER);
}
}
Swing does not handle transparent background properly. Swing expects components to be either opaque or non-opaque and the transparency causes a problem because the component is neither.
Check out Background With Transparency for more information and a couple of solutions to solve the problem.

JScrollPane in Jlist

hello goodevening to all i have a problem on my program with the ScrollPane in my JList i cant put an JScrollPane in my list because i am using a panel instead of Container this is my code so far its all runnable the problem is if you enter a high number in the number of times the some output will not be able to see because of the size of my list . so this is the code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MultCen extends JFrame implements ActionListener
{
public static void main(String args [])
{
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.setSize(300,450);
}
JTextField t1 = new JTextField();
JTextField t2 = new JTextField();
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JList list = new JList();
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen()
{
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
l.setBounds(10,10,130,30);
l1.setBounds(10,40,130,30);
t1.setBounds(140,10,130,25);
t2.setBounds(140,40,130,25);
b.setBounds(60,90,75,30);
c.setBounds(150,90,75,30);
list.setBounds(30,140,220,220);
panel.add(t1);
panel.add(t2);
panel.add(l);
panel.add(l1);
panel.add(list);
panel.add(b);
panel.add(c);
getContentPane().add(panel);
b.addActionListener(this);
c.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b)
{
int t3 = Integer.parseInt(t1.getText());
int t4 = Integer.parseInt(t2.getText());
m.addElement("The multiplication Table of "+t3);
for (int cc =1 ; cc <=t4; cc++ )
{
lab.setText(t3+"*"+cc+" = "+(t3*cc));
m.addElement(lab.getText());
list.setModel(m);
}
}
if(e.getSource() == c)
{
t1.setText("");
t2.setText("");
m.removeAllElements();
}
}
}
JScrollPane does not work with null Layout. Use BoxLayout or any other resizeable layout instead. This is the limitation of setLayout(null).
Use Layout managers. You've asked a lot of questions here and I'm sure a few you have been advised not to use null layout. Again here is the tutorial Laying out components Within a container. Learn to use them so you don't run into the million possible problems on the road ahead. This kind of problem being one of them.
here's an example of how you could achieve the same thing with layout managers, and some empty borders for white space.
With Layout Manager
Without Layout Manger
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MultCen extends JFrame {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MultCen e = new MultCen();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.pack();
}
});
}
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JButton b = new JButton("Okay");
JButton c = new JButton("Clear");
JLabel lab = new JLabel();
DefaultListModel m = new DefaultListModel();
public MultCen() {
JPanel topPanel = new JPanel(new GridLayout(2, 2, 0, 5));
JLabel l = new JLabel("Enter a number :");
JLabel l1 = new JLabel("How many times :");
topPanel.add(l);
topPanel.add(t1);
topPanel.add(l1);
topPanel.add(t2);
JPanel buttonPanel = new JPanel();
buttonPanel.add(b);
buttonPanel.add(c);
buttonPanel.setBorder(new EmptyBorder(10, 0, 10, 0));
JList list = new JList();
JScrollPane scroll = new JScrollPane(list);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(300, 300));
JPanel panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(buttonPanel, BorderLayout.CENTER);
panel.add(scroll, BorderLayout.SOUTH);
panel.setBorder(new EmptyBorder(10, 15, 10, 15));
getContentPane().add(panel);
}
}
Side Notes
Run Swing apps from the Event Dispatch Thread. See Initial Threads
When you do decide to use layout managers, just pack() your frame instead of setSize()
Use better variable names.
See Extends JFrame vs. creating it inside the the program

How to arrange multiple panels in JFrame

I am trying to make a simple calculator to practice Graphics (i am a complete GUI noob). I am having some problems with having unneeded spaces after Polyashenkos Calulator and the text area and the space between the text area and the buttons. Also how do i keep that layout but eliminate the space and also make the bottom 3 buttons smaller. Any tips about what im doing or how i can do it better would be much appreciated. Thank you.
import javax.swing.*;
import java.awt.*;
public class calculator {
public static void main(String[] args) {
// creates the JFrame(a window with decorations)
JFrame frame = new JFrame("Calculator");
// stops the program when window is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(377, 350);
// the main panel of the JFrame,
// remembet you cant add content directly to JFrame
JPanel content = new JPanel(new GridLayout(4, 0));
// panel for the text field
JPanel textarea = new JPanel(new GridLayout(4, 0));
// panel for the buttons,
// GridLayout(int rows, int cols, int horiz_gap, int vert_gap)
JPanel buttonarea = new JPanel(new GridLayout(4, 5, 2, 2));
// the panel for the bigger bottom buttons
JPanel secondbuttonarea = new JPanel(new GridLayout(1, 1, 2, 2));
// the panel for the text on top
JPanel label = new JPanel();
content.add(label);
content.add(textarea);
content.add(buttonarea);
content.add(secondbuttonarea);
JLabel words = new JLabel("Polyashenko's Calculator", JLabel.CENTER);
label.add(words);
JTextField enterhere = new JTextField("0.", JTextField.CENTER);
// will set the curser of the text bar on right side
enterhere.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
textarea.add(enterhere);
// makes a button called b1 with text in it
JButton b1 = new JButton("BkSP");
// adds the backspace button to the buttonarea panel
buttonarea.add(b1);
JButton b2 = new JButton("CE");
buttonarea.add(b2);
JButton b3 = new JButton("C");
buttonarea.add(b3);
JButton b4 = new JButton("/");
buttonarea.add(b4);
JButton b5 = new JButton("sqrt");
buttonarea.add(b5);
JButton b6 = new JButton("7");
buttonarea.add(b6);
JButton b7 = new JButton("8");
buttonarea.add(b7);
JButton b8 = new JButton("9");
buttonarea.add(b8);
JButton b9 = new JButton("*");
buttonarea.add(b9);
JButton b10 = new JButton("%");
buttonarea.add(b10);
JButton b11 = new JButton("4");
buttonarea.add(b11);
JButton b12 = new JButton("5");
buttonarea.add(b12);
JButton b13 = new JButton("6");
buttonarea.add(b13);
JButton b14 = new JButton("-");
buttonarea.add(b14);
JButton b15 = new JButton("1/x");
buttonarea.add(b15);
JButton b16 = new JButton("1");
buttonarea.add(b16);
JButton b17 = new JButton("2");
buttonarea.add(b17);
JButton b18 = new JButton("3");
buttonarea.add(b18);
JButton b19 = new JButton("+");
buttonarea.add(b19);
JButton b20 = new JButton("+/-");
buttonarea.add(b20);
JButton b21 = new JButton("0");
secondbuttonarea.add(b21);
JButton b22 = new JButton(".");
secondbuttonarea.add(b22);
JButton b23 = new JButton("=");
secondbuttonarea.add(b23);
// adds the buttonarea panel to the main panel
frame.getContentPane().add(content);
// makes the window visible, put at end of program
frame.setVisible(true);
}
}
one of lessons by Hovercraft Full Of Eels (-: forums.sun.com :-)
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.*;
import javax.swing.*;
public class SciCalc {
private static void createAndShowUI() {
SciCalcGui gui = new SciCalcGui();
SciCalcMenu menu = new SciCalcMenu(gui);
JFrame frame = new JFrame("Calculator");
frame.getContentPane().add(gui.getMainPanel());
frame.setJMenuBar(menu.getJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
private SciCalc() {
}
}
class SciCalcGui {
private static final String[][] STANDARD_BTN_TEXTS = {
{"7", "8", "9", "/"}, {"4", "5", "6", "*"},
{"1", "2", "3", "-"}, {"0", ".", "=", "+"}};
private static final String[][] SCIENTIFIC_BTN_TEXTS = {
{"sqrt", "1/x", "sin"}, {"%", "Exp", "cos"},
{"x^y", "ln", "tan"}, {"x^2", "n!", "sec"}};
private static final int GAP = 5;
private static final Font BTN_FONT = new Font(Font.DIALOG, Font.BOLD, 20);
private JPanel mainPanel = new JPanel();
private JPanel sciPanel;
private JTextField display = new JTextField();
SciCalcGui() {
display.setFont(BTN_FONT);
JPanel standardPanel = createBtnPanel(STANDARD_BTN_TEXTS, "Standard");
sciPanel = createBtnPanel(SCIENTIFIC_BTN_TEXTS, "Scientific");
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.add(standardPanel, BorderLayout.CENTER);
mainPanel.add(sciPanel, BorderLayout.WEST);
mainPanel.add(display, BorderLayout.NORTH);
sciPanel.setVisible(false);
}
public void sciPanelSetVisible(boolean visible) {
sciPanel.setVisible(visible);
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.pack();
}
public JPanel getMainPanel() {
return mainPanel;
}
private JPanel createBtnPanel(String[][] texts, String title) {
JPanel btnPanel = new JPanel();
int rows = texts.length;
int cols = texts[0].length;
btnPanel.setLayout(new GridLayout(rows, cols, GAP, GAP));
for (int row = 0; row < texts.length; row++) {
for (int col = 0; col < texts[row].length; col++) {
JButton btn = new JButton(texts[row][col]);
btn.setFont(BTN_FONT);
btnPanel.add(btn);
}
}
btnPanel.setBorder(BorderFactory.createTitledBorder(title));
return btnPanel;
}
}
class SciCalcMenu {
private static final String STANDARD = "Standard";
private static final String SCIENTIFIC = "Scientific";
private SciCalcGui gui;
private JMenuBar menuBar = new JMenuBar();
private JMenuItem standardView;
private JMenuItem scientificView;
SciCalcMenu(SciCalcGui gui) {
this.gui = gui;
standardView = new JMenuItem(STANDARD, KeyEvent.VK_T);
scientificView = new JMenuItem(SCIENTIFIC, KeyEvent.VK_S);
ViewAction viewAction = new ViewAction();
standardView.addActionListener(viewAction);
scientificView.addActionListener(viewAction);
standardView.setEnabled(false);
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);
viewMenu.add(standardView);
viewMenu.add(scientificView);
menuBar.add(new JMenu("Edit"));
menuBar.add(viewMenu);
menuBar.add(new JMenu("Help"));
}
public JMenuBar getJMenuBar() {
return menuBar;
}
private class ViewAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals(STANDARD)) {
gui.sciPanelSetVisible(false);
standardView.setEnabled(false);
scientificView.setEnabled(true);
} else if (command.equals(SCIENTIFIC)) {
gui.sciPanelSetVisible(true);
standardView.setEnabled(true);
scientificView.setEnabled(false);
}
}
}
}
A GridLayout won't ever look very good in cases like this.
The content expands to fill the box in the grid. You only have minimal control over the spacing between rows and columns.
You may have to change layouts to make it look the way you want. GridBagLayout has all that control but is much harder to configure.
Sometimes you can nest panels with BorderLayout and GridLayout to make it look reasonable. But it is Swing and that means its usable but it becomes very hard to make it look slick.
I always like to use a FlowLayout for OK/Cancel buttons. They look best to me that way and you can push them all left, right or centered. Your calculator buttons should work well with a GridLayout but you can't easily have a tall "Enter" button or a wide "0" button.
For example, try using a vertical BoxLayout instead of a grid that is 4 high by 1 wide.

Java NullPointerException and simplifying codes

I'm try to make a checkin form and i'm trying to design it well but i'm getting this error NullPointer exception.
Here's my code:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class CheckIn extends JPanel{
private String[] text = {" First Name"," Last Name"," Age"," Gender"," Contact No",
" Address"," Room Type"," Room No"," Time In"," How many days"," Payment Method"};
private JPanel designPanel,bottomRightPanel,bottomLeftPanel;
private String[] genderJCB = {"- Select Gender- ","Male","Female"};
private String[] roomJCB = {"- Select Room Type -","Classic","Deluxe","Presidential"};
private JButton submit,cancel;
private JRadioButton fullRB,depositRB;
private buttonHandler bh;
JTextField[] textFields;
private JComboBox<String> genderBox,roomTypeBox ;
public CheckIn(){
//Container settings
setLayout(null);
setBackground(new Color(70,70,70));
//title
JLabel title = new JLabel("Personal Information",SwingConstants.CENTER);
title.setBounds(0,0,300,45);
title.setForeground(Color.ORANGE);
title.setFont(new Font("Arial",Font.BOLD,13));
title.setBorder(BorderFactory.createMatteBorder(0,0,1,0,Color.BLACK));
add(designPanel());
add(title);
//fields
}
public JPanel designPanel()
{
//Sub container settings
designPanel = new JPanel( new GridLayout(12,2));
designPanel.setBounds(0,45,300,505);
designPanel.setBackground(new Color(80,80,80));
designPanel.add(bottomLeftPanel());
designPanel.add(bottomRightPanel());
return designPanel;
}
public JPanel bottomLeftPanel()
{
JPanel bottomLeftPanel = new JPanel();
bottomLeftPanel.setLayout(null);
bottomLeftPanel.setBorder(BorderFactory.createMatteBorder(1,0,0,0,Color.GRAY));
bottomLeftPanel.setBackground(new Color(70,70,70));
bottomButtons();
return bottomLeftPanel;
}
public JPanel bottomRightPanel()
{
JPanel bottomRightPanel = new JPanel();
bottomRightPanel.setLayout(null);
bottomRightPanel.setBorder(BorderFactory.createMatteBorder(1,0,0,0,Color.GRAY));
bottomRightPanel.setBackground(new Color(70,70,70));
bottomButtons();
return bottomRightPanel;
}
public void bottomButtons()
{
bh = new buttonHandler();
cancel = new JButton("Cancel");
cancel.setBounds(25,4,100,32);
cancel.addActionListener(bh);
bottomLeftPanel.add(cancel);
submit = new JButton("Submit");
submit.setBounds(25,4,100,32);
submit.addActionListener(bh);
bottomRightPanel.add(submit);
}
public void components()
{
JLabel[] labels = new JLabel[text.length];
JTextField[] textFields = new JTextField[text.length];
JPanel[] containerPanel = new JPanel[text.length];
for(int x = 0; x < text.length; x++){
//labels
labels[x] = new JLabel(text[x]);
labels[x].setForeground(Color.WHITE);
labels[x].setBorder(new CompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)));
designPanel.add(labels[x]);
containerPanel[x]= new JPanel();
containerPanel[x].setLayout(null);
containerPanel[x].setBackground(new Color(80,80,80));
containerPanel[x].setBorder(new CompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)));
designPanel.add(containerPanel[x]);
//text fields and etc
if(x==3){
genderBox = new JComboBox(genderJCB);
genderBox.setBounds(0,10,120,25);
genderBox.setBackground(Color.WHITE);
containerPanel[x].add(genderBox);
}
else if(x==6){
roomTypeBox = new JComboBox(roomJCB);
roomTypeBox.setBounds(0,10,145,25);
roomTypeBox.setBackground(Color.WHITE);
containerPanel[x].add(roomTypeBox);
}
else if(x==8){
SpinnerDateModel model = new SpinnerDateModel();
model.setCalendarField(Calendar.MINUTE);
JSpinner spinner= new JSpinner();
spinner.setModel(model);
spinner.setEditor(new JSpinner.DateEditor(spinner, "h:mm a "));
spinner.setBounds(0,10,145,25);
containerPanel[x].add(spinner);
}
else if (x==10){
ButtonGroup group = new ButtonGroup();
fullRB = new JRadioButton("Full");
fullRB.setBounds(0,10,50,25);
fullRB.setBackground(new Color(80,80,80));
fullRB.setForeground(Color.white);
depositRB = new JRadioButton("Deposit");
depositRB.setBounds(60,10,70,25);
depositRB.setBackground(new Color(80,80,80));
depositRB.setForeground(Color.white);
group.add(fullRB);
group.add(depositRB);
containerPanel[x].add(fullRB);
containerPanel[x].add(depositRB);
}
else {
textFields[x] = new JTextField();
textFields[x].setBounds(0,10,145,25);
containerPanel[x].add(textFields[x]);
}
}
}
private class buttonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == cancel){
}
else if(e.getSource() == fullRB){
}
}
}
}
Sorry if my work is such a mess. I'm trying my best to simplify it. And that's what i've come up. How can i simplify more my code? and how can i fix my error. Please help and sorry for a noob question.
And here is the stack trace:
Exception in thread "main" java.lang.NullPointerException
at CheckIn.bottomButtons(CheckIn.java:73)
at CheckIn.bottomLeftPanel(CheckIn.java:55)
at CheckIn.designPanel(CheckIn.java:45)
at CheckIn.<init>(CheckIn.java:30)
at HotelMainGUI.leftForms(HotelMainGUI.java:118)
at HotelMainGUI.leftPanel(HotelMainGUI.java:112)
at HotelMainGUI.subFrame(HotelMainGUI.java:32)
at HotelMainGUI.<init>(HotelMainGUI.java:21)
at HotelMainGUI.main(HotelMainGUI.java:189)
You NullPointerException is coming because of these sequence of code:
CheckIn.designPanel() -> bottomLeftPanel() -> bottomButtons()
Inside bottomButons(), you have have line as :
bottomRightPanel.add(submit);
At this point, you bottomRightPanel is not initialized.
Change the designPanel method as below:
public JPanel designPanel() {
//Sub container settings
designPanel = new JPanel( new GridLayout(12,2));
designPanel.setBounds(0,45,300,505);
designPanel.setBackground(new Color(80,80,80));
designPanel.add(bottomRightPanel());
designPanel.add(bottomLeftPanel());
return designPanel;
}
Moved designPanel.add(bottomRightPanel()); before designPanel.add(bottomLeftPanel());
Hope this resolves your issues.
Also there is lot of room for code restruring e.g. in your bottomRightPanel and bottomLeftPanel, below statements seems to be common or atleast similar. In that case, you can create one single methods as below:
public JPanel createPanel(){
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBorder(BorderFactory.createMatteBorder(1,0,0,0,Color.GRAY));
panel.setBackground(new Color(70,70,70));
return pannel;
}
And add the additional steps in your designPanel() method e.g.:
public JPanel designPanel() {
//Sub container settings
designPanel = new JPanel( new GridLayout(12,2));
designPanel.setBounds(0,45,300,505);
designPanel.setBackground(new Color(80,80,80));
JPanel leftPanel = createPanel();
JPanel rightPanel = createPanel();
createBottomButtons(leftPanel, rightPanel);
designPanel.add(leftPanel );
designPanel.add(rightPanel);
return designPanel;
}
If you notice I removed the bottomButtons(); from createPanel(), added that in designPanel(). Also passed leftPanel and rightPanel as argument to this method.
I hope you can perform remaining restructuring yourself. Good luck!!

Java JFrame background color not working

I tried using:
frame1.getContentPane().setBackground(Color.yellow);
But it is not working. Can anyone help me?
import java.awt.*;
import java.awt.Color;
public class PlayGame {
public static void main(String[] args) {
GameFrame frame1 = new GameFrame();
frame1.getContentPane().setBackground(Color.yellow);
// Set Icon
Image icon = Toolkit.getDefaultToolkit().getImage("image/poker_icon.gif");
frame1.setIconImage(icon);
frame1.setVisible(true);
frame1.setSize(600, 700);
frame1.setTitle("Card Game");
// Set to exit on close
frame1.setDefaultCloseOperation(GameFrame.EXIT_ON_CLOSE);
}
}
GameFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GameFrame extends JFrame implements ActionListener {
private JPanel topPnl, btmPnl, pcPnl, mainPnl;
private JPanel titlePnl, playerPnl, computerPnl;
private JLabel titleLbl, playerLbl, computerLbl;
private JLabel testTextBox1, testTextBox2;
private ImageIcon playerIcon, computerIcon;
//
private JPanel pickCardPnl, pickCardTitlePnl, cardPnl, resultPnl, optionPnl;
private JLabel pickCardTitleLbl;
private JLabel card1Lbl, card2Lbl, card3Lbl, card4Lbl, card5Lbl;
private JLabel resultLbl;
private JButton restartBtn, showCardBtn, exitBtn;
private JButton card1Btn, card2Btn, card3Btn, card4Btn, card5Btn;
private ImageIcon card1Pic, card2Pic, card3Pic, card4Pic, card5Pic;
private JButton playerBtn, computerBtn;
private ImageIcon playerPic;
private String[] card = new String[53];
private String name;
// ArrayInt al;
public GameFrame() {
// a1 = new Array();
//a1.generateRandom();
setCard();
setName();
// Top Panel /////////////////////////////////////
mainPnl = new JPanel(new BorderLayout());
topPnl = new JPanel(new BorderLayout(50, 0));
titlePnl = new JPanel();
pcPnl = new JPanel(new GridLayout(1, 2, 10, 10));
playerPnl = new JPanel(new BorderLayout(10, 10));
computerPnl = new JPanel(new BorderLayout(10, 10));
// Title Panel
titleLbl = new JLabel("Card Game");
titlePnl.add(titleLbl);
// Player Panel
playerIcon = new ImageIcon("image/player.png");
playerLbl = new JLabel(name, playerIcon, JLabel.CENTER);
playerPnl.add(playerLbl, BorderLayout.NORTH);
playerPic = new ImageIcon("image/unknwon.png");
playerBtn = new JButton(playerPic);
playerPnl.add(playerBtn, BorderLayout.CENTER);
playerBtn.setContentAreaFilled(false);
playerBtn.setBorder(BorderFactory.createEmptyBorder());
// Computer Panel
computerIcon = new ImageIcon("image/computer.png");
computerLbl = new JLabel("Computer:", computerIcon, JLabel.CENTER);
computerPnl.add(computerLbl, BorderLayout.NORTH);
playerPic = new ImageIcon("image/back.png");
computerBtn = new JButton(playerPic);
computerPnl.add(computerBtn, BorderLayout.CENTER);
computerBtn.setContentAreaFilled(false);
computerBtn.setBorder(BorderFactory.createEmptyBorder());
pcPnl.add(playerPnl);
pcPnl.add(computerPnl);
// Add panel into Top Panel
topPnl.add(titlePnl, BorderLayout.NORTH);
topPnl.add(pcPnl, BorderLayout.CENTER);
// Bottom Panel /////////////////////////////////////
btmPnl = new JPanel(new BorderLayout());
pickCardPnl = new JPanel(new BorderLayout());
pickCardTitlePnl = new JPanel();
cardPnl = new JPanel(new GridLayout(1, 5, 5, 5));
resultPnl = new JPanel();
optionPnl = new JPanel(new GridLayout(1, 3, 5, 5));
// Pick Card Panel
pickCardTitleLbl = new JLabel("Pick Your Card:");
pickCardPnl.add(pickCardTitleLbl, BorderLayout.NORTH);
card1Pic = new ImageIcon(card[1]);
card1Btn = new JButton(card1Pic);
cardPnl.add(card1Btn);
card1Btn.addActionListener(this);
card2Pic = new ImageIcon(card[2]);
card2Btn = new JButton(card2Pic);
cardPnl.add(card2Btn);
card2Btn.addActionListener(this);
card3Pic = new ImageIcon(card[3]);
card3Btn = new JButton(card3Pic);
cardPnl.add(card3Btn);
card3Btn.addActionListener(this);
card4Pic = new ImageIcon(card[4]);
card4Btn = new JButton(card4Pic);
cardPnl.add(card4Btn);
card4Btn.addActionListener(this);
card5Pic = new ImageIcon(card[5]);
card5Btn = new JButton(card5Pic);
cardPnl.add(card5Btn);
card5Btn.addActionListener(this);
// new ImageIcon(a1.getRandomNumber);
pickCardPnl.add(cardPnl, BorderLayout.CENTER);
card1Btn.setContentAreaFilled(false);
card1Btn.setBorder(BorderFactory.createEmptyBorder());
card2Btn.setContentAreaFilled(false);
card2Btn.setBorder(BorderFactory.createEmptyBorder());
card3Btn.setContentAreaFilled(false);
card3Btn.setBorder(BorderFactory.createEmptyBorder());
card4Btn.setContentAreaFilled(false);
card4Btn.setBorder(BorderFactory.createEmptyBorder());
card5Btn.setContentAreaFilled(false);
card5Btn.setBorder(BorderFactory.createEmptyBorder());
// Result Panel
setCard();
resultLbl = new JLabel("adasdadadasdasdasdasd");
resultPnl.add(resultLbl);
// Option Panel
restartBtn = new JButton("Restart");
optionPnl.add(restartBtn);
restartBtn.addActionListener(this);
showCardBtn = new JButton("Show Cards");
optionPnl.add(showCardBtn);
showCardBtn.addActionListener(this);
exitBtn = new JButton("Exit");
optionPnl.add(exitBtn);
exitBtn.addActionListener(this);
// Add panel into Bottom Panel
btmPnl.add(pickCardPnl, BorderLayout.NORTH);
btmPnl.add(resultPnl, BorderLayout.CENTER);
btmPnl.add(optionPnl, BorderLayout.SOUTH);
//
mainPnl.add(topPnl, BorderLayout.NORTH);
// add(midPNL, BorderLayout.CENTER);
mainPnl.add(btmPnl, BorderLayout.CENTER);
add(mainPnl);
// Menu bar
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Game");
menuBar.add(menu);
JMenuItem item3 = new JMenuItem("Change Name");
item3.addActionListener(this);
menu.add(item3);
JMenuItem item = new JMenuItem("Change Card Deck");
item.addActionListener(this);
menu.add(item);
JMenu subMenu = new JMenu("Change BackGround");
subMenu.addActionListener(this);
menu.add(subMenu);
JMenuItem subItem = new JMenuItem("Blue");
subItem.addActionListener(this);
subMenu.add(subItem);
JMenuItem subItem2 = new JMenuItem("Green");
subItem2.addActionListener(this);
subMenu.add(subItem2);
//
menu.addSeparator();
//
JMenuItem item4 = new JMenuItem("Quit");
item4.addActionListener(this);
menu.add(item4);
setJMenuBar(menuBar);
} //End of GameFrame
public void setCard() {
GenRandom g1 = new GenRandom();
g1.GenRandomCard();
int[] allCard = new int[11];
allCard = g1.getAllCard();
for (int i = 1; i <= 10; i++) {
card[i] = "image/card/" + allCard[i] + ".png";
}
}
public void setName() {
// name = JOptionPane.showInputDialog(null, "Please Enter Your Name", "Welcome", JOptionPane.QUESTION_MESSAGE) + ":";
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == card1Btn) {
playerBtn.setIcon(card1Pic);
card1Btn.setEnabled(false);
}
if (e.getSource() == card2Btn) {
playerBtn.setIcon(card2Pic);
card2Btn.setEnabled(false);
}
if (e.getSource() == card3Btn) {
playerBtn.setIcon(card3Pic);
card3Btn.setEnabled(false);
}
if (e.getSource() == card4Btn) {
playerBtn.setIcon(card4Pic);
card4Btn.setEnabled(false);
}
if (e.getSource() == card5Btn) {
playerBtn.setIcon(card5Pic);
card5Btn.setEnabled(false);
}
if (e.getSource() == restartBtn) {
new AePlayWave("sound/jet.wav").start();
JOptionPane.showMessageDialog(null, "Restart Button ");
}
if (e.getSource() == exitBtn) {
/* long start = System.currentTimeMillis();
long end = start + 4 * 1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end) {
// run
new AePlayWave("sound/jet.wav").start();
}*/
System.exit(0);
}
}
}
Since you did not post an SSCCE, I will do it for you. This shows how to change the background color of a JFrame. Starting from this, you can start adding components to the JFrame and see where you go wrong, instead of letting us look at a few hundred lines of code.
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.EventQueue;
public class ColoredFrame {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );
frame.getContentPane().setBackground( Color.PINK );
//frame contains nothing, so set size
frame.setSize( 200, 200 );
frame.setVisible( true );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} );
}
}
Just put your setVisible(true); at the end of your constructor.
Moreover you had added mainPnl on your JFrame, so changing colour of the JFrame will be useless,
so instead of writing
add(mainPnl);
in your GameFrame class, you better be using
setContentPane(mainPnl);
for frame1.getContentPane().setBackground(Color.YELLOW); to work.
Hope this might help
Regards
You should give background color to JPanel and then use this JPanel in your JFrame rather than giving direct background to your JFrame.
I know this is a very old question, but for others that are looking for the right answer this could also be written as following:
frame1.getContentPane().setBackground(new Color (255,255,102)); //or whatever color you want in the RGB range

Categories