I'm trying to make a snakes and ladders game. It doesn't done yet(no swap turn, no use of ladder and snake) and have so many bug.
But My point is that
I found a problem that make me very curious(Picture Below). It about making a token move. My strategy is that I add a[10][10] array of JPanal(I named it class as Cell) on a big JPanel(I named it class as Board) whose I set its bg as a picture of snakes and ladders game from google and set the layout to gridlayout(10,10). And on every Cell there's one token which is hiding and will only reveal when press the roll button and the output point to that Cell.
This is where the problem happened.
Image of the program when execute
When I press roll button for sometimes
There's a button appear every time I press!(They are not clickable though.)
I know that my start point doesn't even on the left bottom square but where is all that jbutton came from!
This is my main class
public class Main extends JFrame {
TextField text = new TextField();
Dice dice = new Dice();
int tempi = -1, tempj = -1,sum =0;
//Main Method
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Main mPage = new Main();
mPage.setVisible(true);
}
});
}
//Constructor
public Main(){
super("Snakes and Ladders");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(1280,768);
setLocation(400,150);
setLayout(new FlowLayout(FlowLayout.LEFT,30,100));
Board board = new Board();
getContentPane().add(board);
getContentPane().add(dice);
getContentPane().add(text);
//my problem is here.
dice.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int score = Dice.rollDice();
text.setText(String.valueOf(score));
if (tempi != -1 || tempj != -1){
board.cell[9-tempi][9-tempj].fade();
}
if (tempi == -1 && tempj == -1){
sum = sum + score - 1;
}
else sum = sum + score;
tempj = sum%10;
tempi = (sum - tempj)/10;
board.cell[9-tempi][9-tempj].reveal();
}
});
pack();
setMinimumSize(this.getSize());
}
}
This is Cell class
public class Cell extends JPanel implements Cloneable {
private Token pl1 = new Token();
//constructor
public Cell(){
setOpaque(true);
setBackground(new Color(0,0,0,0));
setLayout(new GridLayout(2,2));
this.fade();
this.add(pl1);
}
public void fade(){
pl1.setVisible(false);
}
public void reveal(){
pl1.setVisible(true);
}
}
This is Token class
public class Token extends JLabel {
private BufferedImage image = null;
public Token(){
try {
image = ImageIO.read(new File("C:\\Users\\myacc\\IdeaProjects\\Snakes and Ladders\\src\\Token.png"));
} catch (IOException e) {
e.printStackTrace();
}
Image player = image.getScaledInstance(20,20,Image.SCALE_SMOOTH);
this.setIcon(new ImageIcon(player));
}
}
setBackground(new Color(0,0,0,0));
Don't use backgrounds with transparency. Swing does not know how to paint transparent backgrounds properly.
For full transparency you just make the component non-opaque:
//setOpaque(true);
//setBackground(new Color(0,0,0,0));
setOpaque(false);
If you need semi-transparency, then you need to do custom painting yourself. Check out Background With Transparency for more information on this topic.
Also don't use a TextField. That is an AWT component. Use a JTextField which is the Swing component.
I'm trying to make the person walk but for some reason when I switch icons the label returns to it's default location for a split second then updates to the where I set the bounds. Extremely annoying, any help is much appreciated. Thank You.
public class Main extends JFrame implements ActionListener{
JLabel x = new JLabel("");
ImageIcon player1 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player1.png");
ImageIcon player2 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player2.png");
static int count;
Timer timer;
Main(){
timer = new Timer(100,this);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setFocusable(false);
add(x);
timer.start();
}
public static void main(String [] args){
Main main = new Main();
}
#Override
public void actionPerformed(ActionEvent e) {
count += 1;
if(count == 10){
x.setIcon(player1);
}
if(count == 20){
x.setIcon(player2);
}
if(count == 30){
count = 0;
}
x.setBounds(0, 0,60,60);
}
}
The setBounds(...) call only works when the layout used is null. Having said that, don't use null layouts (see this), but instead use proper layout managers and component positioning.
Code with near-identical blocks like this makes me cringe. Plus it adds up to where you have a thousand lines of code where half that would suffice. Surely there is a way to make a loop to make it all happen and not have code that looks so unsophisticated and brainless.
Offhand it seems like to do so would be adding as much code as I seek to reduce: loop to make 5 buttons, array of labels for the buttons, array of backgrounds... maybe more. Even if that turned out to be acceptable, how would I make a loop to handle the listeners? I can't have an array of methods, can I? I guess such a loop it would have to include a switch. Yes? I'd probably do that if I didn't want to seek a better solution. So I'm asking...
What would code look like that would listen to the entire group of buttons and take action based on which one was pressed? To which component would I assign the single listener? And how?
(There's a chance that the answer to that question will make me cringe even more than the repetitive nature of the code, if I realize that I already know how to do so and needn't have even asked in the first place, but I'm asking anyway. I'm at one of those I've-had-it-for-today points where the brain just wants out.)
private void makeScoremasterBonuses(){
pnlBonuses = new JPanel(new GridLayout(1, 6));
pnlBonuses.setSize(6,1);
JButton t1 = (new JButton("3W"));
t1.setToolTipText("This is a triple-word cell.");
t1.setBackground(TRIPLE_WORD);
t1.setHorizontalAlignment(JButton.CENTER);
t1.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell,TRIPLE_WORD);
}});
JButton t2 = (new JButton("3L"));
t2.setToolTipText("This is a triple-letter cell");
t2.setBackground(TRIPLE_LETTER);
t2.setHorizontalAlignment(JButton.CENTER);
t2.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell,TRIPLE_LETTER);
}});
JButton t3 = (new JButton("2W"));
t3.setToolTipText("This is a double-word cell");
t3.setBackground(DOUBLE_WORD);
t3.setHorizontalAlignment(JButton.CENTER);
t3.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell,DOUBLE_WORD);
}});
JButton t4 = (new JButton("2L"));
t4.setToolTipText("This is a double-letter cell");
t4.setBackground(DOUBLE_LETTER);
t4.setHorizontalAlignment(JButton.CENTER);
t4.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell,DOUBLE_LETTER);
}});
JButton t5 = (new JButton(""));
t5.setToolTipText("No bonus");
t5.setBackground(WHITE);
t5.setHorizontalAlignment(JButton.CENTER);
t5.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell,B_NORMAL);
}});
pnlBonuses.add(new JLabel("Legend: "));
pnlBonuses.add(t1);
pnlBonuses.add(t2);
pnlBonuses.add(t3);
pnlBonuses.add(t4);
pnlBonuses.add(t5);
}
I'm not asking anyone to write the code; I wouldn't even want that (but I couldn't ignore it!).
Here's what the code above does:
Generally any time you have repeated functionality like that, you want to extract that code out into a helper method like this:
private JButton makeJButton(String label, String toolTip, Color bgColor, final Color highlight) {
JButton button = new JButton(label);
button.setToolTipText(toolTip);
button.setBackground(bgColor);
button.setHorizontalAlignment(JButton.CENTER);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell, highlight);
}
});
return button;
}
Then your makeScoremasterBonuses() method becomes much simpler:
private void makeScoremasterBonuses() {
pnlBonuses = new JPanel(new GridLayout(1, 6));
pnlBonuses.setSize(6, 1);
pnlBonuses.add(new JLabel("Legend: "));
pnlBonuses.add(makeJButton("3W", "This is a triple-word cell.", TRIPLE_WORD, TRIPLE_WORD));
pnlBonuses.add(makeJButton("3L", "This is a triple-letter cell.", TRIPLE_LETTER, TRIPLE_LETTER));
pnlBonuses.add(makeJButton("2W", "This is a double-word cell.", DOUBLE_WORD, DOUBLE_WORD));
pnlBonuses.add(makeJButton("3L", "This is a double-letter cell.", DOUBLE_LETTER, DOUBLE_LETTER));
pnlBonuses.add(makeJButton("", "No bonus.", WHITE, B_NORMAL));
}
Identify the aspects that vary, collect them, and iterate over the collection.
Something like this (untested):
pnlBonuses = new JPanel(new GridLayout(1, 6));
pnlBonuses.setSize(6,1);
pnlBonuses.add(new JLabel("Legend: "));
// Create class "CellInfo" with constructor and getters for desired properties.
CellInfo cellInfos[] = {
new CellInfo("3W", "This is a triple-word cell.", TRIPLE_WORD),
new CellInfo("3L", "This is a triple-letter cell.", TRIPLE_LETTER),
// ...
};
// Add a button for each item described by the cellInfos.
for (CellInfo cellInfo : cellInfos) {
Button b = new JButton(cellInfo.getLabel());
b.setToolTipText(cellInfo.getToolTipText());
b.setBackground(cellInfo.getBackground());
b.setHorizontalAlignment(JButton.CENTER);
b.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell, cellInfo.getBackground());
}});
pnlBonuses.add(b);
}
Note that you might need to create some "final" variables for placeholders for use in the inner anonymous class but the idea should work.
An enum could be your friend here. It's almost an array of methods:
static enum Btn {
TripleWord("3W", "This is a triple word cell.", TRIPLE_WORD),
TripleLetter("3L", "This is a triple letter cell.", TRIPLE_LETTER),
DoubleWord("2W", "This is a double word cell.", DOUBLE_WORD),
DoubleLetter("2L", "This is a double letter cell.", DOUBLE_LETTER),
NoBonus("", "No bonus.", WHITE, B_NORMAL);
final String label;
final String tooltip;
final Color color;
final Color shade;
Btn(String label, String tooltip, Color color, Color shade) {
this.label = label;
this.tooltip = tooltip;
this.color = color;
this.shade = shade;
}
Btn(String label, String tooltip, Color color) {
this(label, tooltip, color, color);
}
public JButton asJButton() {
JButton btn = (new JButton(label));
btn.setToolTipText(tooltip);
btn.setBackground(color);
btn.setHorizontalAlignment(JButton.CENTER);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Highlighter.shadeSymmetric(currentCell, shade);
}
});
return btn;
}
}
private void makeScoremasterBonuses() {
int nBtns = Btn.values().length;
JPanel pnlBonuses = new JPanel(new GridLayout(1, nBtns + 1));
pnlBonuses.setSize(nBtns + 1, 1);
pnlBonuses.add(new JLabel("Legend: "));
for (Btn btn : Btn.values()) {
pnlBonuses.add(btn.asJButton());
}
}
(I know I could have edited my previous answer, but this one's so different...)
Thanks to #OldCurmudgeon, I have come up with what I think is pretty good.
Here's "proof" (I may just leave each label and tooltip as is):
public enum Colors {
TRIPLE_WORD (255, 220, 50),
TRIPLE_LETTER (255, 255, 150),
DOUBLE_WORD ( 0, 255, 0),
DOUBLE_LETTER (214, 245, 214),
NOT_A_BONUS (255, 255, 255);
private final int red, green, blue;
Colors(int r, int g, int b){
this.red = r;
this.green = g;
this.blue = b;
}
public java.awt.Color background(Colors c){
return new java.awt.Color(c.red, c.green, c.blue);
}
}
private void makeScoremasterBonuses(){
Colors c;
Colors all [] = Colors.values();
String labels[] = new String[all.length];
String abbrs [] = new String[all.length];
JButton but;
pnlBonuses = new JPanel();
pnlBonuses.add(new JLabel("Legend:"));
for (int i = 0; i < all.length; i++) {
labels[i] = all[i].name().replace("_", " ").toLowerCase();
abbrs [i] = abbreviate(all[i].name());
c = Colors.values()[i];
but = new JButton(abbrs[i]);
but.setToolTipText(labels[i]);
but.setBackground(c.background(c));
but.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
but.setActionCommand("" + i);
but.addActionListener(this);
pnlBonuses.add(but);
}
}
=== THIS IS A MAJOR EDIT OF WHAT I POSTED AN HOUR AGO ===
I wanted to see if I could implement my own naive method. Here it is:
public class Game implements ActionListener{
public Color [] backgrounds = {TRIPLE_WORD, TRIPLE_LETTER,
DOUBLE_WORD, DOUBLE_LETTER, B_NORMAL};
private void makeScoremasterBonuses(){
String[] labels = {"3W", "3L", "2W", "2L", " "};
JButton but;
pnlBonuses = new JPanel();
pnlBonuses.add(new JLabel("Legend:"));
for (int i = 0; i < labels.length; i++) {
char wt = labels[i].charAt(0);
char tp = labels[i].charAt(1);
but = new JButton(labels[i]);//("" + i);
but.setBackground(backgrounds[i]);
but.setHorizontalAlignment(SwingConstants.CENTER);
but.setActionCommand("" + i);
but.addActionListener(this);
but.setToolTipText("This is a "
+ (i == labels.length - 1 ? "non-bonus" :
(wt == '3' ? "triple" : "double")
+ " " + (tp == 'L' ? "letter" : "word"))
+ " cell.");
pnlBonuses.add(but);
}
}
public void actionPerformed(ActionEvent evt) {
int i = Integer.parseInt(evt.getActionCommand());
Highlighter.shadeSymmetric(currentCell,backgrounds[i]);
}
This has NOW (after edits) EVEN MORE SO been the best thread I've initiated, in terms of quality of responses and all that I've learned because of them. THANK YOU ALL.
BUT I STILL haven't managed to appropriately use setActionCommand. Whatever I did to TRY to use it wound up being so much longer code-wise that I gave up and went for the short and easy but inappropriate.
Any thoughts about how to use set... and getActionCommand the right way (i.e., as Actions) without adding a ton of code to do so?
How can I add an event to this code such that if i drag the slider, the number is displayed. Please, let me know as I am new to Java..
import javax.swing.*;
public class Slider extends JFrame {
JSlider pickNum = new JSlider(JSlider.HORIZONTAL, 0, 30, 5);
public Slider() {
super("Slider");
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pickNum.setMajorTickSpacing(10);
pickNum.setMinorTickSpacing(1);
pickNum.setPaintTicks(true);
pickNum.setPaintLabels(true);
getPointedValue();
this.add(pickNum);
this.setVisible(true);
}
public final int getPointedValue() {
int value;
value = pickNum.getValue();
return value;
}
public static void main(String[] args) {
Slider frame = new Slider();
int i;
i = frame.getPointedValue();
System.out.println("current value is:" + i);
}
}
See addChangeListener(ChangeListener), as well as How to Use Sliders & How to Write a Change Listener.
As a concrete example using ChangeListener, SpinSlider shows how to connect a JSlider and a JSpinner.
Right now i change the background color of a button by using
button.setBackground(Color.WHITE);
That being an example.
But when i have a massive grid out of jbuttons (1000+), just running a for loop to change every buttons background is very, very slow. You can see the grid slowly turning white, box by box. I really don't want this
Is there a better way of changing every JButton on the grid to the same color at the same time?
This is how i am making the grid, the numbers used are only for example...
grid = new JPanel(new GridLayout(64, 64, 0, 0));
That's 4096 buttons, takes about 30+ seconds to change every button to the same color.
Edit 1: I need the buttons to be clickable, like when i click a button it turns blue for example. when all of the buttons are clicked, change the color of every button to white. Right now i have that working fine, but it is just slow to change the color of every button.
Edit 2: this is how i am changing the buttons:
new javax.swing.Timer(300, new ActionListener() {
int counter = 0;
public void actionPerformed(ActionEvent e) {
if (counter >= counterMax) {
((Timer) e.getSource()).stop();
}
Color bckgrndColor = (counter % 2 == 0) ? flashColor : Color.white;
for (JButton button : gridButton) {
button.setBackground(bckgrndColor);
}
counter++;
}
}).start();
The fact that you see the boxes being repainted individually indicates that either double buffering is turned off, or that the paint code in the button UI makes use of paintImmediately().
I tested your setup with 64x64 JButtons, an made sure that all UI operations were executed in the EDT (Event Dispatch Thread). I can confirm the effect you saw, changing the background of all buttons took about 1200 ms, with every box repainted immediately.
You can bypass the immediate repaints by setting the grid to non-visible before, and to visible after you changed the backgrounds:
grid.setVisible(false);
for (Component comp : grid.getComponents()) {
comp.setBackground(color);
}
grid.setVisible(true);
This caused the grid to do only one repaint, and reduced the time to ~300ms (factor 4).
This is still too slow for frequent updates, so you're better off with a custom component which draws the grid, or a flyweight container (what trashgod suggested in the comment to your question) if you want allow the grid cells to be arbitrary components.
You can get a considerable benefit if only visible buttons need to be repainted. In the MVC approach shown below, each button listens to a model that defines it's current state. Updating the model is quite fast compared to repainting. Although startup takes a few seconds, I see updates taking < 10 ms. in the steady-state. It's not as scalable as the flyweight pattern used by JTable, illustrated here, but it may serve.
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import javax.swing.*;
/** #see https://stackoverflow.com/questions/6117908 */
public class UpdateTest {
private static final int ROW = 64;
private static final int COL = 64;
private static final int MAX = COL * ROW;
private final DataModel model = new DataModel(MAX);
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new UpdateTest().create();
}
});
}
void create() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(ROW, COL));
for (int i = 0; i < MAX; i++) {
panel.add(new ViewPanel(model, i));
}
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long start = System.nanoTime();
model.update();
System.out.println(
(System.nanoTime() - start) / (1000 * 1000));
}
});
JFrame f = new JFrame("JTextTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(panel), BorderLayout.CENTER);
f.setPreferredSize(new Dimension(800, 600));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
timer.start();
}
private static class ViewPanel extends JPanel implements Observer {
private final JButton item = new JButton();
private DataModel model;
private int index;
public ViewPanel(DataModel model, int i) {
this.model = model;
this.index = i;
this.add(item);
item.setText(String.valueOf(i));
item.setOpaque(true);
item.setBackground(new Color(model.get(index)));
model.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
int value = model.get(index);
item.setBackground(new Color(value));
}
}
private static class DataModel extends Observable {
private final Random rnd = new Random();
private final int[] data;
public DataModel(int n) {
data = new int[n];
fillData();
}
public void update() {
fillData();
this.setChanged();
this.notifyObservers();
}
public int get(int i) {
return data[i];
}
private void fillData() {
for (int i = 0; i < data.length; i++) {
data[i] = rnd.nextInt();
}
}
}
}