How can i add photo to label and save it to folder? - java

How can I open file explorer, select a photo file, add some effects, and then save it but by opening file explorer to let me choose where to save the new photo with effect added. I have no idea. Please help me.
public class Imagine extends JFrame {
DisplayPanel displayPanel;
JButton brightenButton, darkenButton, contrastIncButton, contrastDecButton, reverseButton, resetButton, addPhotoButton,savePhoto;
public Imagine()
{
super();
Container container = getContentPane();
displayPanel = new DisplayPanel();
container.add(displayPanel);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
panel.setBorder(new TitledBorder("Choose option"));
addPhotoButton = new JButton("Select photo");
addPhotoButton.addActionListener(new ButtonListener());
savePhoto = new JButton("Save photo");
savePhoto.addActionListener(new ButtonListener());
brightenButton = new JButton("Luminozitate +");
brightenButton.addActionListener(new ButtonListener());
darkenButton = new JButton("Luminozitate -");
darkenButton.addActionListener(new ButtonListener());
contrastIncButton = new JButton("Contrast +");
contrastIncButton.addActionListener(new ButtonListener());
contrastDecButton = new JButton("Contrast -");
contrastDecButton.addActionListener(new ButtonListener());
reverseButton = new JButton("Negative");
reverseButton.addActionListener(new ButtonListener());
resetButton = new JButton("Reset");
resetButton.addActionListener(new ButtonListener());
panel.add(addPhotoButton);
panel.add(savePhoto);
panel.add(brightenButton);
panel.add(darkenButton);
panel.add(contrastIncButton);
panel.add(contrastDecButton);
panel.add(reverseButton);
panel.add(resetButton);
container.add(BorderLayout.SOUTH, panel);
addWindowListener(new WindowEventHandler());
setSize(displayPanel.getWidth(), displayPanel.getHeight() + 25);
show();
}
class WindowEventHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public static void main(String arg[])
{
new Imagine();
//select file
//ImagesLoading a = new ImagesLoading();
//a.initialize();
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton) e.getSource();
if (button.equals(brightenButton))
{
displayPanel.brightenLUT();
displayPanel.applyFilter();
displayPanel.repaint();
}
else
if (button.equals(darkenButton))
{
displayPanel.darkenLUT();
displayPanel.applyFilter();
displayPanel.repaint();
}
else
if (button.equals(contrastIncButton))
{
displayPanel.contrastIncLUT();
displayPanel.applyFilter();
displayPanel.repaint();
} else
if (button.equals(contrastDecButton))
{
displayPanel.contrastDecLUT();
displayPanel.applyFilter();
displayPanel.repaint();
}
else
if (button.equals(reverseButton))
{
displayPanel.reverseLUT();
displayPanel.applyFilter();
displayPanel.repaint();
} else
if (button.equals(resetButton))
{
displayPanel.reset();
displayPanel.repaint();
}
else
if (button.equals(addPhotoButton))
{
JFrame fr = new JFrame("Image loading program Using awt");
FileDialog fd = new FileDialog(fr, "Open", FileDialog.LOAD);
fd.show();
String d = (fd.getDirectory() + fd.getFile());
System.out.println(d);
}
else
if (button.equals(savePhoto))
{
//
}
}
}
}
class DisplayPanel extends JPanel
{
Image displayImage;
BufferedImage bi;
Graphics2D big;
LookupTable lookupTable;
DisplayPanel()
{
setBackground(Color.black); // panel background color
loadImage();
setSize(displayImage.getWidth(this), displayImage.getWidth(this)); // panel
createBufferedImage();
}
public void loadImage()
{
displayImage = Toolkit.getDefaultToolkit().getImage("a.jpg");
MediaTracker mt = new MediaTracker(this);
mt.addImage(displayImage, 1);
try {
mt.waitForAll();
} catch (Exception e) {
System.out.println("exception while loading.");
}
if (displayImage.getWidth(this) == -1) {
System.out.println("no jpg file");
System.exit(0);
}
}
public void createBufferedImage()
{
bi = new BufferedImage(displayImage.getWidth(this), displayImage.getHeight(this), BufferedImage.TYPE_INT_ARGB);
big = bi.createGraphics();
big.drawImage(displayImage, 0, 0, this);
}
public void brightenLUT()
{
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i + 10);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void darkenLUT()
{
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i - 10);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void contrastIncLUT()
{
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i * 1.2);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void contrastDecLUT()
{
short brighten[] = new short[256];
for (int i = 0; i < 256; i++) {
short pixelValue = (short) (i / 1.2);
if (pixelValue > 255)
pixelValue = 255;
else if (pixelValue < 0)
pixelValue = 0;
brighten[i] = pixelValue;
}
lookupTable = new ShortLookupTable(0, brighten);
}
public void reverseLUT()
{
byte reverse[] = new byte[256];
for (int i = 0; i < 256; i++) {
reverse[i] = (byte) (255 - i);
}
lookupTable = new ByteLookupTable(0, reverse);
}
public void reset()
{
big.setColor(Color.black);
big.clearRect(0, 0, bi.getWidth(this), bi.getHeight(this));
big.drawImage(displayImage, 0, 0, this);
}
public void applyFilter()
{
LookupOp lop = new LookupOp(lookupTable, null);
lop.filter(bi, bi);
}
public void update(Graphics g)
{
g.clearRect(0, 0, getWidth(), getHeight());
paintComponent(g);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(bi, 0, 0, this);
}
}
How to save the added photo with new effects that I selected to a location that I can select from file explorer
How can I open file explorer, select a photo file, add some effects, and then save it but by opening file explorer to let me choose where to save the new photo with effect added. I have no idea. Please help me.

Related

How to get the true x and y coordinates of a JTextField

I had an issue with a piece of code I was writing where I was adding JPanel's inside of others to form a layout. The issue is that after the window is displayed I needed to get the x and y coordinates of one of the text fields but whenever I try using the getX() and getY() methods they keep returning 0. I have verified that the getX() and getY() methods are being called after the window is initialized and displayed. How can I fix this and get the actual coordinates of the text field.
This is window code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class GraphicsPanel extends JFrame implements ActionListener, CaretListener{
JPanel buttonPanel = new JPanel();
JPanel mainPanel = new JPanel();
JPanel animationPanel = new JPanel();
JPanel bottomPanel = new JPanel();
JPanel text = new JPanel();
PokemonLearnsets info = new PokemonLearnsets();
HealthBar healthBar1 = new HealthBar();
HealthBar healthBar2 = new HealthBar();
JTextArea textArea = new JTextArea();
JTextField response = new JTextField();
int health1 = 100;
int total1 = 100;
int health2 = 100;
int total2 = 100;
int startOfRect = 1;
int p1MonNum = -1;
int waitTime = 20;
int p2MonNum = -1;
TextInterface theText;
Icon allIcons[][];
JLabel p1Gif;
JLabel p2Gif;
JPanel mainBuilderPanel = new JPanel();
JPanel builderPanel = new JPanel();
JPanel builderMessagePanel = new JPanel();
JPanel monPanels [] = new JPanel[6];
JPanel imagePanels[] = new JPanel[6];
JPanel namePanels[] = new JPanel[6];
JPanel movePanels[] = new JPanel[6];
JPanel allMoves[][] = new JPanel[6][4];
JTextField names[] = new JTextField[6];
JTextField moves[][] = new JTextField[6][4];
JButton validate = new JButton("Validate");
JLabel tempImages[] = new JLabel[6];
JLabel emptyLabels[] = new JLabel[6];
AutoSuggestor [] nameSuggestions = new AutoSuggestor[6];
AutoSuggestor [][] moveSuggestions = new AutoSuggestor[6][4];
public GraphicsPanel(String name){
super(name);
setupTeamBuilderPanel();
// setupBattlePanel();
}
private void setupTeamBuilderPanel() {
Container c = getContentPane();
mainBuilderPanel.setLayout(new BorderLayout());
mainBuilderPanel.setBorder(new LineBorder(Color.BLACK, 2));
builderPanel.setLayout(new GridLayout(1, 0));
builderPanel.setBorder(new LineBorder(Color.BLACK, 1));
builderMessagePanel.setBorder(new LineBorder(Color.BLACK, 2));
for (int i = 0; i < monPanels.length; i ++) {
monPanels[i] = new JPanel();
imagePanels[i] = new JPanel();
namePanels[i] = new JPanel();
movePanels[i] = new JPanel();
names[i] = new JTextField();
names[i].addCaretListener(this);
emptyLabels[i] = new JLabel();
tempImages[i] = emptyLabels[i];
monPanels[i].setBorder(new LineBorder(Color.BLACK, 3));
imagePanels[i].setBorder(new LineBorder(Color.BLACK, 3));
movePanels[i].setBorder(new LineBorder(Color.BLACK, 3));
monPanels[i].setLayout(new GridLayout(0 ,1));
namePanels[i].setLayout(new GridLayout(1, 0));
movePanels[i].setLayout(new GridLayout(0, 1));
imagePanels[i].setLayout(new BorderLayout());
namePanels[i].add(new JLabel(" Name:"));
namePanels[i].add(names[i]);
imagePanels[i].add(tempImages[i]);
imagePanels[i].add(namePanels[i], BorderLayout.SOUTH);
monPanels[i].add(imagePanels[i]);
for (int k = 0; k < moves[i].length; k ++) {
moves[i][k] = new JTextField();
allMoves[i][k] = new JPanel();
allMoves[i][k].setLayout(new GridLayout(0, 1));
allMoves[i][k].add(new JLabel(" Move " + Integer.toString(k + 1) + ":"));
allMoves[i][k].add(moves[i][k]);
allMoves[i][k].add(new JLabel());
allMoves[i][k].add(new JLabel());
movePanels[i].add(allMoves[i][k]);
}
monPanels[i].add(movePanels[i]);
builderPanel.add(monPanels[i]);
}
String welcomeMessage = "";
for (int i = 0; i < 5; i ++) {
welcomeMessage += " ";
}
welcomeMessage += "Welcome to the Teambuilder!";
setupSuggestions();
validate.addActionListener(this);
builderMessagePanel.add(new JLabel(welcomeMessage));
mainBuilderPanel.add(builderMessagePanel, BorderLayout.NORTH);
mainBuilderPanel.add(validate, BorderLayout.SOUTH);
mainBuilderPanel.add(builderPanel);
c.add(mainBuilderPanel);
}
private void setupBattlePanel() {
Container c = getContentPane();
mainPanel.setLayout(new GridLayout());
bottomPanel.setLayout(new GridLayout());
animationPanel.setBorder(new LineBorder(Color.BLACK, 3));
animationPanel.setLayout(new GridLayout(0, 2));
mainPanel.add(animationPanel);
buttonPanel.setBorder(new LineBorder(Color.BLACK, 3));
buttonPanel.setLayout(new FlowLayout(5));
buttonPanel.setBackground(Color.GREEN);
// buttonPanel.add(new JLabel(" "));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
bottomPanel.add(buttonPanel);
text.setLayout(new GridLayout());
text.setBorder(new LineBorder(Color.BLACK, 3));
text.add(response);
bottomPanel.add(text);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setBackground(Color.LIGHT_GRAY);
JScrollPane textAreaPane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
textAreaPane.setBorder(new LineBorder(Color.BLACK, 3));
mainPanel.add(textAreaPane);
c.add(mainPanel, BorderLayout.CENTER);
c.add(bottomPanel, BorderLayout.SOUTH);
}
private void setupSuggestions() {
ArrayList<String> allPossibleMoves = new ArrayList<String>();
Collections.addAll(allPossibleMoves, info.getAllMoves());
for (int i = 0; i < 6; i ++) {
for (int k = 0; k < 4; k ++) {
moveSuggestions[i][k] = new AutoSuggestor(moves[i][k], allPossibleMoves, Color.WHITE.brighter(), Color.BLACK, Color.BLACK, 0.75f);
moveSuggestions[i][k].setTextField(moves[i][k]);
}
}
}
public void writeToScreen(String writing) {
String current = textArea.getText();
textArea.setText(current + writing);
}
public void updateAll() {
mainPanel.updateUI();
bottomPanel.updateUI();
mainBuilderPanel.updateUI();
}
public void setTextInterface(TextInterface text) {
theText = text;
response.addActionListener(theText.action);
}
public void drawMons(String name1, String name2) {
animationPanel.removeAll();
ImageIcon secImage = new ImageIcon(this.getClass().getResource("SpritesFront/" + name2 + ".gif"));
secImage = new ImageIcon(secImage.getImage().getScaledInstance((int)(secImage.getIconWidth() * 1.5), (int)(secImage.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon = secImage;
p2Gif = new JLabel(icon);
ImageIcon firstImage = new ImageIcon(this.getClass().getResource("SpritesBack/" + name1 + "-back.gif"));
firstImage = new ImageIcon(firstImage.getImage().getScaledInstance((int)(firstImage.getIconWidth() * 1.5), (int)(firstImage.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon2 = firstImage;
p1Gif = new JLabel(icon2);
animationPanel.add(healthBar2);
animationPanel.add(p2Gif);
animationPanel.add(p1Gif);
animationPanel.add(healthBar1);
updateAll();
}
public void fillPortions(int x) {
JLabel [] labels = new JLabel[x];
for (int i = 0; i < x; i ++) {
labels[i] = new JLabel();
animationPanel.add(labels[i]);
}
}
public void refreshHealthBar(int health, int total, int pNum, int mon) {
if (pNum == 1) {
if (p1MonNum != mon && p1MonNum != -1) {
p1MonNum = mon;
health1 = health;
total1 = total;
healthBar1.setHealth(health);
healthBar1.setTotal(total);
redoHealthPanel();
}
else {
p1MonNum = mon;
healthBar1.setTotal(total);;
while (health < health1) {
healthBar1.setHealth(health1);
redoHealthPanel();
health1--;
}
while (health > health1) {
healthBar1.setHealth(health1);
redoHealthPanel();
health1++;
}
}
}
else {
if (p2MonNum != mon && p2MonNum != -1) {
p2MonNum = mon;
health2 = health;
total2 = total;
healthBar2.setHealth(health);
healthBar2.setTotal(total);
redoHealthPanel();
updateAll();
}
else {
p2MonNum = mon;
healthBar2.setTotal(total);
while (health < health2) {
healthBar2.setHealth(health2);
redoHealthPanel();
health2--;
}
while (health > health2) {
healthBar2.setHealth(health2);
redoHealthPanel();
health2++;
}
}
}
}
private void redoHealthPanel () {
animationPanel.removeAll();
animationPanel.add(healthBar2);
animationPanel.add(p2Gif);
animationPanel.add(p1Gif);
animationPanel.add(healthBar1);
updateAll();
try {
TimeUnit.MILLISECONDS.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private String validatePokemon() {
String answer = "";
String tempMonNames [] = new String[6];
boolean invalidMove = false;
for (int i = 0; i < monPanels.length; i ++) {
String currentName = names[i].getText();
if (currentName.isEmpty()) {
answer = "You must have 6 Pokemon on your team but you can have less than 4 moves";
return answer;
}
for (String element : tempMonNames) {
if (element == null) {
continue;
} else if (currentName.equals(element)) {
answer = "You have duplicate Pokemon on your team";
return answer;
}
}
if (!info.validPokemon(currentName)) {
answer += "Pokemon #" + (i + 1) + " is invalid\n";
} else {
tempMonNames[i] = currentName;
}
int count = 0;
for (int k = 0; k < moves[i].length; k++) {
if (moves[i][k].getText().isEmpty()) {
count++;
}
if (!info.validMove(moves[i][k].getText().replace(" ", "").toLowerCase(), currentName)) {
answer += "Pokemon #" + (i + 1) + ", move #" + (k + 1) + " is invalid\n";
invalidMove = true;
}
if (count >= 4) {
answer += "Pokemon #" + (i + 1) + " has no moves\n";
break;
}
}
}
if (invalidMove) {
answer += "***Please keep in mind only damaging moves without recoil are allowed, if there aren't enough for 4 moves, leave fields blank***";
}
return answer;
}
#Override
public void actionPerformed(ActionEvent e) {
if (validatePokemon().isEmpty()) {
JOptionPane.showMessageDialog(null, "Confirmed" , "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, validatePokemon() , "", JOptionPane.ERROR_MESSAGE);
}
}
#Override
public void caretUpdate(CaretEvent e) {
for (int i = 0; i < names.length; i ++) {
if (info.validPokemon(names[i].getText()) && tempImages[i].getParent() == null) {
ImageIcon temp = new ImageIcon(this.getClass().getResource("SpritesFront/" + names[i].getText().replace(" ", "").replace(":", "").replace("'", "").replace(".", "").replace("-", "").toLowerCase() + ".gif"));
temp = new ImageIcon(temp.getImage().getScaledInstance((int)(temp.getIconWidth() * 1.5), (int)(temp.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon = temp;
imagePanels[i].remove(tempImages[i]);
tempImages[i] = new JLabel(icon);
imagePanels[i].add(tempImages[i]);
updateAll();
} else if (!info.validPokemon(names[i].getText())){
imagePanels[i].remove(tempImages[i]);
updateAll();
}
}
}
}
This is set up for the window:
GraphicsPanel window = new GraphicsPanel("Pokemon");
window.setBounds(0, 0, 1440, 830);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
This is where the getX() and getY() are getting called:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
public class AutoSuggestor {
private final JTextComponent textComp;
private JPanel suggestionsPanel;
private JWindow autoSuggestionPopUpWindow;
private String typedWord;
private final ArrayList<String> dictionary = new ArrayList<>();
private JTextField textField;
private int currentIndexOfSpace, tW, tH;
private DocumentListener documentListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
#Override
public void removeUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
#Override
public void changedUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
};
private final Color suggestionsTextColor;
private final Color suggestionFocusedColor;
public AutoSuggestor(JTextComponent textComp, ArrayList<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {
this.textComp = textComp;
this.suggestionsTextColor = textColor;
this.suggestionFocusedColor = suggestionFocusedColor;
this.textComp.getDocument().addDocumentListener(documentListener);
setDictionary(words);
typedWord = "";
currentIndexOfSpace = 0;
tW = 0;
tH = 0;
autoSuggestionPopUpWindow = new JWindow();
autoSuggestionPopUpWindow.setOpacity(opacity);
suggestionsPanel = new JPanel();
suggestionsPanel.setLayout(new GridLayout(0, 1));
suggestionsPanel.setBackground(popUpBackground);
addKeyBindingToRequestFocusInPopUpWindow();
}
private void addKeyBindingToRequestFocusInPopUpWindow() {
textComp.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
textComp.getActionMap().put("Down released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
break;
}
}
}
});
suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
suggestionsPanel.getActionMap().put("Down released", new AbstractAction() {
int lastFocusableIndex = 0;
#Override
public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))
ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
int max = sls.size();
if (max > 1) {//more than 1 suggestion
for (int i = 0; i < max; i++) {
SuggestionLabel sl = sls.get(i);
if (sl.isFocused()) {
if (lastFocusableIndex == max - 1) {
lastFocusableIndex = 0;
sl.setFocused(false);
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
} else {
sl.setFocused(false);
lastFocusableIndex = i;
}
} else if (lastFocusableIndex <= i) {
if (i < max) {
sl.setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
lastFocusableIndex = i;
break;
}
}
}
} else {//only a single suggestion was given
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
}
}
});
}
private void setFocusToTextField() {
textComp.requestFocusInWindow();
}
public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {
ArrayList<SuggestionLabel> sls = new ArrayList<>();
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);
sls.add(sl);
}
}
return sls;
}
private void checkForAndShowSuggestions() {
typedWord = getCurrentlyTypedWord();
suggestionsPanel.removeAll();//remove previos words/jlabels that were added
//used to calcualte size of JWindow as new Jlabels are added
tW = 0;
tH = 0;
boolean added = wordTyped(typedWord);
if (!added) {
if (autoSuggestionPopUpWindow.isVisible()) {
autoSuggestionPopUpWindow.setVisible(false);
}
} else {
showPopUpWindow();
setFocusToTextField();
}
}
protected void addWordToSuggestions(String word) {
SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);
calculatePopUpWindowSize(suggestionLabel);
suggestionsPanel.add(suggestionLabel);
}
public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
String text = textComp.getText();
String wordBeingTyped = "";
text = text.replaceAll("(\\r|\\n)", " ");
if (text.contains(" ")) {
int tmp = text.lastIndexOf(" ");
if (tmp >= currentIndexOfSpace) {
currentIndexOfSpace = tmp;
wordBeingTyped = text.substring(text.lastIndexOf(" "));
}
} else {
wordBeingTyped = text;
}
return wordBeingTyped.trim();
}
private void calculatePopUpWindowSize(JLabel label) {
//so we can size the JWindow correctly
if (tW < label.getPreferredSize().width) {
tW = label.getPreferredSize().width;
}
tH += label.getPreferredSize().height;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
private void showPopUpWindow() {
autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.setSize(tW, tH);
autoSuggestionPopUpWindow.setVisible(true);
//show the pop up
autoSuggestionPopUpWindow.setLocation(textComp.getX(), textComp.getY() + textComp.getHeight());
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.revalidate();
autoSuggestionPopUpWindow.repaint();
}
public void setDictionary(ArrayList<String> words) {
dictionary.clear();
if (words == null) {
return;//so we can call constructor with null value for dictionary without exception thrown
}
for (String word : words) {
dictionary.add(word);
}
}
public JWindow getAutoSuggestionPopUpWindow() {
return autoSuggestionPopUpWindow;
}
public JTextComponent getTextField() {
return textComp;
}
public void addToDictionary(String word) {
dictionary.add(word);
}
boolean wordTyped(String typedWord) {
if (typedWord.isEmpty()) {
return false;
}
//System.out.println("Typed word: " + typedWord);
boolean suggestionAdded = false;
for (String word : dictionary) {//get words in the dictionary which we added
boolean fullymatches = true;
for (int i = 0; i < typedWord.length(); i++) {//each string in the word
if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
fullymatches = false;
break;
}
}
if (fullymatches) {
addWordToSuggestions(word);
suggestionAdded = true;
}
}
return suggestionAdded;
}
}
class SuggestionLabel extends JLabel {
private boolean focused = false;
private final JWindow autoSuggestionsPopUpWindow;
private final JTextComponent textComponent;
private final AutoSuggestor autoSuggestor;
private Color suggestionsTextColor, suggestionBorderColor;
public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {
super(string);
this.suggestionsTextColor = suggestionsTextColor;
this.autoSuggestor = autoSuggestor;
this.textComponent = autoSuggestor.getTextField();
this.suggestionBorderColor = borderColor;
this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();
initComponent();
}
private void initComponent() {
setFocusable(true);
setForeground(suggestionsTextColor);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
replaceWithSuggestedText();
autoSuggestionsPopUpWindow.setVisible(false);
}
});
getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");
getActionMap().put("Enter released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
replaceWithSuggestedText();
autoSuggestionsPopUpWindow.setVisible(false);
}
});
}
public void setFocused(boolean focused) {
if (focused) {
setBorder(new LineBorder(suggestionBorderColor));
} else {
setBorder(null);
}
repaint();
this.focused = focused;
}
public boolean isFocused() {
return focused;
}
private void replaceWithSuggestedText() {
String suggestedWord = getText();
String text = textComponent.getText();
String typedWord = autoSuggestor.getCurrentlyTypedWord();
String t = text.substring(0, text.lastIndexOf(typedWord));
String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);
textComponent.setText(tmp);
}
}
The textComp.getX() and textComp.getY() in the showPopUpWindow method are the ones that are giving zeros.
After thinking about it for a while I came up with this solution and it works for me.
int x = 0;
int y = 0;
Component currentComponent = textComp;
while (currentComponent != null) {
x += currentComponent.getX();
y += currentComponent.getY();
currentComponent = currentComponent.getParent();
}

Multiple Windows(AWT) by Using Thread, But Only the Last Window Works

I want to make an imitative hack System. There will be 3 windows displayed on screen. Each window will show some string Constantly (like some movie scene) . However only the third (the last) window works. So how to make every window show string at the same time?
the frame class as follow:
import java.awt.*;
import java.awt.event.*;
class sys extends Thread {
private static Frame frm;
private static TextArea txa;
private int fsx, fsy, flx, fly, tsx, tsy, tlx, tly;
private String strarr[] = new String[7];
private String frmName;
public sys(String str, String SAEC[]) {
frmName = str;
strarr = SAEC;
}
public void SettingFRM(int sx, int sy, int lx, int ly) {
//frame's location and size
fsx = sx;
fsy = sy;
flx = lx;
fly = ly;
}
public void SettingTXA(int sx, int sy, int lx, int ly) {
//textArea's location and size
tsx = sx;
tsy = sy;
tlx = lx;
tly = ly;
}
public void run() {
frm = new Frame(frmName);
//the exterior design
txa = new TextArea("", 100, 100, TextArea.SCROLLBARS_BOTH);
txa.setBounds(tlx, tly, tsx, tsy);
txa.setBackground(Color.darkGray);
txa.setFont(new Font("Arial", Font.PLAIN, 16));
txa.setForeground(Color.green);
frm.setLayout(null);
frm.setSize(fsx, fsy);
frm.setLocation(flx, fly);
frm.setVisible(true);
frm.setBackground(Color.darkGray);
frm.add(txa);
while (1 != 0) {
txa.append(strarr[(int) (Math.random() * 7)]);// to obtain new string
frm.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
try {
sleep(200);
} catch (InterruptedException e) {
}
}
}
}
main program as follow:
public class ImitativeHackSystem {
public static void main(String[] args) throws InterruptedException {
//specific string
String strarr[] = new String[9];
strarr[0] = new String("Hacking... Time estimate 25 seconds...\n");
strarr[1] = new String("Retrying...\n");
strarr[2] = new String("Error! Code:e2130443523\n");
strarr[3] = new String("Success! IP:192.168.0.1\n");
strarr[4] = new String("picking datas...\n");
strarr[5] = new String("Anti-system started\n");
strarr[6] = new String("Has been discovering... fake random IP address\n");
strarr[7] = new String("01011010000011001000000011111101010");
strarr[8] = new String("111101010101001101101101010011010");
//object array
sys fhs[] = new sys[3];
for (int i = 0; i < 3; i++)
fhs[i] = new sys("Fake Hacking System", strarr);
fhs[0].SettingTXA(635, 690, 5, 30);
fhs[0].SettingFRM(640, 720, 0, 0);
fhs[1].SettingTXA(635, 330, 5, 30);
fhs[1].SettingFRM(640, 360, 645, 0);
fhs[2].SettingTXA(635, 330, 5, 30);
fhs[2].SettingFRM(640, 360, 645, 365);
//to execute
for (int i = 0; i < 3; i++) {
fhs[i].start();
Thread.sleep(500);
}
}
}

PrintPreview Multiple Page Print java

I have the code for my print preview
package printprew;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.print.*;
import javax.swing.border.*;
public class PrintPrew extends JFrame implements ActionListener, ChangeListener, ItemListener {
JButton print = new JButton("Print"),
printThisPage = new JButton("Print Current Page"),
cancel = new JButton("Close");
Pageable pg = null;
double scale = 1.0;
JSlider slider = new JSlider();
Page page[] = null;
JComboBox jcb = new JComboBox();
CardLayout cl = new CardLayout();
JPanel p = new JPanel(cl);
JButton back = new JButton("<<"), forward = new JButton(">>");
public PrintPrew(Pageable pg) {
super("Print Preview");
this.pg = pg;
createPreview();
}
public PrintPrew(final Printable pr, final PageFormat p) {
super("Print Preview");
this.pg = new Pageable() {
public int getNumberOfPages() {
Graphics g = new java.awt.image.BufferedImage(2,2,java.awt.image.BufferedImage.TYPE_INT_RGB).getGraphics();
int n=0;
try { while(pr.print(g, p, n) == pr.PAGE_EXISTS) n++; }
catch(Exception ex) {ex.printStackTrace();}
return n;
}
public PageFormat getPageFormat(int x) { return p; }
public Printable getPrintable(int x) { return pr; }
};
createPreview();
}
private void createPreview() {
page = new Page[pg.getNumberOfPages()];
FlowLayout fl = new FlowLayout();
PageFormat pf = pg.getPageFormat(0);
Dimension size = new Dimension((int)pf.getPaper().getWidth(), (int)pf.getPaper().getHeight());
if(pf.getOrientation() != PageFormat.PORTRAIT)
size = new Dimension(size.height, size.width);
JPanel temp = null;
for(int i=0; i<page.length; i++) {
jcb.addItem(""+(i+1));
page[i] = new Page(i, size);
p.add(""+(i+1), new JScrollPane(page[i]));
}
setTopPanel();
this.getContentPane().add(p, "Center");
Dimension d = this.getToolkit().getScreenSize();
this.setSize(d.width,d.height-60);
slider.setSize(this.getWidth()/2, slider.getPreferredSize().height);
this.setVisible(true);
page[jcb.getSelectedIndex()].refreshScale();
}
private void setTopPanel() {
FlowLayout fl = new FlowLayout();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JPanel topPanel = new JPanel(gbl), temp = new JPanel(fl); slider.setBorder(new TitledBorder("Percentage Zoom"));
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMinimum(0);
slider.setMaximum(500);
slider.setValue(100);
slider.setMinorTickSpacing(20);
slider.setMajorTickSpacing(100);
slider.addChangeListener(this);
back.addActionListener(this);
forward.addActionListener(this);
back.setEnabled(false);
forward.setEnabled(page.length > 1);
gbc.gridx = 0;
gbc.gridwidth = 1;
gbl.setConstraints(slider, gbc);
topPanel.add(slider);
temp.add(back);
temp.add(jcb);
temp.add(forward);
temp.add(cancel);
temp.add(print);
temp.add(printThisPage);
gbc.gridx = 1;
gbc.gridwidth = 2;
gbl.setConstraints(temp, gbc);
topPanel.add(temp);
print.addActionListener(this);
printThisPage.addActionListener(this);
cancel.addActionListener(this);
jcb.addItemListener(this);
print.setMnemonic('P');
cancel.setMnemonic('C');
printThisPage.setMnemonic('U');
this.getContentPane().add(topPanel, "North");
}
public void itemStateChanged(ItemEvent ie) {
cl.show(p, (String)jcb.getSelectedItem());
page[jcb.getSelectedIndex()].refreshScale();
back.setEnabled(jcb.getSelectedIndex() == 0 ? false: true);
forward.setEnabled(jcb.getSelectedIndex() == jcb.getItemCount()-1 ? false:true);
this.validate();
} public void actionPerformed(ActionEvent ae) {
Object o = ae.getSource();
if(o == print) {
try {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.defaultPage(pg.getPageFormat(0));
pj.setPageable(pg);
if(pj.printDialog())
pj.print();
}
catch(Exception ex) {
JOptionPane.showMessageDialog(null,ex.toString(), "Error in Printing",1);
}
}
else if(o == printThisPage)
printCurrentPage();
else if(o == back) {
jcb.setSelectedIndex(jcb.getSelectedIndex() == 0 ? 0:jcb.getSelectedIndex()-1);
if(jcb.getSelectedIndex() == 0)
back.setEnabled(false);
}
else if(o == forward) {
jcb.setSelectedIndex(jcb.getSelectedIndex() == jcb.getItemCount()-1 ? 0:jcb.getSelectedIndex()+1);
if(jcb.getSelectedIndex() == jcb.getItemCount()-1)
forward.setEnabled(false);
}
else if(o == cancel) this.dispose();
}
public void printCurrentPage() {
try {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.defaultPage(pg.getPageFormat(0));
pj.setPrintable(new PsuedoPrintable());
javax.print.attribute.HashPrintRequestAttributeSet pra =
new javax.print.attribute.HashPrintRequestAttributeSet();
if(pj.printDialog(pra))
pj.print(pra);
}
catch(Exception ex) {
JOptionPane.showMessageDialog(null,ex.toString(), "Error in Printing", 1);
}
}
public void stateChanged(ChangeEvent ce) {
double temp = (double)slider.getValue()/100.0;
if(temp == scale)
return;
if(temp == 0) temp = 0.01;
scale = temp;
page[jcb.getSelectedIndex()].refreshScale();
this.validate();
}
class Page extends JLabel {
final int n;
final PageFormat pf;
java.awt.image.BufferedImage bi = null;
Dimension size = null;
public Page(int x, Dimension size) {
this.size = size;
bi = new java.awt.image.BufferedImage(size.width, size.height, java.awt.image.BufferedImage.TYPE_INT_RGB);
n = x;
pf = pg.getPageFormat(n);
Graphics g = bi.getGraphics();
Color c = g.getColor();
g.setColor(Color.white);
g.fillRect(0, 0, (int)pf.getWidth(), (int)pf.getHeight());
g.setColor(c);
try {
g.clipRect(0, 0, (int)pf.getWidth(), (int)pf.getHeight());
pg.getPrintable(n).print(g, pf, n);
}
catch(Exception ex) { }
this.setIcon(new ImageIcon(bi));
}
public void refreshScale() {
if(scale != 1.0)
this.setIcon(new ImageIcon(bi.getScaledInstance((int)(size.width*scale), (int)(size.height*scale), bi.SCALE_FAST)));
else
this.setIcon(new ImageIcon(bi));
this.validate();
}
}
class PsuedoPrintable implements Printable {
public int print(Graphics g, PageFormat fmt, int index) {
if(index > 0) return Printable.NO_SUCH_PAGE;
int n = jcb.getSelectedIndex();
try { return pg.getPrintable(n).print(g, fmt, n); }
catch(Exception ex) {}
return Printable.PAGE_EXISTS;
}
}
}
And my test class for printPrew
package printprew;
import javax.swing.*;
import java.awt.event.*;
import java.awt.print.*;
import java.text.*;
public class TestPr extends JFrame implements ActionListener{
PrinterJob pj = PrinterJob.getPrinterJob();
javax.print.attribute.HashPrintRequestAttributeSet att =
new javax.print.attribute.HashPrintRequestAttributeSet();
JEditorPane tp = null;
JTable tab = null;
public TestPr() {
super("Печать");
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setBottomComponent(createTable());
java.awt.Dimension d = this.getToolkit().getScreenSize();
this.setSize(d.width/2, d.height);
this.getContentPane().add(sp);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
sp.setDividerLocation(0.5);
this.validate();
}
private JPanel createTable() {
String val[][] = {{"т1", "тт1"}, {"т2","тт2"},{"т3","тт3"},
{"т4","тт4"}, {"т5","тт5"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т7","тт7"},{"т7","тт7"},
{"т7","тт7"},{"т7","тт7"},{"т7","тт7"},{"т7","тт7"},{"т7","тт7"}
};
String title[] = {"стобл1_назв","столб2_назв"};
tab = new JTable(val,title);
tab.setRowHeight(25);
tab.setFont(new java.awt.Font("Times New Roman",java.awt.Font.BOLD,16));
JButton b = new JButton("Просмотр таблицы");
b.addActionListener(this);
JPanel p = new JPanel(new java.awt.BorderLayout()), top = new JPanel(new java.awt.FlowLayout());
top.add(b);
p.add(top, "North");
p.add(new JScrollPane(tab), "Center");
return p;
}
public void actionPerformed(ActionEvent ae) {
PageFormat pf= pj.getPageFormat(att);
pf.setOrientation(PageFormat.LANDSCAPE);
new PrintPrew(tab.getPrintable(javax.swing.JTable.PrintMode.FIT_WIDTH,
new MessageFormat("Накладная"), new MessageFormat("{0}")),pf);
}
public static void main(String arg[]) {
new TestPr();
}
}
This table was created just for test my printPreview class. This table has 3 page. But my print prew all time show just last page. If I change the page for preview, it show same last page, but change number of page... And when I print same problem. Averytime print last page of table, just change the number of page. If I print whole document, it print 3 times last page with different number in the buttom.
What need to change?((

getGraphics() Is returning null value

My JPanel preview is returning null upon calling getGraphics() inside the drawToScreen method. The Test class does extend JPanel also since it's being kept within a TabbedPane. The class also implements Runnable, KeyListener and MouseListener
The log of System.out.println is
javax.swing.JPanel[,172,149,1280x720,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=null]
Below is a sample of the existing code. Running it won't work since it uses outside methods to complete itself but hopefully an answer can be found.
public Test() {
setBackground(Color.DARK_GRAY);
setLayout(null);
preview = new JPanel();
preview.setBounds(172, 149, 1280, 720);
add(preview);
}
public void addNotify() {
preview.addNotify();
if(thread == null) {
thread = new Thread(this);
preview.addKeyListener(this);
preview.addMouseListener(this);
thread.start();
}
}
private void init() {
image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_ARGB);
g = (Graphics2D) image.getGraphics();
running = true;
}
private long redraw() {
long t = System.currentTimeMillis();
if(onTab) {
if(!FileManager.isSleeping())
update();
if(!pause) {
draw();
drawToScreen();
}
}
return System.currentTimeMillis() - t;
}
public void run() {
init();
while(running) {
long durationMs = redraw();
try {
Thread.sleep(Math.max(0, FPS - durationMs));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void update () {
reupdateImages();
}
private void draw() {
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
for(int i = 0; i < layers.length; i++) {
if(layers[i] != null) {
g.drawImage(
layers[i].getImage(),
layers[i].getX(),
layers[i].getY(),
layers[i].getWidth(),
layers[i].getHeight(),
null
);
g.setColor(Color.red);
for(int j = 0; j < layers.length; j++) {
if(layers[j].isSelected())
g.drawRect(
layers[j].getX(),
layers[j].getY(),
layers[j].getWidth(),
layers[j].getHeight()
);
}
}
}
}
private void drawToScreen() {
System.out.println(preview);
System.out.println(preview.getGraphics());
Graphics g2 = preview.getGraphics();
g2.drawImage(image, 0, 0,
WIDTH, HEIGHT,
null);
panelImage = image;
g2.dispose();
}
As for the rest of the code, upon markspace's request I have added the rest of it just to debunk outside the provided sample.
#SuppressWarnings("serial")
public class ThumbnailEditor extends JPanel implements Runnable, KeyListener, MouseListener {
private JComboBox layerBox;
private int pos = 0;
private JFileChooser jfc;
// automated gui, I'm lazy and its dynamic
private int numberOfLayers = 24; // even numbers only guys and keep above 8
private JPanel preview;
private JSpinner localWidth;
private JSpinner localHeight;
private JSpinner posx;
private JSpinner posy;
private boolean ignore = false;
private JTextField width;
private JTextField height;
private JButton remove;
private JButton add;
private JButton select;
private JButton edit;
// drawing stoof
public int WIDTH = 1280;
public int HEIGHT = 720;
private Thread thread;
private boolean running;
private int FPS = 60;
private File location;
private BufferedImage panelImage;
private BufferedImage image;
private Graphics2D g;
private boolean pause = false;
private boolean onTab = false;
// when it gets too big, annoying issues start to happen with the text. This automatically fixes it
private static int[] overrideSizes = {
8,
9,
10,
11,
12,
14,
16,
18,
20,
22,
24,
26,
28,
36,
48,
72
};
// adjust this, low the more sensitive the changing of the font is.
private static int sensitivity = 4;
// layer stoof
// layer 0 --> at 0. layer 1 --> at 1
private static ThumbnailObject[] layers;
public static TextEditor[] te;
public ThumbnailEditor() {
setBackground(Color.DARK_GRAY);
setLayout(null);
preview = new JPanel();
preview.setBounds(172, 149, 1280, 720);
add(preview);
layerBox = new JComboBox();
layerBox.setBackground(Color.DARK_GRAY);
layerBox.setFont(new Font("Arial Black", Font.BOLD, 14));
layerBox.setBounds(10, 11, 100, 40);
add(layerBox);
add = new JButton("Add");
add.setBackground(Color.DARK_GRAY);
add.setFont(new Font("Arial Black", Font.BOLD, 14));
add.setBounds(120, 11, 100, 40);
add(add);
select = new JButton("Select");
select.setBackground(Color.DARK_GRAY);
select.setFont(new Font("Arial Black", Font.BOLD, 14));
select.setBounds(230, 11, 100, 40);
add(select);
edit = new JButton("Edit");
edit.setBackground(Color.DARK_GRAY);
edit.setFont(new Font("Arial Black", Font.BOLD, 14));
edit.setBounds(340, 11, 100, 40);
add(edit);
remove = new JButton("Remove");
remove.setBackground(Color.DARK_GRAY);
remove.setFont(new Font("Arial Black", Font.BOLD, 14));
remove.setBounds(450, 11, 100, 40);
add(remove);
JButton generate = new JButton("Generate Test Image");
generate.setBackground(Color.DARK_GRAY);
generate.setFont(new Font("Arial Black", Font.BOLD, 14));
generate.setBounds(1376, 11, 239, 40);
add(generate);
JButton deselect = new JButton("Deselect All Layers");
deselect.setBackground(Color.DARK_GRAY);
deselect.setFont(new Font("Arial Black", Font.BOLD, 14));
deselect.setBounds(120, 62, 210, 40);
add(deselect);
JLabel widthLabel = new JLabel("Width");
widthLabel.setHorizontalAlignment(SwingConstants.CENTER);
widthLabel.setForeground(Color.WHITE);
widthLabel.setFont(new Font("Arial Black", Font.BOLD, 14));
widthLabel.setBounds(10, 149, 70, 40);
add(widthLabel);
JLabel heightLabel = new JLabel("Height");
heightLabel.setHorizontalAlignment(SwingConstants.CENTER);
heightLabel.setFont(new Font("Arial Black", Font.BOLD, 14));
heightLabel.setForeground(Color.WHITE);
heightLabel.setBounds(90, 149, 70, 40);
add(heightLabel);
localWidth = new JSpinner();
localWidth.setFont(new Font("Arial Black", Font.BOLD, 14));
localWidth.setBounds(10, 184, 70, 20);
add(localWidth);
localHeight = new JSpinner();
localHeight.setFont(new Font("Arial Black", Font.BOLD, 14));
localHeight.setBounds(90, 184, 70, 20);
add(localHeight);
JLabel xSizeLabel = new JLabel("X");
xSizeLabel.setHorizontalAlignment(SwingConstants.CENTER);
xSizeLabel.setForeground(Color.WHITE);
xSizeLabel.setFont(new Font("Arial Black", Font.BOLD, 14));
xSizeLabel.setBounds(10, 215, 70, 40);
add(xSizeLabel);
JLabel ySizeLabel = new JLabel("Y");
ySizeLabel.setHorizontalAlignment(SwingConstants.CENTER);
ySizeLabel.setForeground(Color.WHITE);
ySizeLabel.setFont(new Font("Arial Black", Font.BOLD, 14));
ySizeLabel.setBounds(90, 215, 70, 40);
add(ySizeLabel);
posx = new JSpinner();
posx.setFont(new Font("Arial Black", Font.BOLD, 14));
posx.setBounds(10, 248, 70, 20);
add(posx);
posy = new JSpinner();
posy.setFont(new Font("Arial Black", Font.BOLD, 14));
posy.setBounds(92, 248, 70, 20);
add(posy);
pause = true;
layers = new ThumbnailObject[numberOfLayers];
te = new TextEditor[numberOfLayers];
for(int i = 0; i < layers.length; i++) {
layers[i] = new ThumbnailObject();
}
for(int i = 0; i < numberOfLayers; i++) {
layerBox.addItem("Layer [" + i + "]");
}
remove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
pos = layerBox.getSelectedIndex();
layers[pos].reset();
add.setToolTipText("");
if(te[pos] != null) {
te[pos].getFrame().dispose();
te[pos] = null;
}
}
});
select.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pos = layerBox.getSelectedIndex();
if(layers[pos].getImage() != null) {
for(int i = 0; i < layers.length; i++) {
layers[i].setSelected(false);
}
layers[pos].setSelected(true);
localWidth.setValue(layers[pos].getWidth());
localHeight.setValue(layers[pos].getHeight());
posx.setValue(layers[pos].getX());
posy.setValue(layers[pos].getY());
}
}
});
edit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pos = layerBox.getSelectedIndex();
if(layers[pos].getImage() != null) {
if(te[pos] != null) {
te[pos].getFrame().setVisible(true);
}
}
}
});
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
pos = layerBox.getSelectedIndex();
jfc = new JFileChooser();
jfc.setCurrentDirectory(new java.io.File("user.home"));
jfc.setDialogTitle("Select Layer 0 Image File");
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (jfc.showOpenDialog(add) == JFileChooser.APPROVE_OPTION) {
try {
layers[pos].setFile(jfc.getSelectedFile());
if(!layers[pos].isReversed())
if(layers[pos].getFile().getName().contains(".txt")) {
if(te[pos] == null)
te[pos] = new TextEditor(pos);
else
te[pos].getFrame().setVisible(true);
// load defaults, this will be overriden when saved
layers[pos].setFont(te[pos].getFont());
layers[pos].setAlignment(te[pos].getAlignment());
layers[pos].setSize(te[pos].getSize());
layers[pos].setColor(te[pos].getColor()[0], te[pos].getColor()[1], te[pos].getColor()[2]);
layers[pos].setBold(te[pos].isBold());
layers[pos].setItalic(te[pos].isItalic());
layers[pos].setAdjusted(te[pos].isAdjusted());
layers[pos].setWidth(te[pos].getWidth());
layers[pos].setHeight(te[pos].getHeight());
layers[pos].setImage(convertTextToImage(layers[pos].getFile(), pos));
} else
if(layers[pos].getFile().getName().contains("png") ||
layers[pos].getFile().getName().contains("jpg") ||
layers[pos].getFile().getName().contains("jpeg") ||
layers[pos].getFile().getName().contains("bmp")){
layers[pos].setImage(ImageIO.read(layers[pos].getFile()));
layers[pos].setX(0);
layers[pos].setY(0);
layers[pos].setWidth((int) (layers[pos].getImage().getWidth()));
layers[pos].setHeight((int) (layers[pos].getImage().getHeight()));
} else {
JOptionPane.showMessageDialog(null, "txt, png, jpg, and bmp files only!");
layers[pos].reset();
add.setToolTipText("");
if(te[pos] != null) {
te[pos].getFrame().dispose();
te[pos] = null;
}
return;
}
else {
reverseImage(pos);
}
edit.setEnabled(true);
add.setToolTipText(jfc.getSelectedFile().getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
pause = false;
deselect.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
for(int i = 0; i < numberOfLayers; i++) {
layers[i].setSelected(false);
}
}
});
generate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
generatePanel(null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
posx.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
for(int i = 0; i < layers.length; i++) {
if(layers[i].isSelected()) {
layers[i].setX((int) posx.getValue());
}
}
}
});
posy.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
for(int i = 0; i < layers.length; i++) {
if(layers[i].isSelected()) {
layers[i].setY((int) posy.getValue());
}
}
}
});
localWidth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
for(int i = 0; i < layers.length; i++) {
if(layers[i].isSelected())
layers[i].setWidth((int) localWidth.getValue());
}
}
});
localHeight.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(!ignore) {
for(int i = 0; i < layers.length; i++) {
if(layers[i].isSelected())
layers[i].setHeight((int) localHeight.getValue());
}
} else {
ignore = false;
}
}
});
}
public void addNotify() {
preview.addNotify();
preview.requestFocus();
preview.setFocusable(true);
preview.setVisible(true);
if(thread == null) {
thread = new Thread(this);
preview.addKeyListener(this);
preview.addMouseListener(this);
thread.start();
}
}
private void init() {
image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_ARGB);
g = (Graphics2D) image.getGraphics();
running = true;
}
private long redraw() {
long t = System.currentTimeMillis();
if(onTab) {
if(!FileManager.isSleeping())
update();
if(!pause) {
draw();
//drawToScreen();
}
}
return System.currentTimeMillis() - t;
}
public void run() {
init();
while(running) {
long durationMs = redraw();
try {
Thread.sleep(Math.max(0, FPS - durationMs));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void update () {
reupdateImages();
}
private void draw() {
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
for(int i = 0; i < layers.length; i++) {
if(layers[i] != null) {
g.drawImage(
layers[i].getImage(),
layers[i].getX(),
layers[i].getY(),
layers[i].getWidth(),
layers[i].getHeight(),
null
);
g.setColor(Color.red);
for(int j = 0; j < layers.length; j++) {
if(layers[j].isSelected())
g.drawRect(
layers[j].getX(),
layers[j].getY(),
layers[j].getWidth(),
layers[j].getHeight()
);
}
}
}
}
private void drawToScreen() {
System.out.println(preview);
System.out.println(preview.getGraphics());
Graphics g2 = preview.getGraphics();
g2.drawImage(image, 0, 0,
WIDTH, HEIGHT,
null);
panelImage = image;
g2.dispose();
}
public BufferedImage generateThumbnail() {
// so draw doesnt interfere
if(!pause) pause = true;
for(int i = 0; i < numberOfLayers; i++) {
layers[i].setSelected(false);
}
draw();
drawToScreen();
int genwidth = Integer.parseInt(width.getText());
int genheight = Integer.parseInt(height.getText());
// manipulate the width and height to specs
BufferedImage resized = new BufferedImage(genwidth, genheight, BufferedImage.TYPE_INT_ARGB);
Graphics g = resized.createGraphics();
g.drawImage(panelImage, 0, 0, genwidth, genheight, null);
g.dispose();
pause = false;
return resized;
}
public void deselect() {
for(int i = 0; i < numberOfLayers; i++) {
layers[i].setSelected(false);
}
}
private void generatePanel(String n) throws IOException {
if(!pause) pause = true;
for(int i = 0; i < numberOfLayers; i++) {
layers[i].setSelected(false);
}
draw();
drawToScreen();
String user = System.getProperty("user.name");
String location = FileManager.getMediaDirectory().replaceAll("/", "\\\\") + "\\";
int genwidth = WIDTH;
int genheight = HEIGHT;
// manipulate the width and height to specs
BufferedImage resized = new BufferedImage(genwidth, genheight, BufferedImage.TYPE_INT_ARGB);
Graphics g = resized.createGraphics();
g.drawImage(panelImage, 0, 0, genwidth, genheight, null);
g.dispose();
//print
File outputfile = null;
if(n == null || n == "")
outputfile = new File(location + "\\test.png");
else
outputfile = new File(n);
pause = false;
ImageIO.write(resized, "png", outputfile);
}
public static void reupdateImagesOverride() {
/* basically, this will update any changes thus
* if a char change happened, it will change ONLY if you are
* using root as your media center
*/
for(int i = 0; i < layers.length; i++) {
if(layers[i] != null && layers[i].getFile() != null && layers[i].getImage() != null) {
try {
if(!layers[i].isReversed()) {
if(layers[i].getFile().getName().contains(".txt")) {
layers[i].setImage(convertTextToImage(layers[i].getFile(), i));
layers[i].setWidth(layers[i].getImage().getWidth());
layers[i].setHeight(layers[i].getImage().getHeight());
} else
layers[i].setImage(ImageIO.read(layers[i].getFile()));
} else {
reverseImage(i);
}
try{
layers[i].collectTimeStamp();
} catch (Exception e2) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void reupdateImages() {
/* basically, this will update any changes thus
* if a char change happened, it will change ONLY if you are
* using root as your media center
*/
for(int i = 0; i < layers.length; i++) {
if(layers[i] != null && layers[i].getFile() != null && layers[i].getImage() != null) {
if(layers[i].getFile().lastModified() != layers[i].getTimeStamp()) {
try {
if(!layers[i].isReversed()) {
if(layers[i].getFile().getName().contains(".txt")) {
layers[i].setImage(convertTextToImage(layers[i].getFile(), i));
layers[i].setWidth(layers[i].getImage().getWidth());
layers[i].setHeight(layers[i].getImage().getHeight());
} else
layers[i].setImage(ImageIO.read(layers[i].getFile()));
} else {
reverseImage(i);
}
try{
layers[i].collectTimeStamp();
} catch (Exception e2) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
// really simple
public static BufferedImage convertTextToImage(File f, int i) {
try {
int tmpy = 0;
int type = Font.PLAIN;
if(layers[i].isBold()) type = Font.BOLD;
if(layers[i].isItalic()) type = type | Font.ITALIC;
layers[i].setFont(te[i].getFont());
layers[i].setAlignment(te[i].getAlignment());
layers[i].setSize(te[i].getSize());
layers[i].setColor(te[i].getColor()[0], te[i].getColor()[1], te[i].getColor()[2]);
layers[i].setBold(te[i].isBold());
layers[i].setItalic(te[i].isItalic());
layers[i].setAdjusted(te[i].isAdjusted());
layers[i].setWidth(te[i].getWidth());
layers[i].setHeight(te[i].getHeight());
// grab width of longest line, if it's multi-line
BufferedImage tmp = new BufferedImage(layers[i].getWidth(), layers[i].getHeight(), BufferedImage.TYPE_INT_ARGB);
BufferedImage actual;
BufferedImage ghetto;
Graphics2D gx = tmp.createGraphics();
gx.setColor(new Color(layers[i].getColor()[0], layers[i].getColor()[1], layers[i].getColor()[2]));
gx.setFont(new Font(layers[i].getFont(), type, layers[i].getSize()));
String line = null;
BufferedReader reader = new BufferedReader(new FileReader(f));
int longest = 0;
while((line = reader.readLine()) != null) {
if(gx.getFontMetrics().stringWidth(line) > longest) {
longest = gx.getFontMetrics().stringWidth(line);
}
}
// check if the image/text is longer then designated width
if(longest > layers[i].getWidth()) {
if(layers[i].isAdjusted()) {
int tmpnum = longest - layers[i].getWidth();
int reduce = 0;
while(tmpnum > sensitivity) {
tmpnum %= sensitivity;
reduce++;
}
for(int z = 0; z < overrideSizes.length; z++) {
if(overrideSizes[z] > layers[i].getSize()) {
if(z - reduce >= 0) {
layers[i].setSize(overrideSizes[z - reduce]);
if(layers[i].getAlignment().equals("right") || layers[i].getAlignment().equals("center")) {
if(z - (reduce + 1) >= 0) layers[i].setSize(overrideSizes[z - (reduce + 1)]);
}
} else {
layers[i].setSize(overrideSizes[0]);
}
break;
}
}
}
// draw to image, ignore controllers wish of width, we will do that later
actual = new BufferedImage(longest, layers[i].getHeight(), BufferedImage.TYPE_INT_ARGB);
gx.dispose();
tmp = null;
gx = actual.createGraphics();
gx.setColor(new Color(te[i].getColor()[0], te[i].getColor()[1], te[i].getColor()[2]));
gx.setFont(new Font(layers[i].getFont(), type, layers[i].getSize()));
reader.close();
reader = new BufferedReader(new FileReader(f));
while((line = reader.readLine()) != null) {
gx.drawString(line,0, (tmpy += gx.getFontMetrics().getHeight()));
}
reader.close();
// now lets resize this
ghetto = new BufferedImage(layers[i].getWidth(), layers[i].getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2x = ghetto.createGraphics();
g2x.drawImage(actual, 0, 0, layers[i].getWidth(), layers[i].getHeight(), null);
g2x.dispose();
return ghetto;
} else {
actual = new BufferedImage(layers[i].getWidth(), layers[i].getHeight(), BufferedImage.TYPE_INT_ARGB);
gx.dispose();
tmp = null;
gx = actual.createGraphics();
gx.setColor(new Color(te[i].getColor()[0], te[i].getColor()[1], te[i].getColor()[2]));
gx.setFont(new Font(layers[i].getFont(), type, layers[i].getSize()));
reader.close();
reader = new BufferedReader(new FileReader(f));
while((line = reader.readLine()) != null) {
if(layers[i].getAlignment().equals("left"))
gx.drawString(line,0, (tmpy += gx.getFontMetrics().getHeight()));
else
if(layers[i].getAlignment().equals("right"))
gx.drawString(line, layers[i].getWidth() - gx.getFontMetrics().stringWidth(line), (tmpy += gx.getFontMetrics().getHeight()));
else
if(layers[i].getAlignment().equals("center"))
gx.drawString(line, (layers[i].getWidth() / 2) - (gx.getFontMetrics().stringWidth(line) / 2), (tmpy += gx.getFontMetrics().getHeight()));
}
reader.close();
return actual;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void reverseImage(int i) {
BufferedImage tmp = new BufferedImage(
layers[i].getImage().getWidth(),
layers[i].getImage().getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics gx = tmp.createGraphics();
try {
if(layers[i].getFile().getName().contains(".txt")) {
layers[i].setImage(convertTextToImage(layers[i].getFile(), i));
} else
layers[i].setImage(ImageIO.read(layers[i].getFile()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gx.drawImage(
layers[i].getImage(),
layers[i].getImage().getWidth(),
0,
-layers[i].getImage().getWidth(),
layers[i].getImage().getHeight(),
null);
gx.dispose();
layers[i].setImage(tmp);
}
public void mouseClicked(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
// button is being held, scanning layers that match
if(arg0.getButton() == MouseEvent.BUTTON3) {
for(int i = 0; i < layers.length; i++) {
if(layers[i].getFile() != null && layers[i].getImage() != null && layers[i].isSelected()) {
if(layers[i].isReversed()) {
layers[i].setReversed(false);
reupdateImagesOverride();
return;
} else {
layers[i].setReversed(true);
reupdateImagesOverride();
return;
}
}
}
}
if(arg0.getButton() == MouseEvent.BUTTON1) {
for(int i = 0; i < layers.length; i++) {
if(layers[i].isSelected()) {
layers[i].setX(arg0.getX());
layers[i].setY(arg0.getY());
posx.setValue(arg0.getX());
posy.setValue(arg0.getY());
}
}
}
}
public void mouseReleased(MouseEvent arg0) {
}
public void keyPressed(KeyEvent arg0) {
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
public void setOnTab(boolean b) {
onTab = b;
}
}
Don't override addNotify!
A JPanel has a Graphics instance only, and only if it is added to a parent container.
The Graphics instance is built during Component.addNotify() but you overrided it, preventing it to be created.
Maybe try to call super.addNotify() as a quick workaround.

Fail to reset the panel to initial state

I have problem with the Play Again button, which is to reset the panel to initial state.
The Play Again button should reset the panel, it does reshuffle the gameList, but not reset the panel, which means all the buttons remain and lost the ActionListener function.
Here is my program :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import static java.util.Collections.*;
public class MemoryGame extends JFrame
{
private JButton exitButton, replayButton;
private JButton[] gameButton = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<Integer>();
private int counter = 0;
private int[] buttonID = new int[2];
private int[] buttonValue = new int[2];
public static Point getCenterPosition(int frameWidth, int frameHeight)
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
int x = (dimension.width - frameWidth)/2;
int y = (dimension.height - frameHeight)/2;
return (new Point(x,y));
}
public MemoryGame(String title)
{
super(title);
initial();
}
public void initial()
{
for (int i = 0; i < gameButton.length; i++)
{
gameButton[i] = new JButton();
gameButton[i].setFont(new Font("Serif", Font.BOLD, 28));
gameButton[i].addActionListener(new ButtonListener());
}
exitButton = new JButton("Exit");
replayButton = new JButton("Play Again");
exitButton.addActionListener(new ButtonListener());
replayButton.addActionListener(new ButtonListener());
Panel gamePanel = new Panel();
gamePanel.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameButton.length; i++)
{
gamePanel.add(gameButton[i]);
}
Panel buttonPanel = new Panel();
buttonPanel.add(replayButton);
buttonPanel.add(exitButton);
buttonPanel.setLayout(new GridLayout(1, 0));
add(gamePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
for (int i = 0; i < 2; i++)
{
for (int j = 1; j < (gameButton.length / 2) + 1; j++)
{
gameList.add(j);
}
}
shuffle(gameList);
int newLine = 0;
for (int a = 0; a < gameList.size(); a++)
{
newLine++;
System.out.print(" " + gameList.get(a));
if (newLine == 4)
{
System.out.println();
newLine = 0;
}
}
}
public boolean sameValues()
{
if (buttonValue[0] == buttonValue[1])
{
return true;
}
return false;
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (exitButton == e.getSource())
{
System.exit(0);
}
else if (replayButton == e.getSource())
{
initial();
}
for (int i = 0; i < gameButton.length; i++)
{
if (gameButton[i] == e.getSource())
{
gameButton[i].setText("" + gameList.get(i));
gameButton[i].setEnabled(false);
counter++;
if (counter == 3)
{
if (sameValues())
{
gameButton[buttonID[0]].setEnabled(false);
gameButton[buttonID[1]].setEnabled(false);
}
else
{
gameButton[buttonID[0]].setEnabled(true);
gameButton[buttonID[0]].setText("");
gameButton[buttonID[1]].setEnabled(true);
gameButton[buttonID[1]].setText("");
}
counter = 1;
}
if (counter == 1)
{
buttonID[0] = i;
buttonValue[0] = gameList.get(i);
}
if (counter == 2)
{
buttonID[1] = i;
buttonValue[1] = gameList.get(i);
}
}
}
}
}
public static void main(String[] args)
{
int x, y;
int width = 500;
int height = 500;
Point position = getCenterPosition(width, height);
x = position.x;
y = position.y;
JFrame frame = new MemoryGame("Memory Game");
frame.setBounds(x, y, width, height);
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
How can I solve this problem?
EDIT :
Another problem is after reset(), all buttons seem like become sameValue(). I have insert some audio to the buttons, and it's happen in the condition of the ButtonListener. Here is the part :
if (counter == 3)
{
if (sameValues())
{
gameButton[buttonID[0]].setEnabled(false);
gameButton[buttonID[1]].setEnabled(false);
}
Seems like it's satisfy the condition sameValue(), but why?
LATEST UPDATE :
Problem Solved. Latest code is not uploaded.
In the initial() method the code is creating a new GUI. It would be preferable to retain handles to the original controls, and reset them to a 'begin game' state and the correct values (for number).
Alternatives with your current method are to remove() and add() new for every component (not recommended) or to use a CardLayout (not necessary - see first suggestion).
Ok, I've fixed your code.
Be sure to check out my comment to your question and let me know if it works (I did a quick test and it went fine)
package varie;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import static java.util.Collections.shuffle;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MemoryGame extends JFrame {
private JButton exitButton, replayButton;
private JButton[] gameButton = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<>();
private int counter = 0;
private int[] buttonID = new int[2];
private int[] buttonValue = new int[2];
public static Point getCenterPosition(int frameWidth, int frameHeight) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
int x = (dimension.width - frameWidth) / 2;
int y = (dimension.height - frameHeight) / 2;
return (new Point(x, y));
}
public MemoryGame(String title) {
super(title);
initial();
}
public void initial() {
for (int i = 0; i < gameButton.length; i++) {
gameButton[i] = new JButton();
gameButton[i].setFont(new Font("Serif", Font.BOLD, 28));
gameButton[i].addActionListener(new ButtonListener());
}
exitButton = new JButton("Exit");
replayButton = new JButton("Play Again");
exitButton.addActionListener(new ButtonListener());
replayButton.addActionListener(new ButtonListener());
Panel gamePanel = new Panel();
gamePanel.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameButton.length; i++) {
gamePanel.add(gameButton[i]);
}
Panel buttonPanel = new Panel();
buttonPanel.add(replayButton);
buttonPanel.add(exitButton);
buttonPanel.setLayout(new GridLayout(1, 0));
add(gamePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
for (int i = 0; i < 2; i++) {
for (int j = 1; j < (gameButton.length / 2) + 1; j++) {
gameList.add(j);
}
}
shuffle(gameList);
int newLine = 0;
for (int a = 0; a < gameList.size(); a++) {
newLine++;
System.out.print(" " + gameList.get(a));
if (newLine == 4) {
System.out.println();
newLine = 0;
}
}
}
public boolean sameValues() {
if (buttonValue[0] == buttonValue[1]) {
return true;
}
return false;
}
public void reset() {
for(int i = 0; i< gameButton.length; i++){
gameButton[i].setEnabled(true);
gameButton[i].setText("");
for(ActionListener al : gameButton[i].getActionListeners()){
gameButton[i].removeActionListener(al);
}
gameButton[i].addActionListener(new ButtonListener());
}
buttonID = new int[2];
buttonValue = new int[2];
counter = 0;
shuffle(gameList);
int newLine = 0;
for (int a = 0; a < gameList.size(); a++) {
newLine++;
System.out.print(" " + gameList.get(a));
if (newLine == 4) {
System.out.println();
newLine = 0;
}
}
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (exitButton.equals(e.getSource())) {
System.exit(0);
} else if (replayButton.equals(e.getSource())) {
reset();
} else {
for (int i = 0; i < gameButton.length; i++) {
if (gameButton[i].equals(e.getSource())) {
gameButton[i].setText("" + gameList.get(i));
gameButton[i].setEnabled(false);
counter++;
if (counter == 3) {
if (sameValues()) {
gameButton[buttonID[0]].setEnabled(false);
gameButton[buttonID[1]].setEnabled(false);
} else {
gameButton[buttonID[0]].setEnabled(true);
gameButton[buttonID[0]].setText("");
gameButton[buttonID[1]].setEnabled(true);
gameButton[buttonID[1]].setText("");
}
counter = 1;
}
if (counter == 1) {
buttonID[0] = i;
buttonValue[0] = gameList.get(i);
}
if (counter == 2) {
buttonID[1] = i;
buttonValue[1] = gameList.get(i);
}
}
}
}
}
}
public static void main(String[] args) {
int x, y;
int width = 500;
int height = 500;
Point position = getCenterPosition(width, height);
x = position.x;
y = position.y;
JFrame frame = new MemoryGame("Memory Game");
frame.setBounds(x, y, width, height);
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Categories