The idea behind the code is a simple multiplying game where it generates 2 numbers and I have to input the corret answer.
Basically, my question(s) is(are):
When I do operacao.setOpaque(false); it does nothing, or at least not what I'd expect it to do (http://puu.sh/pyVcE/813aa1843a.png - shouldn't the grey area be pink, since the background is pink?). Same happens with JLabels, the setOpaque(false) leaves a grey background behind the (in this case) numbers.
I have that last commented section because I saw someone around here saying to alter the paint method, and it did work, but caused some weird issues (painted over everything when I started the console, only the JTextField would be clear), and then I "fixed" it with the setOpacity(1); setBackground(pink); - is this a proper way of doing it?
public class Frame extends JFrame {
private JPanel panel, mensagem, operacao;
private JTextArea sucesso;
private JLabel numero1, numero2;
private JTextField resposta;
private Color pink = new Color(255, 213, 224);
//more vars
public Frame() {
super("Jogo de Multiplicar!");
setOpacity(1);
setBackground(pink);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
panel = new JPanel();
mensagem = new JPanel();
operacao = new JPanel();
mensagem.setLayout(new FlowLayout(FlowLayout.CENTER));
operacao.setLayout(new FlowLayout(FlowLayout.CENTER));
sucesso = new JTextArea();
sucesso.setEditable(false);
sucesso.setOpaque(false);
sucesso.setFont(minhaFont2);
Random randomGen = new Random();
while (random1 == 0)
random1 = randomGen.nextInt(10);
while (random2 == 0)
random2 = randomGen.nextInt(10);
res = random1 * random2;
numero1 = new JLabel();
numero2 = new JLabel();
numero1.setText(random1 + " *");
numero2.setText(random2 + " =");
numero1.setOpaque(false);
numero1.setFont(minhaFont);
numero2.setFont(minhaFont);
resposta = new JTextField(2);
resposta.addActionListener(new MinhaAcao());
resposta.setFont(minhaFont);
operacao.add(numero1);
operacao.add(numero2);
operacao.add(resposta);
mensagem.add(sucesso);
operacao.setOpaque(true);
operacao.setBackground(pink);
mensagem.setOpaque(true);
mensagem.setBackground(pink);
//add(panel, BorderLayout.NORTH);
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}/*
public void paint(Graphics g) {
g.setColor(pink);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}*/
You need to textfield to be pink. You may have to do this.
resposta.setOpaque(false);
I have refactored your code like below.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Frame extends JFrame {
private JPanel panel, mensagem, operacao;
private JTextArea sucesso;
private JLabel numero1, numero2;
private JTextField resposta;
private Color pink = new Color(255, 213, 224);
//more vars
public Frame() {
super("Jogo de Multiplicar!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
getContentPane().setBackground(pink);
panel = new TransperantPanel();
mensagem = new TransperantPanel();
operacao = new TransperantPanel();
mensagem.setLayout(new FlowLayout(FlowLayout.CENTER));
operacao.setLayout(new FlowLayout(FlowLayout.CENTER));
sucesso = new JTextArea();
sucesso.setEditable(false);
Random randomGen = new Random();
int random1 =0 , random2 = 0;
while (random1 == 0)
random1 = randomGen.nextInt(10);
while (random2 == 0)
random2 = randomGen.nextInt(10);
int res = random1 * random2;
numero1 = new JLabel();
numero2 = new JLabel();
numero1.setText(random1 + " *");
numero2.setText(random2 + " =");
resposta = new JTextField(2);
resposta.setOpaque(false);
resposta.addActionListener(new MinhaAcao());
numero1.setFont(minhaFont);
numero2.setFont(minhaFont);
resposta.setFont(minhaFont);
operacao.add(numero1);
operacao.add(numero2);
operacao.add(resposta);
mensagem.add(sucesso);
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}
public static void main(String[] args){
Frame f = new Frame();
f.setVisible(true);
}
class TransperantPanel extends JPanel {
public TransperantPanel() {
setOpaque(false);
}
}
}
What i have done is
Setting background to contentPane of the frame.
Created a transparent panel(setting Opaque of the panel to false).
Setting JTextfield's Opaque to false.
Related
I have spent many hours digging around the web and cannot seem to find a straightforward answer or method to add a dropdown selection into my main panel that houses the various text fields, in this case, I am trying to add a paint color selection to the panel so that color can then be used as a variable in determining cost.
The closest I have come so far is having a combo box popup in a new window but then was unable to retrieve the selection.
package paintestimator;
import java.lang.String;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.PopupMenu;
import javax.swing.JComboBox;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PaintEstimator extends JFrame
{
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
//Josh
public PaintEstimator()
{
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
JButton ChoiceA = new JButton("Paint Color");
//JComboBox vendorBTN = (new JComboBox());
ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
//box to show chosen color
//mainPanel.add(new JLabel("Color Chosen"));
// mainPanel.add(sColor);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add( new JLabel("Select a Color"));
mainPanel.add (ChoiceA);
// mainPanel.add(sColor);
// Select<String> select = new Select<>();
//select.setLabel("Sort by");
//select.setItems("Most recent first", "Rating: high to low",
// "Rating: low to high", "Price: high to low", "Price: low to high");
//select.setValue("Most recent first");
// mainPanel.add(select);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
// mainPanel.add(ChoiceA);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
//Josh
class CalcChangeBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n); // still need refine decimal point to #.0
(one decimal place)
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f)
{
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// clear text fields and set focus
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
class ChoiceAListener implements ActionListener
{
public void actionPreformed (ActionEvent e)
{
}
public static void main(String[] args)
{
PaintEstimator window = new PaintEstimator();
window.setVisible(true);
}
}
Below is the combo box I was able to create:
public static void main(String[] args)
{
String[] optionsToChoose =
{
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
JFrame jFrame = new JFrame();
JComboBox<String> jComboBox = new JComboBox<>(optionsToChoose);
jComboBox.setBounds(80, 50, 140, 20);
JButton jButton = new JButton("Done");
jButton.setBounds(100, 100, 90, 20);
JLabel jLabel = new JLabel();
jLabel.setBounds(90, 100, 400, 100);
jFrame.add(jButton);
jFrame.add(jComboBox);
jFrame.add(jLabel);
jFrame.setLayout(null);
jFrame.setSize(350, 250);
jFrame.setVisible(true);
jButton.addActionListener((ActionEvent e) ->
{
String selectedColor = "You selected " +
jComboBox.getItemAt(jComboBox.getSelectedIndex());
jLabel.setText(selectedColor);
});
}
Start by reading through How to Use Combo Boxes (and it wouldn't hurt to look over some the examples)
Start by creating an instance field for the combobox...
public class PaintEstimator extends JFrame {
//...
private JComboBox<String> colorChoice = new JComboBox<>();
//...
Next, create a ComboBoxModel to hold the values you want to present and replace the ChoiceA button with the combobox...
mainPanel.add(new JLabel("Select a Color"));
//mainPanel.add(ChoiceA);
// mainPanel.add(sColor);
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
And then in your ActionListener, get the selected value...
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
Runnable example...
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new PaintEstimator();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintEstimator extends JFrame {
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
private JComboBox<String> colorChoice = new JComboBox<>();
public PaintEstimator() {
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
//ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add(new JLabel("Select a Color"));
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class CalcChangeBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n);
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f) {
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
}
}
I'm making a restaurant menu program with GUI.
I created 3 JPanels and set Background(Color.white) to one of them.
But java will not display that background color.
What's wrong?
Here is my code
please do not take any attention to foods' price and cardLayout. Not finished with coding.
public class MainDishPanel extends JPanel {
JCheckBox box1 = new JCheckBox("Hamburger 5 dollars"),
box2 = new JCheckBox("Pizza 5 dollars"),
box3 = new JCheckBox("French Hot dog 5 dollars");
MainDishPanel(){
setOpaque(true);
setBackground(Color.white);
setLayout(new GridLayout(3,1));
// setBorder();
add(box1);add(box2);add(box3);
setVisible(true);
}
}
class with main method:
import java.awt.BorderLayout;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.*;
public class RestaurantMenu extends JFrame implements ActionListener{
/* private JPanel maindishPanel= new JPanel(),
dessertPanel = new JPanel(),
drinkPanel = new JPanel(),*/
private JPanel leftPanel = new JPanel(),
rightPanel = new JPanel();
private MainDishPanel maindish = new MainDishPanel();
private DessertPanel dessert = new DessertPanel();
private DrinkPanel drink = new DrinkPanel();
private LinkedList<Double>price = new LinkedList<>();
private JButton left = new JButton("previous"),
right = new JButton("next");
public int page =1;
private JLabel pageLabel = new JLabel(String.valueOf(page)),
foodTypeLabel = new JLabel();
CardLayout cards;
GridBagLayout grid;
RestaurantMenu(){
setTitle("Main Dish");
GridBagConstraints gbc = new GridBagConstraints();
add(foodTypeLabel, BorderLayout.NORTH);
add(pageLabel, BorderLayout.SOUTH);
add(leftPanel, BorderLayout.WEST);
add(rightPanel, BorderLayout.EAST);
add(maindish, BorderLayout.CENTER);
grid = new GridBagLayout();
leftPanel.setLayout(grid); leftPanel.add(left);
rightPanel.setLayout(grid); rightPanel.add(right);
right.addActionListener(this);
left.addActionListener(this);
//cards = new CardLayout();
/*cards = (CardLayout)maindishPanel.getLayout();
cards.show(maindishPanel,"Main Dish");*/
setVisible(true);
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==right)
cards.next(this);
if(e.getSource()==left)
cards.previous(this);
}
public static void main (String []args){
RestaurantMenu rm = new RestaurantMenu();
}
}
I don't get any error. Background color just won't be changed to white.
RestaurantMenu class can be looked like a spaghetti code or something strange
because I have plenty things to do with that class.
Inside your MainDishPanel you need to set the background color for the JCheckBox to white, or you can just setOpaque to false on your JCheckBox
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
public class MainDishPanel extends JPanel {
JCheckBox box1 = new JCheckBox("Hamburger 5 dollars"), box2 = new JCheckBox("Pizza 5 dollars"),
box3 = new JCheckBox("French Hot dog 5 dollars");
MainDishPanel() {
setOpaque(true);
setBackground(Color.WHITE);
setLayout(new GridLayout(3, 1));
box1.setBackground(Color.WHITE); // or box1.setOpaque(false);
box2.setBackground(Color.WHITE);
box3.setBackground(Color.WHITE);
add(box1);
add(box2);
add(box3);
setVisible(true);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a java swing project that looks like this:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.Box;
import javax.swing.BoxLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class DiceGameReplaceDice extends JFrame
{
private JFrame gameFrame;
private JPanel mainPanel;
private JPanel centerPanel = new JPanel();
private JButton diceArray[];
private DiceListener diceListener = new DiceListener();
private ButtonListener buttonListener = new ButtonListener();
private Random rand = new Random();
private int NUM_DICE = 2;
private String diceImages[] = {"./src/1.png", "./src/2.png", "./src/3.png",
"./src/4.png", "./src/5.png", "./src/6.png"};
public static void main(String[] args)
{
new DiceGameReplaceDice();
}
public DiceGameReplaceDice()
{
// Initialize the frame that holds the game
gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setLocation(300, 100);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add Panel
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Instantiate a ButtonListener
buttonListener = new ButtonListener();
// Add 1 Button and 1 Label to a newly created panel
// Add new panel to West
JButton buttonW1 = new JButton("Add Die");
buttonW1.setName("W1");
buttonW1.addActionListener(buttonListener);
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest,BoxLayout.Y_AXIS ));
panelWest.setBackground(new Color(0, 0, 122)); // set to blue
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
mainPanel.add(panelWest, BorderLayout.WEST);
// Create and display center panel with dice
displayCenterPanel();
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void displayCenterPanel()
{
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel,BoxLayout.X_AXIS ));
centerPanel.setBackground(new Color(0, 122, 0)); // set to green
centerPanel.add(Box.createHorizontalGlue());
diceArray = new JButton[NUM_DICE];
// Add 2 Buttons to center panel with images of 2 random dice
for (int i=0; i<NUM_DICE; i++)
{
// Create dice button
int dieNum = rand.nextInt(6)+1;
diceArray[i] = new JButton(new ImageIcon(diceImages[dieNum-1]));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(diceListener);
// Add to center panel
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
mainPanel.add(centerPanel, BorderLayout.CENTER);
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
// Implement an (inner) class that implements ActionListener
class DiceListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
NUM_DICE -= 1;
displayCenterPanel();
}
}
// Implement an (inner) class that implements ActionListener
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String button = ((JButton)e.getSource()).getName();
System.out.println("Button Pressed: " + button);
if (button.equals("W1"))
NUM_DICE ++;
System.out.println(NUM_DICE);
displayCenterPanel();
}
}
}
When Clicking the "Add Die" button, a die is added to the screen and is correctly formatted. However, when a die is pressed, and the NUM_DICE is decreased, clicking on the die button results in weird overlaps and "ghost buttons". How do you fix this?
The quick fix would be to remove the centerPanel prior to adding the new one. Add the line
mainPanel.remove(centerPanel);
as the first thing you do inside displayCenterPanel.
However, your way of manipulating the layout dynamically leaves a lot to be desired. Instead of creating a new panel each time, just modify the existing one:
public class DiceGame {
private JPanel centerPanel = new JPanel();
private Random rand = new Random();
private int numDice = 2;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DiceGame());
}
public DiceGame() {
JFrame gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JButton buttonW1 = new JButton("Add Die");
buttonW1.addActionListener(e -> {
numDice++;
updateCenterPanel();
});
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest, BoxLayout.Y_AXIS));
panelWest.setBackground(new Color(0, 0, 122));
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
centerPanel.setBackground(new Color(0, 122, 0));
mainPanel.add(panelWest, BorderLayout.WEST);
mainPanel.add(centerPanel);
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void updateCenterPanel() {
centerPanel.removeAll();
centerPanel.add(Box.createHorizontalGlue());
JButton[] diceArray = new JButton[numDice];
for (int i = 0; i < numDice; i++) {
diceArray[i] = new JButton(Integer.toString(rand.nextInt(6) + 1));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(e -> {
numDice--;
updateCenterPanel();
});
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
centerPanel.revalidate();
centerPanel.repaint();
}
}
Revalidating and repainting is necessary after invalidating the component hierarchy.
Notes:
Don't create fields when local variables will do.
NUM_DICE is not final, so it should be named numDice.
Calling gameFrame.setVisible(true); when it is already visible does nothing.
When you have a working version of whatever it is you are doing, replace setSize(...) on the JFrame with pack and be sure to calculate the size of its children properly.
I am working on a project where I have to create an image manager program in Java. The program will have the following features in it: Program should take image from the user as input. Then it should display the image in panel(1), and in panel(2) it should give the user an options of changing width, height, hgap, vgap, top margin and left margin of the image with an 'OK' button at the end including an 'action listener' feature. Using the above mentioned features we will get the grids on the image. Now if the user clicks on the particular grid then that particular image should get extracted into a folder.
I am attaching the program which we have done so far.
The difficulties we are facing are: we are not able to insert a JScrollPane for the image. As well as we are unaware of how to add action listeners to the grids so that we can extract that particular image.
package project_image_manager_imp_files;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
class SidePanel1 extends JPanel implements ActionListener {
JTextField top_margin = new JTextField(10);
JTextField left_margin = new JTextField(10);
JTextField Width = new JTextField(10);
JTextField Height = new JTextField(10);
JTextField Vgap = new JTextField(10);
JTextField Hgap = new JTextField(10);
JLabel j1 = new JLabel("Top margin");
JLabel j2 = new JLabel("Left margin");
JLabel j3 = new JLabel("Width");
JLabel j4 = new JLabel("Height");
JLabel j5 = new JLabel("Vertical gap");
JLabel j6 = new JLabel("Horizontal gap");
JButton b = new JButton("OK");
public SidePanel1() {
this.setBackground(Color.black);
Dimension d1 = new Dimension(1000, 1000);
this.setMaximumSize(d1);
this.setPreferredSize(d1);
JPanel p = new JPanel();
JScrollPane vertical = new JScrollPane();
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(vertical);
vertical.setVerticalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(vertical);
//showCoo.build(c);
//c.add(p);
//p.setOpaque(false);
//t1.addActionListener(new JTextFieldEventClass() );
//b.addActionListener(new JTextFieldEventClass() );
// String s=t3.getText();
//int c=Integer.parseInt(s);
p.add(j1);
p.add(top_margin);
p.add(j2);
p.add(left_margin);
p.add(j3);
p.add(Width);
p.add(j4);
p.add(Height);
p.add(j5);
p.add(Vgap);
p.add(j6);
p.add(Hgap);
p.add(b);
p.setLayout(new GridLayout(7, 2));
b.addActionListener(this);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1, 2));
frame.setBounds(200, 200, 600, 400);
frame.setTitle("Hello World Test");
frame.setResizable(true);
//frame.setSize (500, 300);
Container c = frame.getContentPane();
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.WEST);
frame.add(p, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
int height;
int width;
int hgap;
int vgap;
int tm;
int lm;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(Toolkit.getDefaultToolkit().getImage("images1.jpg"), 0, 0, this);
Graphics2D g2d = (Graphics2D) g.create();
//File f=new File("images1.jpg");
//BufferedImage im=ImageIO.read(f);
int frame_width = getWidth();
int frame_height = getHeight();
for (int j = 0; j < frame_height; j++) {
int y = tm + (height * j) + (vgap * j);
for (int i = 0; i < frame_width; i++) {
int x = lm + (width * i) + (hgap * i);
g.drawRect(x, y, width, height);
}
}
}
public static void main(String[] argv) {
//static JScrollBar scrollbar;
SidePanel1 panel = new SidePanel1();
panel.setLayout(new FlowLayout());
//scrollbar = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//panel.add(scrollbar);
try {
while (true) {
Thread.sleep(100);
///.out.println("("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+")");
}
} catch (InterruptedException e) {}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
width = Integer.parseInt(Width.getText());
height = Integer.parseInt(Height.getText());
hgap = Integer.parseInt(Hgap.getText());
vgap = Integer.parseInt(Vgap.getText());
lm = Integer.parseInt(left_margin.getText());
tm = Integer.parseInt(top_margin.getText());
repaint();
}
}
I'm stuck using Button and JButton
expected result.. ( all information working )
http://i.stack.imgur.com/3qX7v.png
and what I have
http://i.stack.imgur.com/a4gao.png
I want to replace this:
Button butRock = new Button("Rock");
butRock.addActionListener(this);
ButtPan.add(butRock);
To This:
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
I'm stuck because when I replace Button to JButton the program doesn't work properly...when I use this JButton
Question: How to replace the button with picture and that program still work properly...
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class gui extends JFrame implements ActionListener
{
public JLabel JWoL,JWoLPlayer,JWoLPC,JNumWin,JNumLose,JNumTie, logo;
public JLabel JWinT,JLoseT,JTieT, rpsP, rpsC, result;
JPanel LabelsPan;
static final int WINS = 0, LOSSES = 1, DRAWS = 2;
int[] counts = new int[3];
String[] strings = {"| You Win", "| You Lose", "| Draw"};
JLabel[] labels = {JNumWin, JNumLose, JNumTie};
#SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
gui theWindow = new gui();
theWindow.show();
}
private void record(int type)
{
JWoL.setText(strings[type]);
counts[type]++;
labels[type].setText(""+counts[type]);
}
public gui() throws IOException
{
JPanel logo = new JPanel();
logo.setLayout(new GridLayout(1,1));
BufferedImage myPicture = ImageIO.read(new File("logo.jpg"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add(picLabel);
JPanel ButtPan=new JPanel();
ButtPan.setLayout(new GridLayout(1,3));
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
Button butPaper = new Button("Paper");
butPaper.addActionListener(this);
ButtPan.add(butPaper);
Button butScissors = new Button("Scissors");
butScissors.addActionListener(this);
ButtPan.add(butScissors);
JWoLPlayer = new JLabel();
JWoLPC = new JLabel();
JWoL= new JLabel();
JLabel rpsPlayer= new JLabel("| Your Choice: ");
JLabel rpsComputer= new JLabel("| Computers Choice: ");
setTitle("| RoPaS GAME |");
LabelsPan=new JPanel();
LabelsPan.setLayout(new GridLayout(3,2));
rpsP = new JLabel();
LabelsPan.add(rpsPlayer);
LabelsPan.add(JWoLPlayer);
rpsC = new JLabel();
LabelsPan.add(rpsComputer);
LabelsPan.add(JWoLPC);
result =new JLabel();
LabelsPan.add(JWoL,"Center");
JPanel WLPan = new JPanel();
WLPan.setLayout(new GridLayout(3, 2));
JWinT = new JLabel("Wins: ");
JLoseT = new JLabel("Losses: ");
JTieT = new JLabel("Ties: ");
WLPan.add(JWinT);
JNumWin = new JLabel();
WLPan.add(JNumWin);
WLPan.add(JLoseT);
JNumLose = new JLabel();
WLPan.add(JNumLose);
WLPan.add(JTieT);
JNumTie = new JLabel();
WLPan.add(JNumTie);
JLabel[] labels1 = {JNumWin, JNumLose, JNumTie};
labels = labels1;
JPanel TwoPanesN1=new JPanel();
TwoPanesN1.setLayout(new BorderLayout());
TwoPanesN1.add(logo,"North");
TwoPanesN1.add(LabelsPan,"West");
TwoPanesN1.add(WLPan,"East");
getContentPane().setLayout(new GridLayout(3,2));
getContentPane().add(ButtPan);
getContentPane().add(TwoPanesN1);
Font fontDisplay = new Font("Arial", Font.BOLD, 16);
JWoL.setFont(fontDisplay);
LabelsPan.setFont(fontDisplay);
setSize(400,250);
setVisible(true);
setResizable(false);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent ev){System.exit(0);}});
}
public void Play(String PlayerChoice)
{
String PCchoice=PCansw();
JWoLPC.setText(PCchoice);
if(PlayerChoice.equals(PCchoice))
record(DRAWS);
else if(PlayerChoice.equals("Rock"))
if(PCchoice.equals("Paper"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Paper"))
if(PCchoice.equals("Scissors"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Scissors"))
if(PCchoice.equals("Rock"))
record(LOSSES);
else
record(WINS);
}
public String PCansw()
{
String rpsPC2="";
int rpsPC=(int)(Math.random( )*3)+1;
if(rpsPC==1)
rpsPC2= "Rock";
else if(rpsPC==2)
rpsPC2= "Paper";
else if(rpsPC==3)
rpsPC2= "Scissors";
return rpsPC2;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Exit"))
System.exit(0);
else
{
JWoLPlayer.setText(e.getActionCommand());
Play(e.getActionCommand());
}
}
}
The problem is that you are using getActionCommand to determine which JButton was clicked but this property is not set by default in Swing. You would have to call
butRock.setActionCommand("Rock");
java.awt.Button automatically uses the label property as the ActionCommand if it not explicitly set. From the docs
If the command name is null (default) then this method returns the label of the button.
Some asides:
Better to avoid mixing heavy & lightweight components and use lightweight components throughout the application.
As your Rock, Paper, Scissors buttons have identical functionality, consider using an Action.
A direct instance JFrame is typically used rather than extending the class
Use Initial Threads
Window#show is deprecated. Use Window#setVisible.
Don't use System.exit - See more here