getGraphics() Is returning null value - java
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.
Related
How can i add photo to label and save it to folder?
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.
JPanel is SOMETIMES not responding to mouse clicks
I have some custom JPanels that are used as buttons. This works well 90% of the time, however, sometimes the GUI doesn't respond to a mouse click - the mouseClicked event is not triggered and you have to click again (sometimes even more than once) to actually trigger it. This behavior appears to be random, though I have the feeling that it occurs more frequently after having moved the frame to another monitor. Here is the code: public class EatingMouse extends JFrame implements MouseListener { JPanel contentPane; int contentPanelWidth, contentPanelHeight; int mainTabMarginHeight, mainTabMarginWidth; int subTabMarginHeight, subTabMarginWidth; Color fontColor = Color.WHITE; Color tabBackgroundColor = Color.BLACK; Color tabBackgroundHighlightColor = Color.GRAY; Color tabBackgroundSelectedColor = Color.LIGHT_GRAY; TabPanel firstMainTab; TabPanel secondMainTab; ArrayList<TabPanel> firstSubTabs; ArrayList<TabPanel> secondSubTabs; ArrayList<TabPanel> currentSubTabs; int clickCounter; public EatingMouse() { super("Why do you eat mouse clicks?"); JLayeredPane layeredPane = new JLayeredPane(); firstMainTab = new TabPanel("First Tab", 18); firstMainTab.addMouseListener(this); layeredPane.add(firstMainTab, new Integer(100)); secondMainTab = new TabPanel("Second Tab", 18); secondMainTab.addMouseListener(this); layeredPane.add(secondMainTab, new Integer(100)); firstSubTabs = new ArrayList<>(); secondSubTabs = new ArrayList<>(); currentSubTabs = new ArrayList<>(); TabPanel tp = new TabPanel("First First Subtab", 14); tp.addMouseListener(this); layeredPane.add(tp, new Integer(100)); firstSubTabs.add(tp); tp = new TabPanel("Second First Subtab", 14); tp.addMouseListener(this); layeredPane.add(tp, new Integer(100)); firstSubTabs.add(tp); tp = new TabPanel("First Second Subtab", 14); tp.addMouseListener(this); layeredPane.add(tp, new Integer(100)); secondSubTabs.add(tp); tp = new TabPanel("Second Second Subtab", 14); tp.addMouseListener(this); layeredPane.add(tp, new Integer(100)); secondSubTabs.add(tp); contentPane = new JPanel(new BorderLayout()); setContentPane(contentPane); contentPane.add(layeredPane); mainTabMarginWidth = 40; mainTabMarginHeight = 8; subTabMarginWidth = 20; subTabMarginHeight = 10; selectTabs(0, 1); clickCounter = 0; setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(new Dimension(800, 600)); setVisible(true); } public void selectTabs(int mainTab, int subTab) { boolean hasChanged = false; if((mainTab == 0) && !firstMainTab.isSelected) { hasChanged = true; firstMainTab.setSelected(true); secondMainTab.setSelected(false); for(TabPanel tp : currentSubTabs) { tp.setSelected(false); tp.setVisible(false); } currentSubTabs = firstSubTabs; for(TabPanel tp : currentSubTabs) { tp.setVisible(true); } currentSubTabs.get(subTab).setSelected(true); } else if((mainTab == 1) && !secondMainTab.isSelected) { hasChanged = true; firstMainTab.setSelected(false); secondMainTab.setSelected(true); for(TabPanel tp : currentSubTabs) { tp.setSelected(false); tp.setVisible(false); } currentSubTabs = secondSubTabs; for(TabPanel tp : currentSubTabs) { tp.setVisible(true); } currentSubTabs.get(subTab).setSelected(true); } else if((mainTab == 0) && firstMainTab.isSelected) { hasChanged = true; for(TabPanel tp : currentSubTabs) { if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); } else { tp.setSelected(true); } } } else if((mainTab == 1) && secondMainTab.isSelected) { hasChanged = true; for(TabPanel tp : currentSubTabs) { if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); } else { tp.setSelected(true); } } } if(hasChanged) { revalidate(); repaint(); } } #Override public void paint(Graphics graphics) { super.paint(graphics); contentPanelWidth = getContentPane().getWidth(); contentPanelHeight = getContentPane().getHeight(); int xOffset = 100; int yOffset = 100; FontMetrics mainTabMetrics = graphics.getFontMetrics(firstMainTab.label.getFont()); firstMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(firstMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight)); xOffset += firstMainTab.getBounds().width; secondMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(secondMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight)); FontMetrics subTabMetrics = graphics.getFontMetrics(currentSubTabs.get(0).label.getFont()); xOffset = 100; yOffset += firstMainTab.getBounds().height; for(TabPanel tp : currentSubTabs) { tp.setBounds(xOffset, yOffset, (subTabMetrics.stringWidth(tp.text) + subTabMarginWidth), (subTabMetrics.getHeight() + subTabMarginHeight)); tp.revalidate(); tp.repaint(); xOffset += tp.getBounds().width; } } #Override public void mouseClicked(MouseEvent e) { System.out.println("click " + clickCounter++); Object source = e.getSource(); if(source == firstMainTab && !firstMainTab.isSelected) { secondMainTab.setSelected(false); if(currentSubTabs.get(1).isSelected) { selectTabs(0, 1); } else { selectTabs(0, 0); } } else if(source == secondMainTab && !secondMainTab.isSelected) { if(currentSubTabs.get(1).isSelected) { selectTabs(1, 1); } else { selectTabs(1, 0); } } } #Override public void mouseEntered(MouseEvent e) { Object source = e.getSource(); if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundHighlightColor); } else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundHighlightColor); } else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) { ((TabPanel)source).setBackground(tabBackgroundHighlightColor); } } #Override public void mouseExited(MouseEvent e) { Object source = e.getSource(); if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundColor); } else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundColor); } else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) { ((TabPanel)source).setBackground(tabBackgroundColor); } } #Override public void mousePressed(MouseEvent e) { } #Override public void mouseReleased(MouseEvent e) { } public class TabPanel extends JPanel { JLabel label; String text; boolean isSelected; public TabPanel(String labelText, int fontSize) { super(); text = labelText; isSelected = false; setLayout(new GridBagLayout()); setBackground(tabBackgroundColor); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.PAGE_START; gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 0.1; gbc.weightx = 0.1; gbc.insets = new Insets(0,0,0,0); label = new JLabel("<html><div style=\"text-align:center\"> " + text + "</div></html>", SwingConstants.CENTER); label.setAlignmentX(JLabel.CENTER_ALIGNMENT); label.setForeground(fontColor); label.setFont(new Font("Arial", Font.BOLD, fontSize)); add(label, gbc); } public void setSelected(boolean selected) { isSelected = selected; if(selected) { setBackground(tabBackgroundSelectedColor); } else { setBackground(tabBackgroundColor); } } public boolean isSelected() { return isSelected; } #Override public String toString() { return text + " - " + label.getFont().getSize(); } } public static void main(String[] args) { new EatingMouse(); } } Please note that I have chosen JPanels as buttons because I want to heavily customize them later, which I didn't get to work with extending JButton. Thank you for your time reading this and of course I would appreciate any leads on why this is happening and what I can do to improve this code.
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); } } }
Accessing a string from another class in Java
This is slightly different from the usual issue. I know how I would do this if I could set the string to public static String passcode;but the problem is I can't. I need a solution from what I am trying to achieve here: public class EncryptionSubtask { public static void main(String[] args) { Main m2 = new Main(); m2.setVisible(true); m2.setResizable(true); m2.setLayout(new FlowLayout()); } public EncryptionSubtask() { log("Running Substask"); Random rand = new Random(); int n1 = 33 + rand.nextInt(94); int n2 = 33 + rand.nextInt(94); int n3 = 33 + rand.nextInt(94); int n4 = 33 + rand.nextInt(94); int n5 = 33 + rand.nextInt(94); int n6 = 33 + rand.nextInt(94); int n7 = 33 + rand.nextInt(94); int n8 = 33 + rand.nextInt(94); String c1 = Character.toString ((char) n1); String c2 = Character.toString ((char) n2); String c3 = Character.toString ((char) n3); String c4 = Character.toString ((char) n4); String c5 = Character.toString ((char) n5); String c6 = Character.toString ((char) n6); String c7 = Character.toString ((char) n7); String c8 = Character.toString ((char) n8); String passcode = (c1+c2+c3+c4+c5+c6+c7+c8); System.out.println(passcode); } Where I want to get "passcode" to here: public class Main extends Frame implements Runnable, KeyListener, MouseListener, WindowListener { private static final long serialVersionUID = 1L; Thread thread; BufferedImage backbuffer; Graphics2D g2d; AffineTransform transform = new AffineTransform(); enum Modes { Menu, Encrypt, Decrypt } Modes mode = Modes.Menu; public Image background; public static void main(String[] args) { Main m = new Main(); m.setVisible(true); m.setResizable(true); m.setLayout(new FlowLayout()); } #Override public void windowActivated(WindowEvent e) { } #Override public void windowClosed(WindowEvent e) { } #Override public void windowClosing(WindowEvent e) { dispose(); log("Exiting..."); System.exit(0); } #Override public void windowDeactivated(WindowEvent e) { } #Override public void windowDeiconified(WindowEvent e) { } #Override public void windowIconified(WindowEvent e) { } #Override public void windowOpened(WindowEvent e) { } #Override public void mouseClicked(MouseEvent e) { int x = e.getX() - 8; int y = e.getY() - 30; // System.out.println(y); if (x >= 50 && x <= 143 && y >= 50 && y <= 75) { //if statement for encrypt button bounds log("Button Pressed. Encrypt Screen Opened."); // Frame f = new Frame(); // f.setVisible(true); // f.setSize(100, 100); mode = Modes.Encrypt; new EncryptionSubtask(); } if (x >= 500 && x <= 595 && y >= 50 && y <= 75) { // if statement for decrypt button bounds log("Button Pressed. Decrypt Screen Opened."); mode = Modes.Decrypt; } } #Override public void mouseEntered(MouseEvent e) { } #Override public void mouseExited(MouseEvent e) { } #Override public void mousePressed(MouseEvent e) { } #Override public void mouseReleased(MouseEvent e) { } #Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); System.out.println("Key pressed = " + key); if (key == 27) { mode = Modes.Menu; } } #Override public void keyReleased(KeyEvent e) { } #Override public void keyTyped(KeyEvent e) { } public enum LogLevel { Info, Warn } private static int width = 300; private static int height = width / 16 * 9; private static int scale = 3; public Main() { addWindowListener(this); log("Initialising..."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } this.start(); log("Setting title..."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } this.setTitle("LOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOL"); log("Creating backbuffer for window..."); setSize(width * scale, height * scale); backbuffer = new BufferedImage(640 * 3, 480 * 2, BufferedImage.TYPE_INT_RGB); log("Buffering Image, standby..."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } g2d = backbuffer.createGraphics(); File fileThis = new File(System.getProperty("java.class.path")); File parentFile = fileThis.getAbsoluteFile().getParentFile(); // the // project // folder log(parentFile.getAbsolutePath()); File resources = new File(parentFile.toString() + "/resources/"); log(resources.getAbsolutePath()); try { background = ImageIO.read(new File(resources + "/guitar.jpg")); // CHANGE // THIS // IMAGE! File tempFile = new File(resources + "/guitar.jpg"); log(tempFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } addKeyListener(this); addMouseListener(this); } #Override public void run() { Thread t = Thread.currentThread(); while (t == thread) { try { // log("Running..."); Thread.sleep(20); } catch (Exception e) { e.printStackTrace(); } repaint(); } } public void start() { thread = new Thread(this); thread.start(); } public void stop() { try { thread.join(); } catch (Exception e) { e.printStackTrace(); } } public void update(Graphics g) { g2d.setTransform(transform); g2d.setPaint(Color.black); g2d.fillRect(0, 0, getWidth(), getHeight()); switch (mode) { case Menu: g2d.drawImage(background, 0, 0, getWidth(), getHeight(), this); g2d.setPaint(Color.blue); g2d.fillRect(50, 50, 93, 25); g2d.fillRect(500, 50, 95, 25); g2d.setPaint(Color.red); g2d.setFont(new Font("TimesRoman", Font.PLAIN, 30)); g2d.drawString("Encrypt", 50, 70); g2d.drawString("Decrypt", 500, 70); break; case Encrypt: g2d.setPaint(Color.green); g2d.drawString("Encrypt screen", 50, 70); break; case Decrypt: g2d.setPaint(Color.green); g2d.drawString("Decrypt Screen", 50, 70); break; } paint(g); } public void log(String s) { log(s, 0, 0); } public void log(String s, int i) { log(s, i, 0); } public void log(String s, int i, int j) { String logmsg = ""; for (int k = 0; k < i; k++) { logmsg += " "; } if (j == 0) { logmsg = "[Info]" + logmsg; } else { logmsg = "[Warn]" + logmsg; } System.out.println("[" + System.currentTimeMillis() + "][" + Thread.currentThread().getStackTrace()[1].toString() + "]" + logmsg + s); } public void paint(Graphics g) { g.drawImage(backbuffer, 8, 31, this); } } So that I can use it to be drawn to my frame etc.
Okay, you call the constructor of EncryptionSubtask in the mouseClicked method and you do nothing with it. First of all, you need to assign it to a variable, like this: EncryptionSubtask veryStrangeTask = new EncryptionSubtask(); Than have the local variable passcode as a class field like this: public class EncryptionSubtask { String passcode; ... } Now you can use this field in your "other" class with veryStrangeTask.passcode;
Maybe an Observer? You could create an interface which has a method to pass your passcode public interface PasscodeNotify{ public void notifyPasscode(String passcode); } Then you modify EncryptionSubtask constructor to accept an instance of this class, this way: public EncryptionSubtask(PasscodeNotify observer) { ... if(observer != null) observer.notifyPasscode(c1+c2+c3+c4+c5+c6+c7+c8); } And finally you make that your Main class implements another interface, the PasscodeNotify I just created, and implements the method to retrieve your passcode. Does it serves your purpose? Hope it helps!
setFont slows down the execution of the program
i have this class,on which i noticed if i use setFont(...) it 'll slow down the execution of the entire program. public class MenuState extends GameState { private String[] options = { "Start ", "Options","Quit"}; private int currentSelection; private Font font; protected MenuState(GameStateManager gameStateManager) { super(gameStateManager); init(); } public void init() { currentSelection = 0; font = new Font("Times New Roman", Font.BOLD, 30); } public void update() { } public void render(Graphics graphic) { for (int i = 0; i < options.length; i++) { if (i == currentSelection) { graphic.setColor(Color.GREEN); } else { graphic.setColor(Color.BLACK); } if (i == 0) { graphic.setFont(font); graphic.drawString(options[i], GuiDimension.WIDTH.getValue() / 2 - 47, 500); } if (i == 1) { graphic.setFont(font); graphic.drawString(options[i], GuiDimension.WIDTH.getValue() / 2 - 107, 550); } if (i == 2) { graphic.setFont(font); graphic.drawString(options[i], GuiDimension.WIDTH.getValue() / 2 - 47, 600); } } } now if if I comment this row: graphic.setFont(font); the execution is normal otherwise it is slow. someone can tell me the reason?