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
Related
I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Firstly capitalize the name of your class always in Java, then check this code :
public class Sim extends JPanel {
public Sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/1.png");
Icon c = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/2.png");
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
final JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
button.addActionListener(new HandlerClass(label));
}
private class HandlerClass implements ActionListener{
final JLabel label;
public HandlerClass(JLabel label){
this.label = label;
}
public void actionPerformed(ActionEvent e)
{
label.setText("SSSSSSSSSSSSSsssss");
JOptionPane.showMessageDialog(null, "Something");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new Sim());
frame.setVisible(true);
}
}
I'm making a simple text editor in Java and for some reason my find and replace actions won't work, i made two separate frames, one for the find action, and the other to open up another frame with 2 jtextfields for find and replace. i have in my actionperformed
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
and in my findFrame i have the action that should be carried out when the user clicks on the JMenuItem called "Find".
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
In my Replace frame where i want the user to find a word and replace it, anything you type into the find textfield and click the find button, it finds the first 3 characters on the text field, and the replace action just doesn't work at all,
here is my replace frame
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
the find and replace are two separate JMenuItems, when the user clicks on Find it opens up findframe and when they click on "replace" it opens up the replace frame which has a find textfield and a replace textfield.
here is the whole runnable code :
//Programmer Aly Badran – Project 10
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.DefaultEditorKit.CutAction;
class saveFrame extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel labelpanel = new JPanel();
JButton savebutton = new JButton("Save");
JButton dontsave = new JButton("Dont Save");
JLabel savelabel = new JLabel("Are you sure you want to close"?);
public saveFrame(){
setSize(400,100);
setLocation(500, 300);
setTitle("Saving...");
labelpanel.add(savelabel);
panel.add(savebutton);
panel.add(dontsave);
Container cpane = getContentPane();
cpane.add(panel, "South");
cpane.add(labelpanel, "Center");
setVisible(true);
savebutton.addActionListener(this);
dontsave.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if(source == savebutton){
System.exit(0);
}
else if(source == dontsave){
System.exit(0);
}
}
}
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
class MenuFrame extends JFrame implements ActionListener, MouseListener{
static JTextArea textarea = new JTextArea();
static JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenuItem copy = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cut = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem Paste = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenuItem copyAction = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cutAction = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem pasteAction = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenu search = new JMenu("Search");
JMenuItem open = new JMenuItem("Open");
JMenuItem close = new JMenuItem("Close");
JMenuItem quit = new JMenuItem("Quit");
JMenuItem find = new JMenuItem("Find");
JMenuItem replace = new JMenuItem("Replace");
JMenu font = new JMenu("Font");
JCheckBoxMenuItem bold = new JCheckBoxMenuItem("Bold");
JCheckBoxMenuItem italic = new JCheckBoxMenuItem("Italic");
JPopupMenu popup;
public MenuFrame(){
Container cpane = getContentPane();
cpane.add(textarea);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenheight = d.height;
int screenwidth = d.width;
setSize(screenwidth, screenheight);
JPanel panel = new JPanel();
ImageIcon closeicon = new ImageIcon("bin/close.png");
ImageIcon openicon = new ImageIcon("bin/open.png");
ImageIcon quiticon = new ImageIcon("bin/quit.jpeg");
ImageIcon findicon = new ImageIcon("bin/find.png");
ImageIcon replaceicon = new ImageIcon("bin/replace.png");
ImageIcon boldicon = new ImageIcon("bin/bold.png");
ImageIcon italicicon = new ImageIcon("bin/italic.png");
ImageIcon copyicon = new ImageIcon("bin/copy.png");
ImageIcon cuticon = new ImageIcon("bin/cut.png");
ImageIcon pasteicon = new ImageIcon("bin/paste.png");
Border matte = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK);
Border etched = BorderFactory.createEtchedBorder();
popup = new JPopupMenu();
copy.setText("Copy");
cut.setText("Cut");
Paste.setText("Paste");
copy.setIcon(copyicon);
cut.setIcon(cuticon);
Paste.setIcon(pasteicon);
copyAction.setText("Copy");
cutAction.setText("Cut");
pasteAction.setText("Paste");
copyAction.setIcon(copyicon);
cutAction.setIcon(cuticon);
pasteAction.setIcon(pasteicon);
popup.add(cut);
popup.addSeparator();
popup.add(copy);
popup.addSeparator();
popup.add(Paste);
popup.addSeparator();
popup.add(find);
popup.addSeparator();
popup.add(replace);
edit.add(cutAction);
edit.addSeparator();
edit.add(copyAction);
edit.addSeparator();
edit.add(pasteAction);
find.setIcon(findicon);
replace.setIcon(replaceicon);
close.setIcon(closeicon);
menubar = new JMenuBar();
textarea = new JTextArea("He has achieved success.", d.width, d.height);
JScrollPane scroll = new JScrollPane(textarea);
cpane.add(scroll);
open = new JMenuItem("Open", openicon);
close = new JMenuItem("Close", closeicon);
quit = new JMenuItem("Quit", quiticon);
find = new JMenuItem("Find", findicon);
replace = new JMenuItem("Replace", replaceicon);
bold = new JCheckBoxMenuItem("Bold", boldicon);
italic = new JCheckBoxMenuItem("Italic", italicicon);
textarea.setLineWrap(true);
file.add(open);
file.addSeparator();
file.add(close);
file.addSeparator();
file.add(quit);
menubar.add(file);
menubar.add(edit);
menubar.add(search);
menubar.add(font);
search.add(find);
search.addSeparator();
search.add(replace);
font.add(bold);
font.addSeparator();
font.add(italic);
copy.setEnabled(false);
cut.setEnabled(false);
Paste.setEnabled(false);
find.addActionListener(this);
italic.addActionListener(this);
bold.addActionListener(this);
quit.addActionListener(this);
close.addActionListener(this);
find.addActionListener(this);
replace.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
Paste.addActionListener(this);
cut.addMouseListener(this);
textarea.addMouseListener(this);
copy.addMouseListener(this);
Paste.addMouseListener(this);
textarea.setComponentPopupMenu(popup);
file.setBackground(Color.BLACK);
edit.setBackground(Color.BLACK);
search.setBackground(Color.BLACK);
font.setBackground(Color.BLACK);
panel.add(menubar);
menubar.setBorder(matte);
menubar.setBackground(Color.BLACK);
textarea.setBorder(etched);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
String command = evt.getActionCommand();
String s = textarea.getSelectedText();
Font f = new Font("Italic", Font.ITALIC, 13);
Font f2 = new Font("Bold", Font.BOLD, 13);
if(italic.isSelected()){
textarea.setFont(f);
}
if(bold.isSelected()){
textarea.setFont(f2);
}
if(bold.isSelected() && italic.isSelected()){
textarea.setFont(f);
textarea.setFont(f2);
}
if(command.equals("Quit"))
System.exit(0);
if(command.equals("Close")){
JFrame frame = new saveFrame();
frame.setVisible(true);
}
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
if(command.equals("Replace")){
JFrame frame2 = new replaceFrame();
frame2.setVisible(true);
}
}
public void mouseClicked(MouseEvent e) {
boolean s = textarea.getSelectedText() != null;
if(s){
copy.setEnabled(true);
cut.setEnabled(true);
Paste.setEnabled(true);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
}
public class Menus {
public static void main(String [] args){
JFrame frame = new MenuFrame();
frame.setJMenuBar(MenuFrame.menubar);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Your basic problem comes down to the fact that the "selection" highlight won't be painted while the JTextArea doesn't have focus, I know, awesome.
However, you could use a Highlighter instead, for example...
if (source == find) {
try {
DefaultHighlighter.DefaultHighlightPainter highlighter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor("TextArea.selectionBackground"));
MenuFrame.textarea.getHighlighter().addHighlight(n, n + search.length(), highlighter);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
Which will paint a "highlight" over the specified area.
You may want to have a look at this for away to remove it
This and this may also be of interest
In your replace method, you are using the text of the find JButton instead of the findtext JTextField
//String search = find.getText();
String search = findtext.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
Your codes also a mess (sorry, took me a while to navigate it).
For example, you're adding a ActionListener twice to the find menu item and probably some others, which caused to find windows to appear.
I'd avoid using Toolkit#getScreenSize(); in connection with JFrame#setSize, a better solution would be to use JFrame#setExtendedState and pass it JFrame#MAXIMIZED_BOTH, as this will also take into consideration the other UI assets that the OS may have fixed on the screen (like docks and task bars).
You really should be using dialogs instead of JFrames for your "short term input" mechanisms
Your also recreating a bunch of stuff you've already created, for example...
static JTextArea textarea = new JTextArea();
//...
textarea = new JTextArea("He has achieved success.", d.width, d.height);
What's worse, is you add the original instance of the textarea to the frame BEFORE you create the new one, which runs the risk of not knowing which component you are actually dealing with...which is just compounded by the fact that you're using a static reference to it so other classes can access it, which they shouldn't be allowed to do...
In replaceFrame, you are taking text to search from the find field (button), but you should take it from findtext (you are always searching for text "Find").
This is one of the reasons why code duplication is bad - you should extract the finding logic to one place and reuse it in both classes.
The first column in my grid always comes out right but then the rest begin replacing the other cells. Also the border layout does not seem to be functioning. I do not know what the problem is. It should have the title on top, a 7x3 grid in the center and the buttons on the bottom. Please help! Thank you!
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame{
private JPanel mainPanel,titlePanel, fieldPanel, buttonPanel;
private JLabel title, teams, totalP, wlt;
private JTextField team1, team2, team3, team4, team5, team6, total1, total2, total3, total4, total5, total6, wlt1, wlt2, wlt3, wlt4, wlt5, wlt6;
private JButton read, calc, champWin, earthCW, exit;
final private int WINDOW_HEIGHT = 400;
final private int WINDOW_WIDTH = 900;
public GUI(){
buildtitlePanel();
buildfieldPanel();
buildbuttonPanel();
buildmainPanel();
setTitle("Desert Soccer League");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buildmainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void buildtitlePanel() {
titlePanel = new JPanel();
title = new JLabel();
title.setText("2014 Desert Soccer League Totals");
titlePanel.add(title);
}
private void buildfieldPanel() {
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(7, 3));
teams = new JLabel();
teams.setText("Teams");
totalP = new JLabel();
totalP.setText("Total Points");
wlt = new JLabel();
wlt.setText("Win-Loss-Tie");
team1 = new JTextField(10);
team2 = new JTextField(10);
team3 = new JTextField(10);
team4 = new JTextField(10);
team5 = new JTextField(10);
team6 = new JTextField(10);
total1 = new JTextField(10);
total2 = new JTextField(10);
total3 = new JTextField(10);
total4 = new JTextField(10);
total5 = new JTextField(10);
total6 = new JTextField(10);
wlt1 = new JTextField(10);
wlt2 = new JTextField(10);
wlt3 = new JTextField(10);
wlt4 = new JTextField(10);
wlt5 = new JTextField(10);
wlt6 = new JTextField(10);
team1.setEditable(false);
team2.setEditable(false);
team3.setEditable(false);
team4.setEditable(false);
team5.setEditable(false);
team6.setEditable(false);
total1.setEditable(false);
total2.setEditable(false);
total3.setEditable(false);
total4.setEditable(false);
total5.setEditable(false);
total6.setEditable(false);
wlt1.setEditable(false);
wlt2.setEditable(false);
wlt3.setEditable(false);
wlt4.setEditable(false);
wlt5.setEditable(false);
wlt6.setEditable(false);
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
fieldPanel.add(totalP);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
fieldPanel.add(wlt);
fieldPanel.add(wlt1);
fieldPanel.add(wlt2);
fieldPanel.add(wlt3);
fieldPanel.add(wlt4);
fieldPanel.add(wlt5);
fieldPanel.add(wlt6);
}
private void buildbuttonPanel() {
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 5));
read = new JButton();
calc = new JButton();
champWin = new JButton();
earthCW = new JButton();
exit = new JButton();
read.setText("Read Input File");
read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
calc.setText("Calculate Points");
calc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
champWin.setText("Championship Winner");
champWin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
earthCW.setText("Earth Cup Winner");
earthCW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exit.setText("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
buttonPanel.add(read);
buttonPanel.add(calc);
buttonPanel.add(champWin);
buttonPanel.add(earthCW);
buttonPanel.add(exit);
}
}
mainPanel = new JPanel();
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
By default a JPanel uses a FlowLayout. If you want to use a BorderLayout, then you need to set the layout on the panel:
mainPanel = new JPanel( new BorderLayout() );
The GridLayout fills out the rows first so the code should be:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
...
Also note that in your code you are adding the total? fields twice (which won't do anything), instead of the team? fields.
Another way to specify the grid is to just use:
fieldPanel.setLayout(new GridLayout(0, 3));
This tells the grid to add 3 components to each row then move on to the next row. This way you don't have to worry about the exact number of rows.
To add to camickr answer you're also adding the same total fields multiple times, so change this:
fieldPanel.add(teams);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
to
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
This is what is causing your display issue.
Your code should look like:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
fieldPanel.add(team2);
fieldPanel.add(total2);
fieldPanel.add(wlt2);
// etc.
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.
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!!