Button placement and location not working - java

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

Related

How to make a JPanel that work like JOptionPane?

I'm making a simple POS system on NetBeans that would pop out a JPanel (quantity) asking for the quantity when the photo of the product is clicked. I am using a card layout and putting the panel inside the card layout doesn't seem to work as it is different in size. It's also very hard to position it since moving it makes a bigger panel (buy) absorb it and becomes a part of the panel, messing up the layout of that panel. I want to make the panel initially invisible and pop up only with this code:
public void mouseClicked(MouseEvent e) {
if (e.getSource() == bpie )
{
String name = "Banoffee Pie";
int price = 8;
quantity.setVisible(true);
}
}
I'm currently a beginner and have a hard time customizing JOptionPane dialogs and prefer the use of panels if possible. The problem could be solved with the use of another JFrame, however, the use of multiple frames according to experts, is bad practice.
Here is how I want the option pane to look:
I'm currently a beginner and have a hard time customizing JOptionPanes
The JOptionPane was made for utility rather than customizability. As soon as you start thinking 'How can I change a JOptionPane to..?' abandon the option pane and instead use a modal JDialog.
Here is an example of using a dialog. I've tweaked the layout along these lines:
The food icons centered below the title bar.
Abandoned the simpler button names for more descriptive ones.
Adding the question and answer in the same line with a spinner to choose the number.
Of course, colors need to be adjusted to suit the style seen above, which might (and might not - depending on further factors not immediately evident) best be approached by using a custom Pluggable Look and Feel.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
public class SweetShop {
private JComponent ui = null;
private static JFrame frame = new JFrame("Sweet Shop");
private final JDialog dialog = new JDialog(frame, "Choose Sweets", true);
Random random = new Random();
SpinnerNumberModel quantityModel = new SpinnerNumberModel(1, 1, 144, 1);
SweetShop() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(40,100,40,100));
JButton button = new JButton("Buy Sweets");
ui.add(button);
ActionListener openChooserListener = (ActionEvent e) -> {
dialog.setLocationRelativeTo(button);
dialog.setVisible(true);
};
button.addActionListener(openChooserListener);
dialog.add(getSweetSelectionPanel());
dialog.pack();
}
private JPanel getSweetSelectionPanel() {
JPanel panel = new JPanel(new BorderLayout());
int pad = 10;
panel.setBorder(new EmptyBorder(pad, pad, pad, pad));
JPanel iconPanel = new JPanel();
for (int ii=0; ii<12; ii++) {
iconPanel.add(new JLabel(new ImageIcon(getSize16Image())));
}
panel.add(iconPanel, BorderLayout.PAGE_START);
JPanel buttonPanel = new JPanel();
JButton okButton = new JButton("Buy Delicious");
buttonPanel.add(okButton);
ActionListener okListener = (ActionEvent e) -> {
System.out.println("Yuuuummmmm.. x " +
quantityModel.getNumber().intValue());
dialog.setVisible(false);
};
okButton.addActionListener(okListener);
JButton cancelButton = new JButton("No Thanks");
buttonPanel.add(cancelButton);
ActionListener cancelListener = (ActionEvent e) -> {
System.out.println("I just like licking them.");
dialog.setVisible(false);
};
cancelButton.addActionListener(cancelListener);
panel.add(buttonPanel, BorderLayout.PAGE_END);
JPanel questionPanel = new JPanel();
questionPanel.setBorder(new EmptyBorder(20, 50, 20, 50));
panel.add(questionPanel); // automatically uses CENTER constraint
JLabel label = new JLabel("How many do you wish to buy?");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.ITALIC));
label.setText("How many do you wish to buy?");
label.setBorder(new EmptyBorder(5, 5, 5, 5));
questionPanel.add(label);
JSpinner spinner = new JSpinner(quantityModel);
questionPanel.add(spinner);
return panel;
}
private Image getSize16Image() {
int w = 16;
int h = 16;
if (random.nextBoolean()) {
w = random.nextInt(12) + 4;
} else {
h = random.nextInt(12) + 4;
}
BufferedImage bi = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
return bi;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
SweetShop o = new SweetShop();
frame = new JFrame(o.getClass().getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setContentPane(o.getUI());
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}

Assistance With KeyEvent

I am making a platformer game for a class project and so far all I have been able to do is add the chicken character to the game. I need to be able to have him move forward on the press of "D" or right arrow. My code is:
public class Main extends JFrame {
public Main(){
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
setSize(1440, 500);
add(new ContentPanel1());
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String arg[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
class coordinate {
public static int x;
public static int y;
}
class ContentPanel1 extends JPanel{
Image back = Toolkit.getDefaultToolkit().getImage("level0.gif");
Image chick = Toolkit.getDefaultToolkit().getImage("chicken.gif");
ContentPanel1() {
MediaTracker mt = new MediaTracker(this);
mt.addImage(back, 0);
try {
mt.waitForAll();
} catch (InterruptedException e){
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
coordinate.x = 20;
coordinate.y = 321;
super.paintComponent(g);
int imwidth = back.getWidth(null);
int imheight = back.getHeight(null);
g.drawImage(back, 1, 1, null);
g.drawImage(chick, coordinate.x, coordinate.y, null);
}
public void MoveDirection(KeyEvent e, Graphics g) {
coordinate.x = 20;
coordinate.y = 321;
super.paintComponent(g);
int key = e.getKeyCode();
if(key == 68) {
coordinate.x += 1;
g.drawImage(chick, coordinate.x, coordinate.y, null);
}
}
}
The main trouble I have been having with my code is the bit at the end with the MoveDirection method. The way I have it going is by adding a new chicken to the frame (This was mainly due to the fact that I was just testing to see if the code worked). Is there a better way to do that too?
Start by taking a look at How to Use Key Bindings
NEVER call super.paintComponent(g); (or paintComponent(g);) directly from outside the context of the paintComponent method, there is a lot more to painting then just painting the component background. See Painting in AWT and Swing and Performing Custom Painting for more details. Instead, simply call repaint when you want to, well, repaint the component.
The use of MediaTracker is out of date and you should be using the ImageIO API instead, which will block automatically while reading the image. See Reading/Loading an Image for more details
Don't use Toolkit.getDefaultToolkit().getScreenSize() in combination with JFrame#setSize, the getScreenSize method does not take into account things like the task bar or dock of some OS's, instead use the JFrame#setExtendedState and pass it JFrame.MAXIMIZED_BOTH
frame.setLocale(null); isn't doing what you think it is

What Layout Should I Use for This Project (Java)

I am making a platformer game for a project for class and need to have a chicken character jump on some platforms. I have a start screen and a button, and when the button is clicked, it will change the frame to the first level. When I add the chicken character to the frame as well as the background image, all I can see is the background image. Should I be using a different layout or is there something else I can do. This is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Main extends JFrame {
public Main(){
//Creates Chicken Character
final JLabel chicken = new JLabel(" ");
ImageIcon chick1 = new ImageIcon("chicken.gif");
ImageIcon chick2 = new ImageIcon("chicken2.gif");
chicken.setIcon(chick1);
//Sets Chicken Location
chicken.setLocation(1, 1);
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Creates label for level 0 background image
JLabel background = new JLabel(" ");
ImageIcon back = new ImageIcon("level0.gif");
background.setIcon(back);
//Creates a panel for level 0
final JPanel p5 = new JPanel();
chicken.setLocation(1, 1);
p5.add(background);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
add(new ContentPanel());
add(chicken);
chicken.setLocation(100, 100);
setSize(1440, 500);
setLocale(null);
chicken.isOpaque();
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String arg[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
class ContentPanel extends JPanel{
Image bgimage = null;
ContentPanel() {
MediaTracker mt = new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage("level0.gif");
mt.addImage(bgimage, 0);
try {
mt.waitForAll();
} catch (InterruptedException e){
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bgimage, 1, 1, null);
}
}
Note: It's been a while since I used the Graphics API
Quick Answer:
You need to draw everything in your paintComponent method. Your drawing routine should check the state of all game objects and draw them accordingly. Right now the panel is drawing the background image - that's it. Add your chicken image the same way you added your bgImage.
Some more things to consider:
If you experience screen flicker look into Double Buffering.
Not to overwhelm you but you might want to do some light reading on game coding. Get a general idea on how to code your game loop and what happens each time the loop is executed.
Since you are using an OO language you should also probably make a Chicken class.
public class Chicken {
private int x;
private int y;
private Image chickenSprtie;
//add get / set for access
}
Or even a general Super Class - Sprite with int x, int y. Or even a "Drawable" interface to forces all your drawable game objects to have common methods....

Beginner Scoring program button development in 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.

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