Beginner Scoring program button development in Java - java

I'm trying to add a "green team" to an example scoring GUI I found online. For some reason, the code compiles, but it runs with only the original two teams. I've tried playing around with the sizes/locations somewhat clumsily, and since no change was observed with these modications (NO change at ALL), I admit that I must be missing some necessary property or something. Any help? Here's the code:
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
totalGUI.add(titlePanel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
totalGUI.add(scorePanel);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended demo = new ButtonDemo_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

import javax.swing.*;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel, 0 );
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel, 1);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
totalGUI.add(buttonPanel);
totalGUI.add(scorePanel);
totalGUI.add(titlePanel);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended3 demo = new ButtonDemo_Extended3();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You have to use a layout manager in order to display your widgets. In this case I used a FlowLayout(). Also, make sure that you add the elements first in the panel and then you add the panel to its parent panel.
Now, the code works as you probably want, but again you should use a particular layout in order to arrange the panels inside the frame.

If I run your code unmodified, I see just the "Red Team" label, and some buttons which are too small to read the text (and some of them only appear when moused over).
If you comment out all the null layouts:
//buttonPanel.setLayout(null);
then all three buttons and labels appear properly.
Doing without a layout manager, and using absolute positioning, is possible (see the Java Swing tutorial page on this exact topic) but not usually recommended. There is a lot of information on using layout managers in the Laying Out Components Within a Container lesson of the Swing tutorials.

Related

How do I delete an image inside a JLabel by right clicking my mouse

I'm working on an Animal Project and I want to improve the project with the MouseListener functions, but I cannot find out how to do this specific bit and I've looked everywhere. Here is my code so you get a good idea at what I'm doing.
Main Class
public class Animals {
public static void main(String[] args) {
JFrame application = new JFrame("Animal Project");
GUI graphicalInterface = new GUI();
application.add(graphicalInterface);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setLocation(200, 200);
application.pack();
application.setVisible(true);
application.setResizable(false);
}
Sub Class
public class GUI extends JPanel implements ActionListener {
private JButton animalOption = new JButton();
private JButton save = new JButton();
private JButton load = new JButton();
private JButton clear = new JButton();
private JPanel buttonPanel;
private JPanel imagePanel;
private ImageIcon bear;
private ImageIcon tiger;
private ImageIcon lion;
private JLabel imageBlock1;
private JLabel imageBlock2;
private JLabel imageBlock3;
private int choice;
private int count = 1;
private JLabel currImageBlock = null;
GUI() {
Border blackline = BorderFactory.createLineBorder(Color.black);
//create button panel
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(100, 230));
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.white);
buttonPanel.setBorder(blackline);
imagePanel = new JPanel(new GridLayout(3, 3));
imagePanel.setPreferredSize(new Dimension(500, 500));
imagePanel.setOpaque(true);
imagePanel.setBackground(Color.white);
imagePanel.setBorder(blackline);
imageBlock1 = new JLabel();
imageBlock1.setPreferredSize(new Dimension(100, 100));
imageBlock1.setOpaque(true);
imageBlock1.setBackground(Color.white);
imageBlock1.setBorder(blackline);
imageBlock2 = new JLabel();
imageBlock2.setPreferredSize(new Dimension(100, 100));
imageBlock2.setOpaque(true);
imageBlock2.setBackground(Color.white);
imageBlock2.setBorder(blackline);
imageBlock3 = new JLabel();
imageBlock3.setPreferredSize(new Dimension(100, 100));
imageBlock3.setOpaque(true);
imageBlock3.setBackground(Color.white);
imageBlock3.setBorder(blackline);
bear = new ImageIcon("Bear.png");
tiger = new ImageIcon("Tiger.png");
lion = new ImageIcon("Lion.png");
animalOption = new JButton();
//add action listener to each button
animalOption.addActionListener(this);
//set button size
animalOption.setPreferredSize(new Dimension(100, 50));
//set text for each button
animalOption.setText("Animal");
animalOption.setToolTipText("press to select your animal");
//add buttons to gui
buttonPanel.add(animalOption);
save = new JButton();
//add action listener to each button
save.addActionListener(this);
//set button size
save.setPreferredSize(new Dimension(100, 50));
//set text for each button
save.setText("Save");
save.setToolTipText("press to save your selection");
//add buttons to gui
buttonPanel.add(save);
load = new JButton();
//add action listener to each button
load.addActionListener(this);
//set button size
load.setPreferredSize(new Dimension(100, 50));
//set text for each button
load.setText("Load");
load.setToolTipText("press to load your selection");
//add buttons to gui
buttonPanel.add(load);
clear = new JButton();
//add action listener to each button
clear.addActionListener(this);
//set button size
clear.setPreferredSize(new Dimension(100, 50));
//set text for each button
clear.setText("Clear");
clear.setToolTipText("press to clear your selection");
//add buttons to gui
buttonPanel.add(clear);
this.add(buttonPanel);
this.add(imagePanel);
imagePanel.add(imageBlock1);
imagePanel.add(imageBlock2);
imagePanel.add(imageBlock3);
}
public void actionPerformed(ActionEvent e) {
if (count == 1) {
currImageBlock = imageBlock1;
} else if (count == 2) {
currImageBlock = imageBlock2;
} else if (count == 3) {
currImageBlock = imageBlock3;
} else if (count > 3 && e.getSource().equals(animalOption)) {
JOptionPane.showMessageDialog(imagePanel, "Your choices have exceeded, please press clear.");
}
if (e.getSource().equals(animalOption) && count < 4) {
choice = selectAnimal();
if (choice == 1) {
currImageBlock.setIcon(bear);
currImageBlock.setToolTipText("This is a bear");
} else if (choice == 2) {
currImageBlock.setIcon(tiger);
currImageBlock.setToolTipText("This is a tiger");
} else if (choice == 3) {
currImageBlock.setIcon(lion);
currImageBlock.setToolTipText("This is a lion");
}
chooseNumber();
count++;
}
if (e.getSource().equals(clear)) {
imageBlock1.setIcon(null);
imageBlock2.setIcon(null);
imageBlock3.setIcon(null);
imageBlock1.revalidate();
imageBlock2.revalidate();
imageBlock3.revalidate();
count = 1;
}
}
static int selectAnimal() {
int animal = 0;
String theAnimal = JOptionPane.showInputDialog("Please enter animal, type 1 for bear, type 2 for tiger, type 3 for lion");
animal = Integer.parseInt(theAnimal);
return animal;
}
And this is what it looks like when I run the code and after I've selected which Animal I want
I have a clear all button where if I click it, it clears all the images in inside the imageBlock Jlabel, however I want to add a feature where if I right click on the specific JLabel the image and all its contents will be deleted inside that specific JLabel. Any help would really be appreciated.
This example code shows how a mouse listener can be used to perform an action (in this case - remove) on an image set as icon within a JLabel. Note a MouseAdapter is used in the code but a MouseListener interface can be implemented with similar result.
Other ways of performing this function:
Select an image label and click a button to remove it.
Open a context or pop-up menu with remove image menu option - when the image label is right-clicked upon.
The example code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ImageLabelAction {
private JLabel imageBlock;
private ImageIcon koala = new ImageIcon("koala.jpg");
public static void main(String [] args) {
new ImageLabelAction().gui();
}
private void gui() {
JFrame frame = new JFrame();
frame.setTitle("Frame with Image Label");
imageBlock = new JLabel();
imageBlock.setPreferredSize(new Dimension(100, 100));
imageBlock.setOpaque(true);
imageBlock.setBackground(Color.white);
imageBlock.setBorder(BorderFactory.createLineBorder(Color.black));
imageBlock.setIcon(koala);
imageBlock.addMouseListener(new PictureRemoveListener());
frame.add(imageBlock);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(250, 250);
frame.setVisible(true);
}
private class PictureRemoveListener extends MouseAdapter {
#Override public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
imageBlock.setIcon(null);
}
}
}
}
You could set a mouse listener to just move it way out of the frame when right clicked. Or you can make a boolean if mouse is clicked set true and only show that object if the boolean is true, so where you set the image from the file only run that code if right mouse button hasn't been clicked
Something like the following pseudo code:
imageBlock1.addMouseListener(new MouseAdapter() {
public void mouseClicked (MouseEvent e) {
// use flags to figure out if it is right mouse click
imageBlock1.setIcon(null);
}
});
Do this for imageBlock2, 3, 4 etc.
It has been a while but something along those lines could do what you are asking.

Button placement and location not working

I recently tried out an online tutorial of Swing and Java GUI's and I decided to replicate the tutorial code but add in a third button. I tried to add in a red one, and I successfully did (it doesn't do anything yet), but i'm having some coordinate issues. Whenever I try to run it, something like this comes up:
All I really need help with is with coordinates or the size of the frames. I really don't know where to go from here. I'm sure this is a relatively simple question but, thanks!
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Test1 implements ActionListener
{
// Definition of global values and items that are part of the GUI.
int blackScoreAmount = 0;
int greenScoreAmount = 0;
int redScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel blackLabel, greenLabel, redLabel, blackScore, greenScore, redScore;
JButton blackButton, greenButton, redButton, resetButton;
public JPanel createContentPane ()
{
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(10, 0);
titlePanel.setSize(180, 30);
totalGUI.add(titlePanel);
blackLabel = new JLabel("Black Team");
blackLabel.setLocation(0, 0);
blackLabel.setSize(120, 30);
blackLabel.setHorizontalAlignment(0);
blackLabel.setForeground(Color.black);
titlePanel.add(blackLabel);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(130, 0);
greenLabel.setSize(120, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(250, 0);
redLabel.setSize(120, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(180, 30);
totalGUI.add(scorePanel);
blackScore = new JLabel(""+blackScoreAmount);
blackScore.setLocation(0, 0);
blackScore.setSize(120, 30);
blackScore.setHorizontalAlignment(0);
scorePanel.add(blackScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(130, 0);
greenScore.setSize(120, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(250, 0);
redScore.setSize(120, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(380, 80);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
blackButton = new JButton("Black Score");
blackButton.setLocation(0, 0);
blackButton.setSize(120, 30);
blackButton.addActionListener(this);
buttonPanel.add(blackButton);
greenButton = new JButton("Green Score");
greenButton.setLocation(130, 0);
greenButton.setSize(120, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
redButton = new JButton("Red Score");
redButton.setLocation(250, 0);
redButton.setSize(120, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 40);
resetButton.setSize(250, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == blackButton)
{
blackScoreAmount = blackScoreAmount + 1;
blackScore.setText(""+blackScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
blackScoreAmount = 0;
greenScoreAmount = 0;
blackScore.setText(""+blackScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Black and Green");
//Create and set up the content pane.
Test1 demo = new Test1();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 190);
frame.setVisible(true);
}
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Your frame is 280x190:
frame.setSize(280, 190);
and you try to place a red button with an x origin of 250 and a width size of 120 -> 370. Just adjust the window frame size accordingly if you add new elements.
And for that kind of task it may be better (at least simpler) to use layouts.
The size of your window is "hardcoded" :
frame.setSize(280, 190);
and so are the size and positions of your buttons:
redButton.setLocation(250, 0);
redButton.setSize(120, 30);
Your putting a button with a Width of 120 at the position 250 of a frame that is 280 large so only 25% of you button can be visible.
You have to adapt the size of your frame and the position of your buttons to get it to be fully visible and pretty..
EDIT
Now, has suggested by many other repliers, if you want to improve your application, try getting rid of all the hard-coded values and use Layout Managers instead.
Here are some good explanations about them :
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

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

Add components to JDialog

When I run this, an empty title bar is displayed. I just want to be able to see the components and work from there, but nothing is displayed. The dialog is designed to allow the user to select a color by moving sliders, then return to color to the main page.
import java.awt.*;
import javax.swing.*;
public class ColourDialog extends JDialog
{
String colorNames[] = {"Red: ", "Green: ", "Blue: "};
Label labels[] = new Label[3];
JSlider slider[]= new JSlider[3];
Label lb;
static ColourDialog d;
public void ColourDialog()
{
setModal(true);
Container c = getContentPane();
c.setLayout(new BorderLayout());
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++)
{
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
//slider[i].addChangeListener(this);
}
lb = new Label("Colour");
c.add(sliderPanel, BorderLayout.CENTER);
c.add(lb, BorderLayout.SOUTH);
setSize(500, 450);
setLocation(200,200);
setTitle("Colour Dialog");
}
public static Color showDialog()
{
if (d == null)
d = new ColourDialog();
d.show();
//return new Color(red,green,blue);
return new Color(0,0,0);
}
public static void main(String args[])
{
ColourDialog.showDialog();
}
}
I think that you have look at JColorChooser, this JComponent can returns selected Color
there I can't fout out correct definitions and initializations for JSlider
EDIT
there are lots of mistakes starting with extends JDialog end with public static Color showDialog(), that returns empty container typos with initializations for ColourDialog()
import java.awt.*;
import javax.swing.*;
public class ColourDialog {
private JDialog dialog = new JDialog();
private String colorNames[] = {"Red: ", "Green: ", "Blue: "};
private Label labels[] = new Label[3];
private JSlider slider[] = new JSlider[3];
private Label lb;
public ColourDialog() {
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++) {
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
}
lb = new Label("Colour");
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setModal(true);
dialog.add(sliderPanel, BorderLayout.CENTER);
dialog.add(lb, BorderLayout.SOUTH);
dialog.pack();
dialog.setLocation(200, 200);
dialog.setTitle("Colour Dialog");
dialog.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ColourDialog colourDialog = new ColourDialog();
}
});
}
}
I think it might be because you say "public void ColourDialog()" this is an invalid constructor. Try getting rid of the "void" and try again.
You never call the method ColorDialog(). This is a good spot to mention "start methods with a lower case letter). To fix you code:
Change:
d = new ColourDialog();
To:
d = new ColourDialog();
d.ColourDialog();

JRadioButton Will not appear until Mouse over

import java.awt.Frame;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class IndicatorWindow implements ItemListener {
JRadioButton RMA, EMA, SMA, Williams, Stochastic;
JPanel IndPan, RadioPanel, title;
JLabel Lab;
JButton OK;
public JPanel createContentPane() {
JPanel GUI = new JPanel();
GUI.setLayout(null);
title = new JPanel();
title.setLayout(null);
title.setLocation(0, 0);
title.setSize(500, 145);
GUI.add(title);
Lab = new JLabel("Please Select Indicator Type");
Lab.setLocation(5, 0);
Lab.setSize(200, 30);
title.add(Lab);
ButtonGroup bg1 = new ButtonGroup();
RadioPanel = new JPanel();
RadioPanel.setLayout(null);
RadioPanel.setLocation(10, 30);
RadioPanel.setSize(190, 220);
GUI.add(RadioPanel);
RMA = new JRadioButton("RMA");
RMA.setLocation(0, 0);
RMA.addItemListener(this);
RMA.setSize(110, 20);
bg1.add(RMA);
RadioPanel.add(RMA);
EMA = new JRadioButton("EMA");
EMA.setLocation(0, 30);
EMA.addItemListener(this);
EMA.setSize(110, 20);
bg1.add(EMA);
RadioPanel.add(EMA);
SMA = new JRadioButton("SMA");
SMA.setLocation(0, 60);
SMA.addItemListener(this);
SMA.setSize(110, 20);
bg1.add(SMA);
RadioPanel.add(SMA);
Stochastic = new JRadioButton("Stochastic");
Stochastic.setLocation(0, 90);
Stochastic.addItemListener(this);
Stochastic.setSize(110, 20);
bg1.add(Stochastic);
RadioPanel.add(Stochastic);
Williams = new JRadioButton("Williams");
Williams.setLocation(0, 120);
Williams.addItemListener(this);
Williams.setSize(110, 20);
bg1.add(Williams);
RadioPanel.add(Williams);
OK = new JButton();
OK.setText("Confirm");
OK.setLocation(45, 150);
OK.addItemListener(this);
OK.setSize(90, 30);
RadioPanel.add(OK);
//GUI.setOpaque(true);
return GUI;
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == RMA) {
System.out.print("Browse");
} else if (source == EMA) {
System.out.print("EMA");
} else if (source == SMA) {
System.out.print("SMA");
} else if (source == Williams) {
System.out.print("Williams");
} else if (source == Stochastic) {
System.out.print("Stochastic");
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
IndicatorWindow ind = new IndicatorWindow();
frame.setContentPane(ind.createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(200, 250);
frame.setLayout(null);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setState(Frame.NORMAL);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
My problem is that when i compile and run this code, the jFrame appears but there is only one problem, 3 JRadioButtons dont appear until you put your mouse over them. The RMA and Williams radiobuttons appear, the 3 in the middle do not though, any thoughts on why this is?
http://i.stack.imgur.com/gNnIb.jpg
You should be using layout managers. People think using a "null layout" is easier, but it is not and you are more prone to having errors with your code. Layout managers will position and size components properly to make sure all components are displayed. Sometimes you even use multiple different layout managers to achieve the layout you desire.
Your problem in this case is that you have two components occupying the same space in your container. So one component gets painted over top of the other. After you mouse over your radio button, the button is repainted because of the rollover effect of the button. However, now try resizing the frame and the radio buttons will disappear because all the components are repainted and the component is painted over top of the buttons again.
The following line of code is the problem:
// title.setSize(500, 145);
title.setSize(500, 20);
But the real solution is to rewrite the code and use layout managers. While you are at it use proper Java naming conventions. Variable names do NOT start with an uppercase letter. You got "title" and "bg1" correct. So fix "EMA", "RMA" etc...
#camickr is correct. Note how using layout managers (and a little re-factoring) can actually simplify your code. Also, the relevant tutorial suggests using an action listener, rather than an item listener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/5255337 */
public class IndicatorWindow implements ActionListener {
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
JRadioButton rma, ema, sma, stochastic, williams;
ButtonGroup bg = new ButtonGroup();
public JPanel createContentPane() {
JPanel gui = new JPanel(new BorderLayout());
JPanel title = new JPanel();
JLabel lab = new JLabel("Please Select Indicator Type");
title.add(lab);
gui.add(title, BorderLayout.NORTH);
createRadioButton(rma, "RMA");
createRadioButton(ema, "EMA");
createRadioButton(sma, "SMA");
createRadioButton(stochastic, "Stochastic");
createRadioButton(williams, "Williams");
gui.add(radioPanel, BorderLayout.CENTER);
JButton ok = new JButton();
ok.setText("Confirm");
ok.addActionListener(this);
radioPanel.add(ok);
return gui;
}
private void createRadioButton(JRadioButton jrb, String name) {
jrb = new JRadioButton(name);
bg.add(jrb);
jrb.addActionListener(this);
radioPanel.add(jrb);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
frame.add(new IndicatorWindow().createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setAlwaysOnTop(true);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You should add your JRadioButtons with a method:
private void bgAdd (String name, int y)
{
JRadioButton rb = new JRadioButton (name);
rb.setLocation (0, y);
rb.addItemListener (this);
rb.setSize (110, 19);
bg1.add (rb);
radioPanel.add (rb);
}
Calling code:
bgAdd ("RMA", 0);
bgAdd ("EMA", 30);
bgAdd ("SMA", 60);
bgAdd ("Stochastic", 90);
bgAdd ("Williams", 120);
Action:
public void itemStateChanged (ItemEvent e) {
Object button = e.getItemSelectable ();
String source = ((JRadioButton) button).getText ();
System.out.print (source + " ");
}
Then add BoxLayout to the page, for example.

Categories