I'm writing a simple Trivia game and I ran into a problem where the question string won't display
In my frame I'm using border layout with "new game" and "end game" on the bottom (South) and my Trivia panel in the center.
The Trivia panel is made of grid layout with 2 rows and 1 column with the 4 answers on the bottom half and on the upper half I used another panel with border layout with the question string in the center and the score in the east.
It should look like this:
However all of the components display except for the question string.
My paintComponent is:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
g.drawString(tf,0,0);
}
where tf is my string and my Trivia panel code is:
public TriviaPanel(){
score = 0;
scoreString = new JTextField();
scoreString.setFont(font);
questionPanel = new JPanel();
questionPanel.setLayout(new BorderLayout());
questionPanel.add(scoreString,BorderLayout.EAST);
this.setLayout(new GridLayout(2,1));
pool = null;
try {
pool = new Pool();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
question = pool.getQuestion();
String[] answers = question.shuffle();
tf = question.getQuestion();
this.add(questionPanel);
answersPanel = new JPanel();
answersPanel.setLayout(new GridLayout(2,2));
buttons = new JButton[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i] = new JButton(answers[i]);
answersPanel.add(buttons[i]);
buttons[i].addActionListener(lis);
}
this.add(answersPanel);
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
}
where pool is used to hold my pool of questions.
When I debugged the code I see the tf string being updated to the question string but it won't display.
Is it because of the coordinates?
Any insights would be greatly appreciated.
[Edit] Although not finished but full code below:
import java.util.Arrays;
import java.util.Collections;
public class Question {
private final int NUM_OF_ANSWERS = 4;
private String question;
private String[] answers = new String[NUM_OF_ANSWERS];
private final int CORRECT_ANSWER = 0;
public Question(String qu, String an, String dm1, String dm2, String
dm3){
question = qu;
answers[0] = an;
answers[1] = dm1;
answers[2] = dm2;
answers[3] = dm3;
}
public String getCorrectAnswer() {
return answers[CORRECT_ANSWER];
}
public String getQuestion(){
return question;
}
public String[] getAnswers(){
return answers;
}
public String toString(){
String str = question;
for (int i = 0; i<4; i++)
str+=" "+answers[i];
str+="\n";
return str;
}
public String[] shuffle(){
String[] shuffled = new String[NUM_OF_ANSWERS];
for (int i=0;i<NUM_OF_ANSWERS;i++)
shuffled[i]=answers[i];
Collections.shuffle(Arrays.asList(shuffled));
return shuffled;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
public class Pool {
private ArrayList<Question> questions = new ArrayList<>();
private Scanner input = new Scanner(new File("src/trivia.txt"));
private static int iterator = 0;
public Pool() throws FileNotFoundException {
while (input.hasNext()){
String q = input.nextLine();
String a = input.nextLine();
String d1 = input.nextLine();
String d2 = input.nextLine();
String d3 = input.nextLine();
Question question = new Question(q,a,d1,d2,d3);
questions.add(question);
}
Collections.shuffle(questions);
//System.out.println(questions);
}
public Question getQuestion(){
Question q = questions.get(iterator);
iterator++;
return q;
}
public int getSize(){
return questions.size();
}
public static int getIterator() {
return iterator;
}
}
import javax.swing.*;
import java.awt.*;
public class GameFrame extends JFrame {
private JButton restart, finish;
private JPanel buttons;
public GameFrame(){
super("Trivia");
TriviaPanel tp = new TriviaPanel();
this.setLayout(new BorderLayout());
this.add(tp,BorderLayout.CENTER);
restart = new JButton("New game");
finish = new JButton("End game");
buttons = new JPanel();
buttons.add(restart);
buttons.add(finish);
this.add(buttons,BorderLayout.SOUTH);
this.setSize(1000,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
GameFrame gf = new GameFrame();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.util.concurrent.TimeUnit;
public class TriviaPanel extends JPanel {
private TimerListener tl = new TimerListener();
private Timer timer = new Timer(10000,tl);
private static int score;
private JTextField scoreString;
private final int CORRECT = 10, INCORRECT = 5;
private JButton[] buttons;
private Pool pool;
private Question question;
private JButton pressed;
private final int NUM_OF_ANSWERS = 4;
private Listener lis = new Listener();
//private JPanel questionPanel;
private JPanel answersPanel;
private String tf;
private Font font = new Font("Serif",Font.BOLD,24);
private JTextField tf2 = new JTextField();
private QuestionPanel questionPanel;
public TriviaPanel(){
score = 0;
scoreString = new JTextField();
scoreString.setFont(font);
questionPanel = new QuestionPanel();
//questionPanel.setLayout(new BorderLayout());
//questionPanel.add(scoreString,BorderLayout.EAST);
this.setLayout(new GridLayout(2,1));
pool = null;
try {
pool = new Pool();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
question = pool.getQuestion();
String[] answers = question.shuffle();
tf = question.getQuestion();
//tf2.setText(question.getQuestion());
//questionPanel.add(tf2,BorderLayout.CENTER);
this.add(questionPanel);
answersPanel = new JPanel();
answersPanel.setLayout(new GridLayout(2,2));
buttons = new JButton[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i] = new JButton(answers[i]);
answersPanel.add(buttons[i]);
buttons[i].addActionListener(lis);
}
this.add(answersPanel);
timer.start();
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
questionPanel.repaint();
}
private void next(){
Question q = pool.getQuestion();
question=q;
tf = q.getQuestion();
String[] answers = q.shuffle();
for (int i = 0; i < NUM_OF_ANSWERS; i++)
buttons[i].setText(answers[i]);
}
private void gameOver(){
JOptionPane.showConfirmDialog(null,
"Score: "+score, "Select an Option...", JOptionPane.YES_NO_CANCEL_OPTION);
}
private void check(String guess) {
timer.stop();
String answer = question.getCorrectAnswer();
if (guess.equals(answer)) {
score += CORRECT;
tf = "Correct!!!";
} else {
score -= INCORRECT;
tf = "Wrong answer";
}
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
repaint();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class QuestionPanel extends JPanel{
public QuestionPanel(){
this.setLayout(new BorderLayout());
this.add(scoreString,BorderLayout.EAST);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
g.drawString(tf,0,200);
}
}
private class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
pressed = (JButton) e.getSource();
String guess = pressed.getText();
check(guess);
if (pool.getIterator() < pool.getSize()) {
timer.restart();
next();
}
else
gameOver();
}
}
private class TimerListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
score-=INCORRECT;
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
repaint();
timer.restart();
next();
}
}
}
Start by getting rid of
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
questionPanel.repaint();
}
Seriously this is just dangerous and could set you for a endless loop which will consume your CPU cycles
Next, I modified your QuestionPanel so the text is actually rendered somewhere within the realms of probability ...
private class QuestionPanel extends JPanel {
public QuestionPanel() {
this.setLayout(new BorderLayout());
this.add(scoreString, BorderLayout.EAST);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g.drawString(tf, 10, y);
}
}
But seriously, why aren't you just using a JLabel?
Now, any time tf changes, you need to call QuestionPanel's repaint method.
So, that's in the next and check(String) methods.
And finally (for now), you should never, ever do...
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
inside the context of the event dispatching thread. This is stopping the repaints from been processed, so, for one whole second, nothing will change.
If you want to stop the user for a second, disable the buttons and/or other controls and use another Swing Timer (for simplicity)
This is demonstrated in this self contained, compilable and runnable example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GameFrame frame = new GameFrame();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class GameFrame extends JFrame {
private JButton restart, finish;
private JPanel buttons;
public GameFrame() {
super("Trivia");
TriviaPanel tp = new TriviaPanel();
this.setLayout(new BorderLayout());
this.add(tp, BorderLayout.CENTER);
restart = new JButton("New game");
finish = new JButton("End game");
buttons = new JPanel();
buttons.add(restart);
buttons.add(finish);
this.add(buttons, BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static class TriviaPanel extends JPanel {
// private TimerListener tl = new TimerListener();
// private Timer timer = new Timer(10000, tl);
private static int score;
private JTextField scoreString;
private final int CORRECT = 10, INCORRECT = 5;
private JButton[] buttons;
private Pool pool;
private Question question;
private JButton pressed;
private final int NUM_OF_ANSWERS = 4;
private Listener lis = new Listener();
//private JPanel questionPanel;
private JPanel answersPanel;
private String tf;
private Font font = new Font("Serif", Font.BOLD, 24);
private JTextField tf2 = new JTextField();
private QuestionPanel questionPanel;
public TriviaPanel() {
score = 0;
scoreString = new JTextField();
scoreString.setFont(font);
questionPanel = new QuestionPanel();
//questionPanel.setLayout(new BorderLayout());
//questionPanel.add(scoreString,BorderLayout.EAST);
this.setLayout(new GridLayout(2, 1));
pool = null;
try {
pool = new Pool();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
question = pool.getQuestion();
String[] answers = question.shuffle();
tf = question.getQuestion();
//tf2.setText(question.getQuestion());
//questionPanel.add(tf2,BorderLayout.CENTER);
this.add(questionPanel);
answersPanel = new JPanel();
answersPanel.setLayout(new GridLayout(2, 2));
buttons = new JButton[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i] = new JButton(answers[i]);
answersPanel.add(buttons[i]);
buttons[i].addActionListener(lis);
}
this.add(answersPanel);
// timer.start();
scoreString.setText("Score: " + score + "/" + pool.getIterator() * CORRECT);
}
// #Override
// protected void paintComponent(Graphics g) {
// super.paintComponent(g);
// questionPanel.repaint();
// }
private void next() {
Question q = pool.getQuestion();
question = q;
tf = q.getQuestion();
String[] answers = q.shuffle();
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i].setText(answers[i]);
}
questionPanel.repaint();
}
private void gameOver() {
JOptionPane.showConfirmDialog(null,
"Score: " + score, "Select an Option...", JOptionPane.YES_NO_CANCEL_OPTION);
}
private void check(String guess) {
// timer.stop();
String answer = question.getCorrectAnswer();
if (guess.equals(answer)) {
score += CORRECT;
tf = "Correct!!!";
} else {
score -= INCORRECT;
tf = "Wrong answer";
}
questionPanel.repaint();
scoreString.setText("Score: " + score + "/" + pool.getIterator() * CORRECT);
// OH GOD THIS IS A BAD IDEA!
// try {
// TimeUnit.SECONDS.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Timer timer = (Timer) e.getSource();
timer.stop();
// Personally, I'd use a listener, but this will do
afterCheckDelay();
}
});
timer.start();
}
protected void afterCheckDelay() {
if (pool.getIterator() < pool.getSize()) {
//timer.restart();
next();
} else {
gameOver();
}
}
private class QuestionPanel extends JPanel {
public QuestionPanel() {
this.setLayout(new BorderLayout());
this.add(scoreString, BorderLayout.EAST);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g.drawString(tf, 10, y);
}
}
private class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
pressed = (JButton) e.getSource();
String guess = pressed.getText();
check(guess);
}
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// timer.stop();
// score -= INCORRECT;
// scoreString.setText("Score: " + score + "/" + pool.getIterator() * CORRECT);
// repaint();
// timer.restart();
// next();
}
}
}
public static class Pool {
private ArrayList<Question> questions = new ArrayList<>();
// private Scanner input = new Scanner(new File("src/trivia.txt"));
private static int iterator = 0;
public Pool() throws FileNotFoundException {
Question question = new Question("Why am I doing this", "Because I'm awesome", "You feel for the trick", "You have no idea", "To much caffine");
questions.add(question);
// while (input.hasNext()) {
// String q = input.nextLine();
// String a = input.nextLine();
// String d1 = input.nextLine();
// String d2 = input.nextLine();
// String d3 = input.nextLine();
// Question question = new Question(q, a, d1, d2, d3);
// questions.add(question);
// }
Collections.shuffle(questions);
//System.out.println(questions);
}
public Question getQuestion() {
Question q = questions.get(iterator);
iterator++;
return q;
}
public int getSize() {
return questions.size();
}
public static int getIterator() {
return iterator;
}
}
public static class Question {
private final int NUM_OF_ANSWERS = 4;
private String question;
private String[] answers = new String[NUM_OF_ANSWERS];
private final int CORRECT_ANSWER = 0;
public Question(String qu, String an, String dm1, String dm2, String dm3) {
question = qu;
answers[0] = an;
answers[1] = dm1;
answers[2] = dm2;
answers[3] = dm3;
}
public String getCorrectAnswer() {
return answers[CORRECT_ANSWER];
}
public String getQuestion() {
return question;
}
public String[] getAnswers() {
return answers;
}
public String toString() {
String str = question;
for (int i = 0; i < 4; i++) {
str += " " + answers[i];
}
str += "\n";
return str;
}
public String[] shuffle() {
String[] shuffled = new String[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
shuffled[i] = answers[i];
}
Collections.shuffle(Arrays.asList(shuffled));
return shuffled;
}
}
}
Related
So I've been making a game for someone's birthday, I finally finished, but I'm having issues exporting it into a runnable jar file. What the game is is similar to "Who wants to be a millionaire", so it opens a window asking the contestant their name, then it goes on to ask the questions. At the end, it opens a letter that I wrote to them.
Now for the actual issue. I run the project in Eclipse and it works like a charm. However when I run it as a jar, I get the name prompt, then it all closes down. I don't get any error messages that I can see. I've tried running it through command prompt to see if anything would happen but no dice. Any help would be greatly appreciated with this!
EDIT: Below is my Start class and my JGame class:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class start {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy/MM/dd");
Date bday = sdformat.parse("2020/02/01");
LocalDate now = LocalDate.now();
String toda = dtf.format(now);
Date today = sdformat.parse(toda);
if (today.after(bday)) {
new JWelcome();
} else {
new JWrongDate();
}
}
}
JGame:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class JGame extends JWin {
private static final long serialVersionUID = 1L;
private JLabel jlabel;
private JWelcome jwelcome;
private JGWindowListener jgwl;
private JGMBar jgmb;
private JPanel northpanel;
private JPanel centerpanel;
private JPanel eastpanel;
private JPanel jsouthpanel;
private JButton jbutton_A;
private JButton jbutton_B;
private JButton jbutton_C;
private JButton jbutton_D;
private JButton jbfifty_fifty;
private JTArea jtarea;
private JGameListener jgml;
private JFile jfile;
private JFile jfile_A;
private JFile jfile_B;
private JFile jfile_C;
private JFile jfile_D;
private JFile jsolution;
private String answer_A;
private String answer_B;
private String answer_C;
private String answer_D;
private String solution;
// private JLabel jwon;
private int index;
public JGame(JWelcome jwelcome) throws ParseException {
super();
this.jwelcome = jwelcome;
jgwl = new JGWindowListener(this);
jgml = new JGameListener(this);
jgmb = new JGMBar(this);
setTitle("Brigit's Birthday Game");
setSize(800, 300);
jlabel = new JLabel("Hello " + jwelcome.getJTArea().getText() + "! Welcome to your birthday game!");
jtarea = new JTArea("Question");
jfile = new JFile();
jfile_A = new JFile();
jfile_B = new JFile();
jfile_C = new JFile();
jfile_D = new JFile();
jsolution = new JFile();
index = 0;
jtarea.setText(jfile.loadQuestions("Questions.txt", index));
Rectangle r = new Rectangle();
jtarea.scrollRectToVisible(r);
getContentPane().setLayout(new BorderLayout());
// jwon = new JLabel("Select the correct answer");
northpanel = new JPanel();
northpanel.setLayout(new FlowLayout());
northpanel.add(jlabel);
northpanel.setBackground(Color.magenta);
getContentPane().add((BorderLayout.NORTH), northpanel);
addWindowListener(jgwl);
setJMenuBar(jgmb);
centerpanel = new JPanel();
centerpanel.setLayout(new FlowLayout());
centerpanel.add(jtarea);
centerpanel.setBackground(Color.magenta);
getContentPane().add(BorderLayout.CENTER, centerpanel);
jbfifty_fifty = new JButton("50:50");
jbfifty_fifty.addActionListener(jgml);
eastpanel = new JPanel();
eastpanel.setLayout(new FlowLayout());
eastpanel.add(jbfifty_fifty);
eastpanel.setBackground(Color.magenta);
getContentPane().add(BorderLayout.EAST, eastpanel);
// jfile_A.loadQuestions("Answers_A.txt", 0
answer_A = (String) jfile_A.loadQuestions("Answers_A.txt", index);
answer_B = (String) jfile_B.loadQuestions("Answers_B.txt", index);
answer_C = (String) jfile_C.loadQuestions("Answers_C.txt", index);
answer_D = (String) jfile_D.loadQuestions("Answers_D.txt", index);
solution = (String) jsolution.loadQuestions("Solutions.txt", index);
jbutton_A = new JButton("A: ");
jbutton_B = new JButton("B: ");
jbutton_C = new JButton("C: ");
jbutton_D = new JButton("D: ");
jbutton_A.setText("A: " + answer_A);
jbutton_B.setText("B: " + answer_B);
jbutton_C.setText("C: " + answer_C);
jbutton_D.setText("D: " + answer_D);
jsouthpanel = new JPanel();
jsouthpanel.setLayout(new FlowLayout());
jbutton_A.addActionListener(jgml);
jbutton_B.addActionListener(jgml);
jbutton_C.addActionListener(jgml);
jbutton_D.addActionListener(jgml);
jsouthpanel.add(jbutton_A);
jsouthpanel.add(jbutton_B);
jsouthpanel.add(jbutton_C);
jsouthpanel.add(jbutton_D);
jsouthpanel.setBackground(Color.BLACK);
jsouthpanel.setForeground(Color.BLACK);
getContentPane().add(BorderLayout.SOUTH, jsouthpanel);
setVisible(true);
}
public JButton getJButton_A() {
return jbutton_A;
}
public JButton getJButton_B() {
return jbutton_B;
}
public JButton getJButton_C() {
return jbutton_C;
}
public JButton getJButton_D() {
return jbutton_D;
}
public JFile getFile_A() {
return jfile_A;
}
public JFile getFile_B() {
return jfile_B;
}
public JFile getFile_C() {
return jfile_C;
}
public JFile getFile_D() {
return jfile_D;
}
public String getAnswer_A() {
return answer_A;
}
public String getAnswer_B() {
return answer_B;
}
public String getAnswer_C() {
return answer_C;
}
public String getAnswer_D() {
return answer_D;
}
public String getSolution() {
return solution;
}
public JPanel getSouthPanel() {
return jsouthpanel;
}
public JFile getJFile() {
return jfile;
}
public JTArea getJTArea() {
return jtarea;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public JLabel getJLabel() {
return jlabel;
}
public void setJLabel(JLabel jl) {
jlabel = jl;
}
public JButton getFifty() {
return jbfifty_fifty;
}
int nextQuestion() throws IOException {
try {
index = index + 1;
if (index >= 20) {
File file = new File("letter.docx");
Desktop desktop = Desktop.getDesktop();
if (file.exists())
desktop.open(file);
setIndex(0);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: " + e);
}
jtarea.setText(jfile.loadQuestions("Questions.txt", index));
answer_A = (String) jfile_A.loadQuestions("Answers_A.txt", index);
answer_B = (String) jfile_B.loadQuestions("Answers_B.txt", index);
answer_C = (String) jfile_C.loadQuestions("Answers_C.txt", index);
answer_D = (String) jfile_D.loadQuestions("Answers_D.txt", index);
solution = (String) jsolution.loadQuestions("Solutions.txt", index);
jbutton_A.setText("A: " + answer_A);
jbutton_B.setText("B: " + answer_B);
jbutton_C.setText("C: " + answer_C);
jbutton_D.setText("D: " + answer_D);
return index;
}
void play() {
jlabel.setText("Select one of the four answers");
jbutton_A.addActionListener(jgml);
jbutton_B.addActionListener(jgml);
jbutton_C.addActionListener(jgml);
jbutton_D.addActionListener(jgml);
}
void pause() {
jlabel.setText("pause");
jbutton_A.removeActionListener(jgml);
jbutton_B.removeActionListener(jgml);
jbutton_C.removeActionListener(jgml);
jbutton_D.removeActionListener(jgml);
jsouthpanel.setBackground(Color.BLACK);
}
public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(JGame.class.getResource("baloons.jpeg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
void close() {
dispose();
setVisible(false);
System.exit(0);
}
}
EDIT 2:
Here is the command used to run my game:
C:\Program Files\Java\jdk-13.0.2\bin\javaw.exe -Dfile.encoding=Cp1252 -classpath "C:\Users\neilp\eclipse-workspace\Brigit Birthday Quiz\bin" start
Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
This is a simple calculator where the user can type out the calculation and hit enter, and the calculator would determine if it is a valid calculation or not. If it is a valid calculation, the calculation is carried out. If not, an error message is written to the screen.
The calculation is carried out part isn't finished.
Can someone suggest a solutions to the getAnswer() method.
It would be very much appreciated.
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
#SuppressWarnings("serial")
public class Calculator extends JFrame{
private interface CalculatorInterface {
public void writeToScreen(String text);
public void clearScreen();
public String getScreenText();
}
private class CalculatorPanel extends JPanel implements CalculatorInterface {
private class NumberPanel extends JPanel implements CalculatorInterface {
private static final int NUMTOTAL = 10;
private CalculatorPanel calcPanel;
private JButton[] numButtons;
public NumberPanel(CalculatorPanel calcPanel) {
this.calcPanel = calcPanel;
buildLayout();
addButtons();
}
private void buildLayout() {
this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
GridLayout layout = new GridLayout(4,3);
layout.setHgap(1);
layout.setVgap(1);
this.setLayout(new GridLayout(4,3));
}
private void addButtons() {
numButtons = new JButton[NUMTOTAL];
for(int i = numButtons.length -1; i >= 0 ; i--) {
numButtons[i] = new JButton("" + i);
numButtons[i].setPreferredSize(new Dimension(60,40));
numButtons[i].setFont(new Font("Sans serif", Font.PLAIN, 18));
numButtons[i].addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)e.getSource()).getText().trim();
if(getScreenText().equals("Invalid Calc")) {
clearScreen();
writeToScreen(text);
}else {
writeToScreen(text);
}
}
});
this.add(numButtons[i]);
}
}
#Override
public void writeToScreen(String text) {
calcPanel.writeToScreen(text);
}
#Override
public void clearScreen() {
calcPanel.clearScreen();
}
#Override
public String getScreenText() {
return calcPanel.getScreenText();
}
}
private class OperPanel extends JPanel implements CalculatorInterface {
private static final int ADD = 0;
private static final int SUB = 1;
private static final int MULT = 2;
private static final int DIV = 3;
private static final int OPENB = 4;
private static final int CLOSEB = 5;
private static final int CLEAR = 6;
private static final int EQL = 7;
private static final int OPERTOTAL = 8;
private CalculatorPanel calcPanel;
private JButton[] operButtons;
public OperPanel(CalculatorPanel calcPanel) {
this.calcPanel = calcPanel;
buildLayout();
addButtons();
}
private void buildLayout() {
GridLayout layout = new GridLayout(4,1);
layout.setHgap(1);
layout.setVgap(1);
this.setLayout(new GridLayout(4,1));
}
private void addButtons() {
operButtons = new JButton[OPERTOTAL];
operButtons[ADD] = makeButton(ADD, "+");
operButtons[SUB] = makeButton(SUB, "-");
operButtons[MULT] = makeButton(MULT, "*");
operButtons[DIV] = makeButton(DIV, "/");
operButtons[CLEAR] = makeButton(CLEAR, "CL");
operButtons[EQL] = makeButton(EQL, "=");
operButtons[OPENB] = makeButton(OPENB, "(");
operButtons[CLOSEB] = makeButton(CLOSEB, ")");
for(JButton button: operButtons) {
this.add(button);
}
}
private JButton makeButton(int index, String label) {
operButtons[index] = new JButton(label);
operButtons[index].addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)e.getSource()).getText();
if(text.equals("=")) {
String screenText = getScreenText();
clearScreen();
try {
writeToScreen(getAnswer(screenText));
}catch(Exception excep) {
writeToScreen("Invalid Calc");
}
}else if(text.equals("CL")) {
clearScreen();
}else {
writeToScreen(text);
}
}
});
return operButtons[index];
}
private String getAnswer(String text) throws Exception {
/*I'm trying to solve for any input by the user e.g
*(the stuff in square brackets represents what is displayed
* on the screen:.
*[1+1] (hits equals) [2]
*[1+2-3] (hits equals) [0]
*[1+2*3] (hits equals) [7]
*[10*(14+1/2)] (hits equals) [145]
*/
throw new Exception();
}
#Override
public String getScreenText() {
return calcPanel.getScreenText();
}
#Override
public void clearScreen() {
calcPanel.clearScreen();
}
#Override
public void writeToScreen(String text) {
calcPanel.writeToScreen(text);
}
}
private NumberPanel numPanel;
private OperPanel operPanel;
private JTextField calcScreen;
public CalculatorPanel(JTextField calcScreen) {
this.calcScreen = calcScreen;
buildNumPanel();
buildOperPanel();
buildCalcPanel();
}
private void buildNumPanel() {
this.numPanel = new NumberPanel(this);
}
private void buildOperPanel() {
this.operPanel = new OperPanel(this);
}
private void buildCalcPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.add(numPanel);
this.add(operPanel);
}
#Override
public void writeToScreen(String text) {
calcScreen.setText(getScreenText() + text);
}
#Override
public String getScreenText() {
return calcScreen.getText();
}
#Override
public void clearScreen() {
calcScreen.setText("");
}
}
private JPanel mainPanel;
private JTextField calcScreen;
private CalculatorPanel calcPanel;
public Calculator() {
buildScreen();
buildCalcPanel();
buildMainPanel();
buildCalculator();
}
private void buildScreen() {
this.calcScreen = new JTextField();
this.calcScreen.setPreferredSize(new Dimension(150,50));
this.calcScreen.setHorizontalAlignment(JTextField.CENTER);
this.calcScreen.setFont(new Font("Sans serif", Font.PLAIN, 30));
}
private void buildCalcPanel() {
this.calcPanel = new CalculatorPanel(this.calcScreen);
}
private void buildMainPanel() {
this.mainPanel = new JPanel();
this.mainPanel.setBorder(new EmptyBorder(10,10,10,10));
this.mainPanel.setLayout(new BoxLayout(this.mainPanel, BoxLayout.Y_AXIS));
this.mainPanel.add(calcScreen);
this.mainPanel.add(calcPanel);
}
private void buildCalculator() {
this.add(mainPanel);
this.setTitle("Calculator");
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Calculator calc = new Calculator();
}
}
How can I check to see if a string is a valid calculation for a simple calculator?
Edit 1: Fixed a silly bug in the makeButton() method were I passed in the text of the button to be verified instead of the text on screen. (I'm an idiot.)
Edit 2: Removed the isValid(String text) from the code and make it so the getAnswer() method just threw an exception if input is not a valid calculation.
As well mentioned in a previous StackOverflow answer (Evaluating a math expression given in string form), you could use Javascript's ScriptEngine to calculate expressions based on strings that you would retrieve from the Text Field. Place it in a try-catch block first to see if there's an error in the expression. In the catch block, set the variable storing whether its a valid expression or not to false.
boolean validExpression = true;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String input = textField.getText() // Modify this to whatever variable you have assigned to your text field
try {
System.out.println(engine.eval(foo));
}
catch (ScriptException e) {
validExpression = false;
System.out.println("Invalid Expression");
}
Make sure you include the following imports:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
Although you could try to implement Shunting-Yard Algorithm or another arithmetic parser, this is simply a way more pragmatic solution.
Another problem, same program:
The following is MainGUI.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MainGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 4149825008429377286L;
private final double version = 8;
public static int rows;
public static int columns;
private int totalCells;
private MainCell[] cell;
public static Color userColor;
JTextField speed = new JTextField("250");
Timer timer = new Timer(250,this);
String generationText = "Generation: 0";
JLabel generationLabel = new JLabel(generationText);
int generation = 0;
public MainGUI(String title, int r, int c)
{
rows = r;
columns = c;
totalCells = r*c;
System.out.println(totalCells);
cell = new MainCell[totalCells];
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Timer set up
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.setActionCommand("timer");
//set up menu bar
JMenuBar menuBar = new JMenuBar();
JMenu optionsMenu = new JMenu("Options");
JMenu aboutMenu = new JMenu("About");
menuBar.add(optionsMenu);
menuBar.add(aboutMenu);
JMenuItem helpButton = new JMenuItem("Help!");
helpButton.addActionListener(this);
helpButton.setActionCommand("help");
aboutMenu.add(helpButton);
JMenuItem aboutButton = new JMenuItem("About");
aboutButton.addActionListener(this);
aboutButton.setActionCommand("about");
aboutMenu.add(aboutButton);
JMenuItem colorSelect = new JMenuItem("Select a Custom Color");
colorSelect.addActionListener(this);
colorSelect.setActionCommand("colorSelect");
optionsMenu.add(colorSelect);
JMenuItem sizeChooser = new JMenuItem("Define a Custom Size");
sizeChooser.addActionListener(this);
sizeChooser.setActionCommand("sizeChooser");
optionsMenu.add(sizeChooser);
//Create text field to adjust speed and its label
JPanel speedContainer = new JPanel();
JLabel speedLabel = new JLabel("Enter the speed of a life cycle (in ms):");
speedContainer.add(speedLabel);
speedContainer.add(speed);
speedContainer.add(generationLabel);
Dimension speedDim = new Dimension(100,25);
speed.setPreferredSize(speedDim);
//Create various buttons
JPanel buttonContainer = new JPanel();
JButton randomizerButton = new JButton("Randomize");
randomizerButton.addActionListener(this);
randomizerButton.setActionCommand("randomize");
buttonContainer.add(randomizerButton);
JButton nextButton = new JButton("Next"); //forces a cycle to occur
nextButton.addActionListener(this);
nextButton.setActionCommand("check");
buttonContainer.add(nextButton);
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
buttonContainer.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
buttonContainer.add(stopButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
buttonContainer.add(clearButton);
//holds the speed container and button container, keeps it neat
JPanel functionContainer = new JPanel();
BoxLayout functionLayout = new BoxLayout(functionContainer, BoxLayout.PAGE_AXIS);
functionContainer.setLayout(functionLayout);
functionContainer.add(speedContainer);
speedContainer.setAlignmentX(CENTER_ALIGNMENT);
functionContainer.add(buttonContainer);
buttonContainer.setAlignmentX(CENTER_ALIGNMENT);
//finish up with the cell container
GridLayout cellLayout = new GridLayout(rows,columns);
JPanel cellContainer = new JPanel(cellLayout);
cellContainer.setBackground(Color.black);
int posX = 0;
int posY = 0;
for(int i=0;i<totalCells;i++)
{
MainCell childCell = new MainCell();
cell[i] = childCell;
childCell.setName(String.valueOf(i));
childCell.setPosX(posX);
posX++;
childCell.setPosY(posY);
if(posX==columns)
{
posX = 0;
posY++;
}
cellContainer.add(childCell);
childCell.deactivate();
Graphics g = childCell.getGraphics();
childCell.paint(g);
}
//make a default color
userColor = Color.yellow;
//change icon
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
//add it all up and pack
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
container.add(cellContainer);
container.add(functionContainer);
add(menuBar);
setJMenuBar(menuBar);
add(container);
pack();
}
private void checkCells()
{
//perform check for every cell
for(int i=0;i<totalCells;i++)
{
cell[i].setNeighbors(checkNeighbors(i));
}
//use value from check to determine life
for(int i=0;i<totalCells;i++)
{
int neighbors = cell[i].getNeighbors();
if(cell[i].isActivated())
{
System.out.println(cell[i].getName()+" "+neighbors);
if(neighbors==0||neighbors==1||neighbors>3)
{
cell[i].deactivate();
}
}
if(cell[i].isActivated()==false)
{
if(neighbors==3)
{
cell[i].activate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
//help button, self-explanatory
if(e.getActionCommand().equals("help"))
{
JOptionPane.showMessageDialog(this, "The game is governed by four rules:\nFor a space that is 'populated':"
+ "\n Each cell with one or no neighbors dies, as if by loneliness."
+ "\n Each cell with four or more neighbors dies, as if by overpopulation."
+ "\n Each cell with two or three neighbors survives."
+ "\nFor a space that is 'empty' or 'unpopulated':"
+ "\n Each cell with three neighbors becomes populated."
+ "\nLeft click populates cells. Right click depopulates cells.","Rules:",JOptionPane.PLAIN_MESSAGE);
}
//shameless self promotion
if(e.getActionCommand().equals("about"))
{
JOptionPane.showMessageDialog(this, "Game made and owned by *****!"
+ "\nFree usage as see fit, but give credit where credit is due!\nVERSION: "+version,"About:",JOptionPane.PLAIN_MESSAGE);
}
//clears all the cells
if(e.getActionCommand().equals("clear"))
{
timer.stop();
generation = 0;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
}
}
//starts timer
if(e.getActionCommand().equals("start"))
{
if(Integer.parseInt(speed.getText())>0)
{
timer.setDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
else
{
JOptionPane.showMessageDialog(this, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
}
//stops timer
if(e.getActionCommand().equals("stop"))
{
timer.stop();
}
//run when timer
if(e.getActionCommand().equals("timer"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
timer.stop();
checkCells();
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
//see checkCells()
if(e.getActionCommand().equals("check"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
checkCells();
}
//color select gui
if(e.getActionCommand().equals("colorSelect"))
{
userColor = JColorChooser.showDialog(this, "Choose a color:", userColor);
if(userColor==null)
{
userColor = Color.yellow;
}
}
//size chooser!
if(e.getActionCommand().equals("sizeChooser"))
{
SizeChooser size = new SizeChooser();
size.setLocationRelativeTo(null);
size.setVisible(true);
}
}
private int checkNeighbors(int c)
{
//if a LIVE neighbor is found, add one
int neighbors = 0;
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=0)
{
if(c-columns-1>=0)
{
if(cell[c-columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=0)
{
if(c-columns>=0)
{
if(cell[c-columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=0)
{
if(c-columns+1>=0)
{
if(cell[c-columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0)
{
if(c-1>=0)
{
if(cell[c-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1)
{
if(c+1<totalCells)
{
if(cell[c+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=rows-1)
{
if(c+columns-1<totalCells)
{
if(cell[c+columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=rows-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns<totalCells)
{
if(cell[c+columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns+1<totalCells)
{
if(cell[c+columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns+1].getName());
neighbors++;
}
}
}
return neighbors;
}
}
The following is MainCell.java:
public class MainCell extends JPanel implements MouseListener
{
//everything here should be self-explanatory
private static final long serialVersionUID = 1761933778208900172L;
private boolean activated = false;
public static boolean leftMousePressed;
public static boolean rightMousePressed;
private int posX = 0;
private int posY = 0;
private int neighbors = 0;
private URL cellImgURL_1 = getClass().getResource("images/cellImage_1.gif");
private ImageIcon cellImageIcon_1 = new ImageIcon(cellImgURL_1);
private Image cellImage_1 = cellImageIcon_1.getImage();
private URL cellImgURL_2 = getClass().getResource("images/cellImage_2.gif");
private ImageIcon cellImageIcon_2 = new ImageIcon(cellImgURL_2);
private Image cellImage_2 = cellImageIcon_2.getImage();
private URL cellImgURL_3 = getClass().getResource("images/cellImage_3.gif");
private ImageIcon cellImageIcon_3 = new ImageIcon(cellImgURL_3);
private Image cellImage_3 = cellImageIcon_3.getImage();
public MainCell()
{
Dimension dim = new Dimension(17, 17);
setPreferredSize(dim);
addMouseListener(this);
}
public void activate()
{
setBackground(MainGUI.userColor);
System.out.println(getName()+" "+posX+","+posY+" activated");
setActivated(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
else if(getPosY()!=0&&getPosX()!=MainGUI.columns-1)
{
g.drawImage(cellImage_1,0,0,null);
}
else if(getPosY()==0)
{
g.drawImage(cellImage_2,0,0,null);
}
else if(getPosX()==MainGUI.columns-1)
{
g.drawImage(cellImage_3,0,0,null);
}
}
public void setActivated(boolean b)
{
activated = b;
}
public void deactivate()
{
setBackground(Color.gray);
System.out.println(getName()+" "+posX+","+posY+" deactivated");
setActivated(false);
}
public boolean isActivated()
{
return activated;
}
public void setNeighbors(int i)
{
neighbors = i;
}
public int getNeighbors()
{
return neighbors;
}
public int getPosX()
{
return posX;
}
public void setPosX(int x)
{
posX = x;
}
public int getPosY()
{
return posY;
}
public void setPosY(int y)
{
posY = y;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
if(leftMousePressed&&SwingUtilities.isLeftMouseButton(e))
{
activate();
}
if(rightMousePressed&&SwingUtilities.isRightMouseButton(e))
{
deactivate();
}
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e)&&!leftMousePressed)
{
deactivate();
rightMousePressed = true;
}
if(SwingUtilities.isLeftMouseButton(e)&&!rightMousePressed)
{
activate();
leftMousePressed = true;
}
}
public void mouseReleased(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e))
{
rightMousePressed = false;
}
if(SwingUtilities.isLeftMouseButton(e))
{
leftMousePressed = false;
}
}
}
The following is SizeChooser.java:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SizeChooser extends JFrame
{
private static final long serialVersionUID = -6431709376438241788L;
public static MainGUI GUI;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField rowsTextField = new JTextField(String.valueOf((screenSize.height/17)-15));
JTextField columnsTextField = new JTextField(String.valueOf((screenSize.width/17)-10));
private static int rows = screenSize.height/17-15;
private static int columns = screenSize.width/17-10;
public SizeChooser()
{
setResizable(false);
setTitle("Select a size!");
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
add(container);
JLabel rowsLabel = new JLabel("Rows:");
container.add(rowsLabel);
container.add(rowsTextField);
JLabel columnsLabel = new JLabel("Columns:");
container.add(columnsLabel);
container.add(columnsTextField);
JButton confirmSize = new JButton("Confirm");
confirmSize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GUI.setVisible(false);
GUI = null;
if(Integer.parseInt(rowsTextField.getText())>0)
{
rows = Integer.parseInt(rowsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
if(Integer.parseInt(columnsTextField.getText())>0)
{
columns = Integer.parseInt(columnsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
setVisible(false);
}
});
container.add(confirmSize);
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
pack();
}
public static void main(String[]args)
{
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
}
}
So the problem now is, when the randomize button is pressed, or a large number of cells exist and then the timer is started, the cells aren't as snappy as they would be with less active cells. For example, with 100 columns and 50 rows, when the randomize button is pressed, one cell activates, then the next, then another, and so forth. Can I have them all activate at exactly the same time? Is this just a problem with too many things calculated at once? Would concurrency help?
QUICK EDIT: Is the swing timer the best idea for this project?
I havent read through your code completely but I am guessing that your listener methods are fairly computationally intensive and hence the lag in updating the display.
This simple test reveals that your randomize operation should be fairly quick:
public static void main(String args[]) {
Random rn = new Random();
boolean b[] = new boolean[1000000];
long timer = System.nanoTime();
for (int i = 0; i < b.length; i++) {
b[i] = rn.nextInt(6) == 0;
}
timer = System.nanoTime() - timer;
System.out.println(timer + "ns / " + (timer / 1000000) + "ms");
}
The output for me is:
17580267ns / 17ms
So this leads me into thinking activate() or deactivate() is causing your UI to be redrawn.
I am unable to run this because I don't have your graphical assets, but I would try those changes to see if it works:
In MainGUI#actionPerformed, change:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
to:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
// This will not cause the object to be redrawn and should
// be a fairly cheap operation
cell[i].setActivated(rn.nextInt(6)==0);
}
// Cause the UI to repaint
repaint();
}
Add this to MainCell
// You can specify those colors however you like
public static final Color COLOR_ACTIVATED = Color.RED;
public static final Color COLOR_DEACTIVATED = Color.GRAY;
And change:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
to:
protected void paintComponent(Graphics g)
{
// We now make UI changes only when the component is painted
setBackground(activated ? COLOR_ACTIVATED : COLOR_DEACTIVATED);
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
I have a jframe with page navigation buttons,print,search buttons.When i clicked on the print button it is perfectly opening the window and i am able to print the page also.But when i clicked on search button i am not able to get the window.My requirement is clicking on the Search button should open a window(same as print window) with text field and when i enter the search data then it should display the matches and unmatches.
I have tried the below code but i am not succeed.
import com.google.common.base.CharMatcher;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import com.sun.pdfview.PagePanel;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import static com.google.common.base.Strings.isNullOrEmpty;
public class PdfViewer extends JPanel {
private static enum Navigation {
GO_FIRST_PAGE, FORWARD, BACKWARD, GO_LAST_PAGE, GO_N_PAGE
}
private static final CharMatcher POSITIVE_DIGITAL = CharMatcher.anyOf("0123456789");
private static final String GO_PAGE_TEMPLATE = "%s of %s";
private static final int FIRST_PAGE = 1;
private int currentPage = FIRST_PAGE;
private JButton btnFirstPage;
private JButton btnPreviousPage;
private JTextField txtGoPage;
private JButton btnNextPage;
private JButton btnLastPage;
private JButton print;
private JButton search;
private PagePanel pagePanel;
private PDFFile pdfFile;
public PdfViewer() {
initial();
}
private void initial() {
setLayout(new BorderLayout(0, 0));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
add(topPanel, BorderLayout.NORTH);
btnFirstPage = createButton("|<<");
topPanel.add(btnFirstPage);
btnPreviousPage = createButton("<<");
topPanel.add(btnPreviousPage);
txtGoPage = new JTextField(10);
txtGoPage.setHorizontalAlignment(JTextField.CENTER);
topPanel.add(txtGoPage);
btnNextPage = createButton(">>");
topPanel.add(btnNextPage);
btnLastPage = createButton(">>|");
topPanel.add(btnLastPage);
print = new JButton("print");
topPanel.add(print);
search = new JButton("search");
topPanel.add(search);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
JPanel viewPanel = new JPanel(new BorderLayout(0, 0));
scrollPane.setViewportView(viewPanel);
pagePanel = new PagePanel();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
pagePanel.setPreferredSize(screenSize);
viewPanel.add(pagePanel, BorderLayout.CENTER);
disableAllNavigationButton();
btnFirstPage.addActionListener(new PageNavigationListener(Navigation.GO_FIRST_PAGE));
btnPreviousPage.addActionListener(new PageNavigationListener(Navigation.BACKWARD));
btnNextPage.addActionListener(new PageNavigationListener(Navigation.FORWARD));
btnLastPage.addActionListener(new PageNavigationListener(Navigation.GO_LAST_PAGE));
txtGoPage.addActionListener(new PageNavigationListener(Navigation.GO_N_PAGE));
print.addActionListener(new PrintUIWindow());
search.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
}
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setPreferredSize(new Dimension(55, 20));
return button;
}
private void disableAllNavigationButton() {
btnFirstPage.setEnabled(false);
btnPreviousPage.setEnabled(false);
btnNextPage.setEnabled(false);
btnLastPage.setEnabled(false);
}
private boolean isMoreThanOnePage(PDFFile pdfFile) {
return pdfFile.getNumPages() > 1;
}
private class PageNavigationListener implements ActionListener {
private final Navigation navigation;
private PageNavigationListener(Navigation navigation) {
this.navigation = navigation;
}
public void actionPerformed(ActionEvent e) {
if (pdfFile == null) {
return;
}
int numPages = pdfFile.getNumPages();
if (numPages <= 1) {
disableAllNavigationButton();
} else {
if (navigation == Navigation.FORWARD && hasNextPage(numPages)) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_LAST_PAGE) {
goPage(numPages, numPages);
}
if (navigation == Navigation.BACKWARD && hasPreviousPage()) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_FIRST_PAGE) {
goPage(FIRST_PAGE, numPages);
}
if (navigation == Navigation.GO_N_PAGE) {
String text = txtGoPage.getText();
boolean isValid = false;
if (!isNullOrEmpty(text)) {
boolean isNumber = POSITIVE_DIGITAL.matchesAllOf(text);
if (isNumber) {
int pageNumber = Integer.valueOf(text);
if (pageNumber >= 1 && pageNumber <= numPages) {
goPage(Integer.valueOf(text), numPages);
isValid = true;
}
}
}
if (!isValid) {
JOptionPane.showMessageDialog(PdfViewer.this,
format("Invalid page number '%s' in this document", text));
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
}
}
}
}
private void goPage(int pageNumber, int numPages) {
currentPage = pageNumber;
PDFPage page = pdfFile.getPage(currentPage);
pagePanel.showPage(page);
boolean notFirstPage = isNotFirstPage();
btnFirstPage.setEnabled(notFirstPage);
btnPreviousPage.setEnabled(notFirstPage);
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
boolean notLastPage = isNotLastPage(numPages);
btnNextPage.setEnabled(notLastPage);
btnLastPage.setEnabled(notLastPage);
}
private boolean hasNextPage(int numPages) {
return (++currentPage) <= numPages;
}
private boolean hasPreviousPage() {
return (--currentPage) >= FIRST_PAGE;
}
private boolean isNotLastPage(int numPages) {
return currentPage != numPages;
}
private boolean isNotFirstPage() {
return currentPage != FIRST_PAGE;
}
}
private class PrintUIWindow implements Printable, ActionListener {
/*
* (non-Javadoc)
*
* #see java.awt.print.Printable#print(java.awt.Graphics,
* java.awt.print.PageFormat, int)
*/
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int pagenum = pageIndex+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) graphics;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) pageFormat.getImageableWidth (),
(int) pageFormat.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) pageFormat.getImageableX (),
(int) pageFormat.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) graphics, bounds,
null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
//JOptionPane.showMessageDialog (this, ie.getMessage ());
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (pageFormat.getImageableX (),
pageFormat.getImageableY (),
pageFormat.getImageableWidth (),
pageFormat.getImageableHeight ()));
return PAGE_EXISTS;
}
/*
* (non-Javadoc)
*
* #see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
* )
*/
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Inside action performed");
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
try
{
HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
//attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (printJob.printDialog (attset))
printJob.print (attset);
}
catch (PrinterException pe)
{
//JOptionPane.showMessageDialog (this, pe.getMessage ());
}
}
}
public PagePanel getPagePanel() {
return pagePanel;
}
public void setPDFFile(PDFFile pdfFile) {
this.pdfFile = pdfFile;
currentPage = FIRST_PAGE;
disableAllNavigationButton();
txtGoPage.setText(format(GO_PAGE_TEMPLATE, FIRST_PAGE, pdfFile.getNumPages()));
boolean moreThanOnePage = isMoreThanOnePage(pdfFile);
btnNextPage.setEnabled(moreThanOnePage);
btnLastPage.setEnabled(moreThanOnePage);
}
public static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
public static void main(String[] args) {
try {
long heapSize = Runtime.getRuntime().totalMemory();
System.out.println("Heap Size = " + heapSize);
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load a pdf from a byte buffer
File file = new File("/home/swarupa/Downloads/2626OS-Chapter-5-Advanced-Theme.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
final PDFFile pdffile = new PDFFile(buf);
PdfViewer pdfViewer = new PdfViewer();
pdfViewer.setPDFFile(pdffile);
frame.add(pdfViewer);
frame.pack();
frame.setVisible(true);
PDFPage page = pdffile.getPage(0);
pdfViewer.getPagePanel().showPage(page);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Where i am doing wrong.Can any one point me.
I think, that this should solve your problem ;) You've forgotten to set the window to be visible :)
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
parent.setVisible(true);
}
}
Btw-why do you create that JDialog?
You create JDialog and JFrame, why? You never call setVisible(true), why?
What you expect from the Action1?
Sorry for posting this answer to your comment as a new post, but it was too long to post it as a comment. You just can't remove close and minimize buttons from JFrame. If you want some window without those buttons, you have to create and customize your own JDialog. Nevertheless there will still be a close button (X). You can make your JDialog undecorated and make it to behave more like JFrame when you implement something like this:
class CustomizedDialog extends JDialog {
public CustomizedDialog(JFrame frame, String str) {
super(frame, str);
super.setUndecorated(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
And then you can call it in your code with this:
CustomizedDialog myCustomizedDialog = new CustomizedDialog(new JFrame(), "My title");
JPanel panel = new JPanel();
panel.setSize(256, 256);
myCustomizedDialog.add(panel);
myCustomizedDialog.setSize(256, 256);
myCustomizedDialog.setLocationRelativeTo(null);
myCustomizedDialog.setVisible(true);
I hope, this helps :)