I am working on a java game for class where we implement a game of nim. I thought that I was nearing completion but when I ran the program, nothing appears. It just says build successful and quits. I never get to see the game or play it. Below is my code for the application.
package Nim;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Nim extends JFrame implements ActionListener {
// Number of stickSpace that is needed for the sticks;
int rowspace = 3;
// Buttons for the human to click to take turns playing witht the computer.
private JButton humanMove,
computerMove;
// whatRow = what row the user would like to remove from
// howMany = how many sticks to take from each row
private JComboBox whatRow,
howMany;
// Creates an array of JTextFields with the rowspace as a size.
private JTextField[] stickSpace = new JTextField[rowspace];
// Creates the game;
private Nimgame nimgame;
public void Nim(){
//As requireed, we use a loop to fill the array.
for(int i=0; i<rowspace ;i++){
stickSpace[i] = new JTextField(5);
}
// Creates pulldown menus for the user to select the whatRow s/he
// wants to choose from, and another for howMany s/he wants to take.
whatRow = new JComboBox();
howMany = new JComboBox();
// Add the options to the pulldown menus so the player can choose.
// 0-2 because the array index starts at 0. 1-3 for the amount of sticks.
for(int p=0; p<=3; p++){
if(p<3){
whatRow.addItem(p);
}
if(p>0){
howMany.addItem(p);
}
}
// Adds the text "Human Turn" and "CPU Turn" to the buttons used for turns.
humanMove = new JButton("Human Turn");
computerMove = new JButton("CPU Turn");
// Adds a listener to the buttons to signal the game its time to act.
humanMove.addActionListener(this);
computerMove.addActionListener(this);
// Creates a gridlayout (3,2) with 3 rows and two columns.
JPanel gridpanel = new JPanel(new GridLayout(3,2));
// Labels the rows so the player knows it starts at row Zero - Three.
gridpanel.add(new JLabel("Row Zero", JLabel.LEFT));
gridpanel.add(stickSpace[0]);
gridpanel.add(new JLabel("Row One", JLabel.LEFT));
gridpanel.add(stickSpace[1]);
gridpanel.add(new JLabel("Row Two", JLabel.LEFT));
gridpanel.add(stickSpace[2]);
// Creates another gridlayout this time with 4 rows and 2 columns.
// This sill be used to add the comboboxes, labels, and buttons.
JPanel mainPanel = new JPanel(new GridLayout(4,2));
mainPanel.add(new JLabel("Remove from Row:", JLabel.RIGHT));
mainPanel.add(whatRow);
mainPanel.add(new JLabel("# To Remove:", JLabel.RIGHT));
mainPanel.add(howMany);
mainPanel.add(humanMove);
mainPanel.add(computerMove);
// This adds the gridpanel and the main panel to the visual
// application, but they are still not visiable at this moment.
getContentPane().add(gridpanel, BorderLayout.NORTH);
getContentPane().add(mainPanel, BorderLayout.SOUTH);
// This sections sets the title, size, position on screen, sets it visiable,
// sets the background color, and makes it exit on close of the visual application.
setTitle("The Game of Nim");
setSize(300, 250);
setBackground(Color.yellow);
setVisible(true);
// Creates the actual game to play.
nimgame = new Nimgame();
// Prints out the sticks in each row.
for(int p=0; p<3; p++){
stickSpace[p].setText(nimgame.addSticks(p));
}
}
// Method to handle when an action lister find an action event
public void actionPerformed(ActionEvent e){
// Checks if the humanMove button has been pressed
if(e.getSource() == humanMove){
int foo = whatRow.getSelectedIndex();
int bar = howMany.getSelectedIndex()+1;
nimgame.stickRemove(foo, bar);
for(int p=0; p<3; p++){
stickSpace[p].setText(nimgame.addSticks(p));
}
}
// Checks if the computerMove button has been pressed.
if(e.getSource() == computerMove){
nimgame.computerRandom();
for(int p=0; p<3; p++){
stickSpace[p].setText(nimgame.addSticks(p));
}
}
// Checks to see if the game is over or not.
if(nimgame.isDone()){
JOptionPane.showMessageDialog(null, "Game Over Player Player" + nimgame.whoWon());
}
}
public static void main(String[] args) {
Nim NIM = new Nim();
}
}
Any idea why nothing would be showing up? I figured I forgot to setVisible, but that wasn't the case. Any help would be much appreciated.
public void Nim(){
This isn't a constructor, it's a void method declaration with an awfully confusing name. As you don't declare a constructor at all, you have an implicit default constructor which is called here:
Nim NIM = new Nim();
but the default constructor doesn't do what you'd expect, so you don't see anything. To fix this, change the aforementioned method definition to a constructor definition by removing void:
public Nim() {
Related
When I try to run this, I keep getting an empty frame that cannot be closed, and I have to terminate the program from eclipse. I am fairly certain that the problem is a result of the while loop (about 2/3 of the way down the code block), but I haven't been able to figure out a way to fix this
public Draw()
{
super( "Uno");
JMenuBar bar = new JMenuBar(); // create menu bar
JMenu gameMenu = new JMenu( "Play Game" );
JMenu quitMenu = new JMenu( "Quit" ); //Quit Program
bar.add( gameMenu ); // add Add menu to menu bar
bar.add( quitMenu ); // add quit button to menu bar
setJMenuBar( bar ); // set menu bar for this application
window = new JDesktopPane();
add(window);
gameMenu.addMouseListener(
new MouseListener()
{
public void mouseClicked(MouseEvent e)
{
Dimension size = window.getSize();
double height = size.getHeight();
double width = size.getWidth();
JInternalFrame frame = new JInternalFrame("Uno", true, true, true, true );
JFrame input = new JFrame();
input.setTitle(" ");
input.setSize(350, 155);
input.setLayout(new FlowLayout());
input.setLocationRelativeTo(null);
input.setVisible(true);
JLabel label1 = new JLabel("How many total players? (2-10)");
final JTextField text1 = new JTextField(3);
JLabel label2 = new JLabel("How many computer players? *");
final JTextField text2 = new JTextField(3);
JLabel label3 = new JLabel("* Computer players must be <= total number of players");
JButton confirm = new JButton("OK");
label1.setVisible(true);
label2.setVisible(true);
label3.setVisible(true);
text1.setVisible(true);
text2.setVisible(true);
confirm.setVisible(true);
input.add(label1);
input.add(text1);
input.add(label2);
input.add(text2);
input.add(label3);
input.add(confirm);
while(valid == false)
{
confirm.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String players = text1.getText();
String computers = text2.getText();
int temp1 = Integer.parseInt(players);
System.out.println("Number of players = " + temp1);
int temp2 = Integer.parseInt(computers);
System.out.println("Number of computers = " + temp2);
if (temp1 >= 2 && temp1 <= 10)
if (temp2 <= temp1 && temp2 >= 0)
valid = true;
} //close actionPerformed
}); //close ActionListener
} //close while loop
} //close mouseClicked
} //close mouseListener
} //close Draw
Initially, I was having an issue where it kept infinitely drawing the frame on top of itself because the while loop kept returning false. That issue was solved by removing the components from the while loop, and placing them before it as they are above. Now when I run it, all I get is this: picture
The goal of this program is to make an Uno game, but the first step is to determine the number of players. This is the only way I know how to do this, and this is only the second program I have done with graphics, so I am by no means an expert at Java. I will appreciate any help I can get because I have been stuck for a few days now.
The problem is that you are not giving the event handlers any chance to do their job. Your while loop continually creates event handlers. However, the actionPeformed() method can never be called because the while loop has control of the CPU and the button will not respond to any clicks.
I suggest that you learn a bit more about event handling. You will need to redesign your code in order to get the behavior you wish. Most likely you need to remove the while loop entirely and just create an event handler which will execute code when the button is clicked.
For future reference:
In general, checking equality with a boolean value is unnecessary. The result of == is a bool, but the variable you are checking is already a bool. So use it directly: instead of while (valid == false), you can do while (!valid). If you read the ! as "not", this actually makes a lot of sense.
In this case, the point is moot, since you need to remove the while loop entirely. However, this might be useful information for you some time in the future.
Simplified: How to make String value to call specific existed JButton variable name in java?
I'm trying to make a non-ordinary Tic-Tac-Toe game...
Anyway, what I will post here is not really the whole concept of that. I just want to make it simple: I have 9 square jButtons named (3 by 3) (and maybe allow user to make 4x4, 5x5, 10x10 etc. via settings in future):
[markbox_00_00] / [markbox_00_01] / [markbox_00_02]
[markbox_01_00] / [markbox_01_01] / [markbox_01_02]
[markbox_02_00] / [markbox_02_01] / [markbox_02_02]
[btnSave] / [btnUndoActions]
where the first two digit represent the row and the next two is the column; and a save button (btnSave) and undo button(btnUndoActions).
Each markbox have default spring value of "0", when I click it turns "1"; and when I click "1" it turns "0". When you press undo button it will reset to last save.
Here is some of my simplified line of codes:
private byte markboxColLimit = 3, markboxRowLimit = 3, row, col;
private byte[][] saveNumber = new byte[markboxRowLimit][markboxColLimit];
private String buttonName;
public Astral_TicTacToe() {
initComponents();
/* I want something like this, but using a for loop based on markboxColLimit and
markboxRowLimit as limits */
markbox_00_00.setText("0");
markbox_00_01.setText("0");
markbox_00_02.setText("0");
markbox_01_00.setText("0");
markbox_01_01.setText("0");
markbox_01_02.setText("0");
markbox_02_00.setText("0");
markbox_02_01.setText("0");
markbox_02_02.setText("0");
/* I know the line below is wrong... what I'm trying is to avoid
* repetitiveness by looping and dynamically calling the variable
* name of JButtons, or in other ways...
*/
/* Attempting to make an alternative code from above (trying to make a loop instead) */
for(row = 0; row < markboxRowLimit; row++){
for(col = 0; col < markboxColLimit; col++){
buttonName = "markbox_0" + Byte.toString(row) + "_0" + Byte.toString(col);
buttonName.setText("0");
}
}
}
private void btnUndoActionsActionPerformed(java.awt.event.ActionEvent evt) {
markbox_00_00.setText(Byte.toString(saveNumber[0][0]));
markbox_00_01.setText(Byte.toString(saveNumber[0][1]));
markbox_00_02.setText(Byte.toString(saveNumber[0][2]));
markbox_01_00.setText(Byte.toString(saveNumber[1][0]));
markbox_01_01.setText(Byte.toString(saveNumber[1][1]));
markbox_01_02.setText(Byte.toString(saveNumber[1][2]));
markbox_02_00.setText(Byte.toString(saveNumber[2][0]));
markbox_02_01.setText(Byte.toString(saveNumber[2][1]));
markbox_02_02.setText(Byte.toString(saveNumber[2][2]));
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
saveNumber[0][0] = Byte.parseByte(markbox_00_00.getText());
saveNumber[0][1] = Byte.parseByte(markbox_00_01.getText());
saveNumber[0][2] = Byte.parseByte(markbox_00_02.getText());
saveNumber[1][0] = Byte.parseByte(markbox_01_00.getText());
saveNumber[1][1] = Byte.parseByte(markbox_01_01.getText());
saveNumber[1][2] = Byte.parseByte(markbox_01_00.getText());
saveNumber[2][0] = Byte.parseByte(markbox_02_00.getText());
saveNumber[2][1] = Byte.parseByte(markbox_02_01.getText());
saveNumber[2][2] = Byte.parseByte(markbox_02_02.getText());
}
private void markbox_00_00ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_00.getText()))
markbox_00_00.setText("1");
else
markbox_00_00.setText("0");
}
private void markbox_00_01ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_01.getText()))
markbox_00_00.setText("1");
else
markbox_00_00.setText("0");
}
....
private void markbox_02_02ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_00.getText()))
markbox_02_02.setText("1");
else
markbox_02_02.setText("0");
}
In short: how can I make String a specific variable name of JButton for calling/accessing/editing for their properties?
Example:
buttonName = markbox_01_02;
buttonName.setText("2");
is equavalent to markbox_01_02.getText("2");
I really appreciate the help, thank you...
P.S. I use to make JFrame in NetBeans Design (just click and drag the objects in palette window like JPanel, JButton, etc., so I don't type the code manually except making my own logical Method).
You probably need to redo your program and rephrase your question because it's kind of unclear where you're stuck that's why I wrote this answer as a Community Wiki.
The following program creates a GridLayout for the board and add 2 JButtons below it which contain "Save" and "Undo" buttons.
Whenever you press a button it will change it's text to 0 or 1 depending on the previous state of the button, and "Undo" button will undo last clic the same way, if it was 0 it will become 1 and viceversa.
I guess you should read How to write an ActionListener before copy-pasting this example, understand what it says and try to understand how this program works.
The logic to "Save" button is up to you 'cause I'm not sure what you wanna do there and I'm not gonna write all the code for you. This is made only for you to get an idea on how to handle events.
Also, the logic to end the game is left to you for the same reasons as the "Save" button.
I wish I knew how to record my screen in Ubuntu and save as GIF but here's a screenshot on how this program looks like:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToe implements ActionListener {
JFrame frame;
JButton buttons[];
JPanel pane, buttonPane;
boolean pressed[];
JButton save, undo;
int n = -1;
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
if(e.getSource() == buttons[i]) {
pressed[i] = !pressed[i];
buttons[i].setText(pressed[i] ? "1" : "0");
n = i;
break;
}
}
}
public TicTacToe () {
frame = new JFrame("Tic Tac Toe Game");
buttons = new JButton[9];
pane = new JPanel(new GridLayout(3, 3));
pressed = new boolean[9];
buttonPane = new JPanel(new FlowLayout());
save = new JButton("Save");
undo = new JButton("Undo");
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("0");
pressed[i] = false;
}
for (JButton b : buttons) {
b.addActionListener(this);
pane.add(b);
}
undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (n == -1) {
return;
}
pressed[n] = !pressed[n];
buttons[n].setText(pressed[n] ? "1" : "0");
}
});
buttonPane.add(save);
buttonPane.add(undo);
frame.add(pane, BorderLayout.PAGE_START);
frame.add(buttonPane, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main (String args[]) {
new TicTacToe();
}
}
For this program, the JButton doesn't seem to show up unless you click the area where the JButton should be; the JFrame starts up blank. The moment you click the button, the respective code runs and the button finally shows up.
How do I get the buttons to show up upon starting the program?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/*
The Amazing BlackJack Advisory Tool by JoshK,HieuV, and AlvinC.
Prepare to be amazed :O
*/
public class BlckJackUI {
//main class, will contain the JFrame of the program, as well as all the buttons.
public static void main(String args[])
{
//Creating the JFrame
JFrame GUI = new JFrame("Blackjack Advisor");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(1300, 900);
GUI.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Hieu Vo\\Desktop\\Green Background.png")));
GUI.setVisible(true);
// Because each button needs to run through the Math class.
final Math math = new Math();
// The Ace Button:
ImageIcon Ace = new ImageIcon("/Users/computerscience2/Downloads/Ace.jpg");
JButton ace = new JButton(Ace);
ace.setSize(300, 100);
ace.setLocation(100, 100);
ace.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Automatically default the the Ace to 11, and if Bust, Ace becomes 1.
if (math.array.playerhandtotal <= 21)
{
math.cardvalue = math.cardvalue + 11;
}
else
{
math.cardvalue = math.cardvalue + 1;
}
math.array.clicktracker++;
math.calcResult();
JOptionPane.showMessageDialog(null,math.array.result);
}
});
GUI.add(ace);
ImageIcon Two = new ImageIcon("/Users/computerscience2/Downloads/2.jpg");
JButton two = new JButton(Two);
two.setSize(300, 100);
two.setLocation(100, 200);
two.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
/*
This generally repeats throughout the whole class, and the only
thing different is the changing cardvalue. When a button is pressed,
respective cardvalues are added into the playerhand ArrayList, and
totaled up to form playerhandtotal, which is a major factor in
bringing up the advice.
*/
math.cardvalue = math.cardvalue + 2;
math.array.clicktracker++;
math.calcResult();
JOptionPane.showMessageDialog(null,math.array.result);
}
});
GUI.add(two);
Et cetera, Et cetera... Just a bunch of the same stuff, more buttons coded the same exact way as JButton two, but with different value associated to them.
JButton start = new JButton("Start/Reset");
start.setSize(300, 100);
start.setLocation(500,500);
start.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
/*
The start button also acts like a reset button, and the concept is fairly
simple. If we reset all the important values to 0 or "null," then the
program acts as if it was just opened.
*/
Arrays array = new Arrays();
array.playerhand.clear();
array.dealer = 0;
math.array.starttracker++;
math.array.clicktracker = 0;
array.playerhandtotal = 0;
math.cardvalue = 0;
array.result = null;
JOptionPane.showMessageDialog(null,"Please select the card \nthat the dealer is showing :)");
}
});
GUI.add(start);
GUI.setLayout(null);
This is all in the same class, and I understand a layout would be nicer, but perhaps there's a way to fix this issue using what I have now?
The program starts blank because you are calling setVisible before you add components. Call setVisible after you add components (in the end of contructor) and it should work fine.
Also, avoid absolute positioning and call of set|Preferred|Minimum|MaximumSize methods for your components. Learn how to use layout managers.
Write GUI.validate(); after you add all the components to your frame. Any time you add something to a frame you have to validate it like this. Otherwise, you will get the behavior that you have described.
No. The problem is caused by the layout. Before adding anything to a JFrame or a JPanel which you want it to have an absolute position, you have to setLayout(null). Otherwise, you'll have unexpected behaviours all the time. I just figured it out by myself after three hours of experimenting; suddenly, I connected your post with other different subject, and it worked, but this isn't well explained on the Internet yet.
I am creating a java GUI which is a fortune teller. The GUI will spit out one of twelve fortunes every time you click the "get my fortune" button, the strings will never repeat back to back, can can repeat later after other strings have gone before it. I have made already for the most part. But now I am having some trouble creating the while loops to display the strings without repeating. I have looked at my book which didn't really help. If you guys could point me in the right direction,it would be much appreciated. Thanks!
I entered all of the code so you can see the variables used. But my question starts at class RndButtonListener.
package FortuneTellerRunner;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
*
* #author a3cal_000
*/
class FortuneTellerFrame extends JFrame
{
final private JPanel mainPnl, titlePnl, displayPnl, buttonPnl, imagePnl;
final private JButton quitBtn, rndBtn;
final private JLabel titleLbl, iconLbl;
final private JTextArea displayTa;
final private JScrollPane scroller;
public String[] fortune = new String [12];
int newIndex, oldIndex;
private static final int HEIGHT = 250;
private static final int WIDTH = 450;
public FortuneTellerFrame()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPnl = new JPanel();
mainPnl.setLayout(new BorderLayout());
displayPnl = new JPanel();
buttonPnl = new JPanel();
titlePnl = new JPanel();
ImageIcon icon = new ImageIcon("FortuneTellerIcon.JPEG");
iconLbl = new JLabel(icon);
titleLbl = new JLabel("Fortune Teller!");
displayTa = new JTextArea();
imagePnl = new JPanel();
scroller = new JScrollPane();
// Create the layout of the title panel
titlePnl.setLayout(new GridLayout(2,1));
add(mainPnl);
// Set the label to the panel.
titlePnl.add(titleLbl);
titlePnl.add(iconLbl);
// add the panel to the main panel.
mainPnl.add(titlePnl, BorderLayout.NORTH);
mainPnl.add(scroller, BorderLayout.CENTER);
mainPnl.add(displayTa, BorderLayout.CENTER);
// Create the "Get my fortune button.
rndBtn = new JButton("Get My Fortune!");
quitBtn = new JButton("Quit");
// Add the buttons to the buttonPnl in grid layout.
buttonPnl.add(rndBtn);
buttonPnl.add(quitBtn);
// Create the grid layout for the button panel.
buttonPnl.setLayout( new GridLayout(1, 2));
// Add the button panel to the grid layout, South.
mainPnl.add(buttonPnl, BorderLayout.SOUTH);
ActionListener listener = new RndButtonListener();
rndBtn.addActionListener(listener);
quitBtn.addActionListener(listener);
}
class RndButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
fortune[0] = "He who throws dirt is losing ground.";
fortune[1] = "You will find the love of your life in food.";
fortune[2] = "Do or do not, there is no try.";
fortune[3] = "Tomorrow is a better day to try anything of importance.";
fortune[4] = "Life's not about how hard you can hit, but how hard you can get hit and keep moving forward.";
fortune[5] = "You can't be late until you show up.";
fortune[6] = "If you think things can't get worse it's probably only because you lack sufficent imagination.";
fortune[7] = "If youre at the top it means you have further to fall.";
fortune[8] = "Even in last place, youre still in the race.";
fortune[9] = "The road to riches is paved on the failures of others.";
fortune[10] = "If you feel like your going no where, get off the treadmill.";
fortune[11] = "Thinking about going to the gym is just as good as going.";
Random rnd = new Random(fortune.length);
do
{
newIndex = rnd.nextInt(fortune.length);
}
while(newIndex == oldIndex);
do
{
System.out.println(fortune[newIndex]);
displayTa.append(fortune[newIndex] + "||");
displayTa.updateUI();
mainPnl.updateUI();
oldIndex = newIndex;
}
while(newIndex != oldIndex);
class QuitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
}
}
}
}
The basic problem is you are re-creating the Random with the same seed each time, which is generally creating the same random sequence over and over again.
Instead try using...
do {
newIndex = (int) Math.round(Math.random() * (fortune.length - 1));
} while (newIndex == oldIndex);
You also don't need the second loop, it's just clutter that confuses the situation.
You may also find that...
displayTa.append(fortune[newIndex] + "\n");
produces nicer output (IMHO)
You may also wish to take a look at How to use Scroll Panes
Your program run fine, but this is a problem, fortune.length is a random seed which return me only 6 and 8 when I later called Random.nextInt().
Random rnd = new Random(fortune.length);
Do it this way
Random rnd = new Random();
and also consider the formatting solution given by MadProgrammer.
Random() gives you same number pattern. Try Random(System.currentTimeMillis()). It uses current time as seed, so you can get real random numbers.
I did something similar to this just today, so let's see if I can remember... I made an ArrayList of type int of how many items I had (fortunes)
ArrayList<Integer> fortuneSeq = new ArrayList<Integer>();
Then add in some numbers starting from 0 to code for the fortunes.
for(int i = 0; i < fortune.length; i++) {
fortuneSeq.add(i);
}
Then I used the shuffle() method from the Collections class to randomize the list.
Collections.shuffle(fortuneSeq);
After that, just loop through to access the fortunes.
for(int i = 0; i < fortune.length; i++) {
System.out.println(fortune[fortuneSeq.get(i)]);
//...
}
Edit: Silly autocorrect, you don't like programmers.
Edit: Fixed some furtunes instead of fortunes and fixed println statement.
I'm currently programming a Calendar in Java. The Calendar itself fills out perfectly fine with the Month and Year being displayed in JComboBoxes above the grid below it. The Grid itself is full of empty JLabels or JButtons (for the days of the month). The JComboBoxes are linked to ActionListeners, which detect the user changing information (confirmed by System.out.print statements). However, I cannot find a way to "redraw" the JPanel after this occurs. The method being called completely creates a new JPanel and adds in the new JLabels/JButtons, but nothing on the JFrame is updated after this happens. I have attempted using both the repaint and revalidate on the whole JPanel (which includes the JComboBoxes and the grid below it in a BorderLayout), the JPanel with only the grid, and the JFrame, but nothing happens. Does anyone have any ideas what is wrong?
// This code is within the build() method that builds the GUI.
// This method adds the centerPanel into the mainPanel
yearChoice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int i = yearChoice.getSelectedIndex();
if (i >= 0) {
yy = Integer.parseInt(yearChoice.getSelectedItem()
.toString());
//System.out.println("Year=" + yy);
compute();
}
}
});
private void compute(){
elements = new int[6][7];
// OMITTED is the code that determines whether a cell in the array should be an empty
// JLabel or a JButton. This code is based on the Calendar, and does work properly,
// but I can't figure out how to get the new Month/Year to show up on a new Panel
centerPanel = new JPanel(new GridLayout(7, 7));
JLabel sunday = new JLabel("S"),
monday = new JLabel("M"),
tuesday = new JLabel("T"),
wednesday = new JLabel("W"),
thursday = new JLabel("Th"),
friday = new JLabel("F"),
saturday = new JLabel("S");
centerPanel.add(sunday);
centerPanel.add(monday);
centerPanel.add(tuesday);
centerPanel.add(wednesday);
centerPanel.add(thursday);
centerPanel.add(friday);
centerPanel.add(saturday);
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
if(elements[i][j] == -1){
centerPanel.add(new JLabel(" "));
}else{
centerPanel.add(new JButton("" + elements[i][j]));
}
}
}
// Here is where I attempt to repaint the centerPanel for the JPanel, but it
// doesn't work
}
The method being called completely creates a new JPanel and adds in the
new JLabels/JButtons, but nothing on the JFrame is updated after this
happens. I have attempted using both the repaint and revalidate on the
whole JPanel (which includes the JComboBoxes and the grid below it in
a BorderLayout), the JPanel with only the grid, and the JFrame, but
nothing happens. Does anyone have any ideas what is wrong?
you call another JPanel for (re)validate & repaint
updates are out of visible rectangle on the screen, put JPanel to the JScrollPane
if updates are out of visible rectangle you can to call JFrame.pack(), but in this case JFrame will be changed its Dimension on the screen
The method being called completely creates a new JPanel and adds in
the new JLabels/JButtons, but nothing on the JFrame is updated after
this happens.
for why reason you re_create a JPanel, create that once time and to play with setVisible(false/true)
don't re_create a JPanel, put these (two or three JPanels) to the CardLayout, then any changes will be only switch betweens views
for better help sooner post an SSCCE, short, runnable, compilable
code example