setFont slows down the execution of the program - java

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?

Related

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.

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.

Why is my simple java2d Space Invaders game lagging?

I'm currently making a space invaders-esque game for my software engineering course. I've already got everything working that satisfies the requirements, so this isn't a 'solve my homework' kind of question. My problem is that the game will lag (at what seems like random times & intervals) to the point where it becomes too frustrating to play. Some things I think might be causing this - though I'm not positive - are as follows:
Problem with timer event every 10 ms (I doubt this because of the very limited resources required for this game).
Problem with collision detection (checking for collision with every visible enemy every 10 ms seems like it would take up a large chunk of resources)
Problem with repainting? This seems unlikely to me however...
#SuppressWarnings("serial")
public class SIpanel extends JPanel {
private SIpanel panel;
private Timer timer;
private int score, invaderPace, pulseRate, mysteryCount, distanceToEdge;
private ArrayList<SIthing> cast;
private ArrayList<SIinvader> invaders, dead;
private ArrayList<SImissile> missileBase, missileInvader;
private SIinvader[] bottomRow;
private SIbase base;
private Dimension panelDimension;
private SImystery mysteryShip;
private boolean gameOver, left, right, mysteryDirection, space, waveDirection;
private boolean runningTimer;
private Music sound;
private void pulse() {
pace();
processInputs();
if (gameOver) gameOver();
repaint();
}
private void pace() {
// IF invaders still live
if (!invaders.isEmpty()) {
invaderPace++;
// Switch back manager
if (distanceToEdge <= 10) {
switchBack();
pulseRate = (pulseRate >= 16) ? (int) (pulseRate*(0.8)) : pulseRate;
waveDirection = !waveDirection;
distanceToEdge = calculateDistanceToEdge();
}
// Move invaders left/right
else if (invaderPace >= pulseRate) {
invaderPace = 0;
distanceToEdge = calculateDistanceToEdge();
moveAI();
invadersFire();
if (!dead.isEmpty()) removeDead();
if (mysteryCount < 1) tryInitMysteryShip();
}
// All invaders are kill, create new wave
} else if (missileBase.isEmpty() && missileInvader.isEmpty() && !cast.contains(mysteryShip)) {
// System.out.println("New Wave!");
newWave();
}
// Every pace
if (!missileBase.isEmpty()) moveMissileBase();
// Every two paces
if (invaderPace % 2 == 0) {
if (!missileInvader.isEmpty()) moveMissileInvader();
if (mysteryCount > 0) moveMysteryShip();
}
}
private void processInputs() {
if (left) move(left);
if (right) move(!right);
if (space) fireMissile(base, true);
}
protected void fireMissile(SIship ship, boolean isBase) {
if(isBase && missileBase.isEmpty()) {
base.playSound();
SImissile m = new SImissile(ship.getX()+(ship.getWidth()/2), ship.getY()-(ship.getHeight()/4));
missileBase.add(m);
cast.add(m);
} else if (!isBase && missileInvader.size()<3) {
base.playSound();
SImissile m = new SImissile(ship.getX()+(ship.getWidth()/2), ship.getY()+(ship.getHeight()/4));
missileInvader.add(m);
cast.add(m);
}
}
private void newWave() {
pulseRate = 50;
int defaultY=60, defaultX=120, defaultWidth=30, defaultHeight=24;
for(int i=0; i<5; i++) {
for(int j=0; j<10; j++) {
if (i<1) invaders.add(new SItop((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
else if (i<3) invaders.add(new SImiddle((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
else if (i<5) invaders.add(new SIbottom((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
}
}
for (SIinvader s: invaders) {
cast.add(s);
}
if (!cast.contains(base)) {
cast.add(base);
}
bottomRow = getBottomRow();
}
private void tryInitMysteryShip() {
Random rand = new Random();
int x=rand.nextInt(1000);
if (x<=3) {
mysteryCount = 1;
if (rand.nextBoolean()) {
mysteryDirection = true;
}
if (mysteryDirection) {
mysteryShip = new SImystery(0, 60, 36, 18);
} else {
mysteryShip = new SImystery(480, 60, 36, 18);
}
cast.add(mysteryShip);
}
}
private void moveMysteryShip() {
int distance = 0;
if (mysteryDirection) {
mysteryShip.moveRight(5);
distance = getWidth() - mysteryShip.getX();
} else {
mysteryShip.moveLeft(5);
distance = 30+mysteryShip.getX()-mysteryShip.getWidth();
}
if (distance <= 5) {
dead.add(mysteryShip);
mysteryShip = null;
mysteryCount = 0;
}
}
private void removeDead() {
#SuppressWarnings("unchecked")
ArrayList<SIinvader> temp = (ArrayList<SIinvader>) dead.clone();
dead.clear();
for (SIinvader s : temp) {
invaders.remove(s);
cast.remove(s);
}
bottomRow = getBottomRow();
}
private void invadersFire() {
int[] p = new int[bottomRow.length];
for (int i=0; i<p.length; i++) {
for (int j=0; j<p.length; j++) {
p[j] = j;
}
Random rand = new Random();
int a=rand.nextInt(101);
if (a>=20) {
int b=rand.nextInt(p.length);
fireMissile(bottomRow[b], false);
}
}
}
private int calculateDistanceToEdge() {
int distance = 0;
SIinvader[] outliers = getOutliers();
if (waveDirection) {
distance = getWidth() - outliers[0].getX()-outliers[0].getWidth();
} else {
distance = outliers[1].getX();
}
return distance;
}
private SIinvader[] getOutliers() {
SIinvader leftMost = invaders.get(0), rightMost = invaders.get(0);
for (SIinvader s : invaders) {
if (s.getX() < leftMost.getX()) {
leftMost = s;
}
if (s.getX() > rightMost.getX()) {
rightMost = s;
}
}
return new SIinvader[] { rightMost, leftMost };
}
private SIinvader[] getBottomRow() {
SIinvader[] x = new SIinvader[(invaders.size()>10)?10:invaders.size()];
for (int i=0; i<x.length; i++) {
x[i] = invaders.get(i);
for (SIinvader s:invaders) {
if (s.getX() == x[i].getX()) {
if (s.getY() > x[i].getY()) {
x[i] = s;
}
}
}
}
return x;
}
private void move(boolean b) {
int defaultX = 5;
if (b) base.moveLeft(defaultX);
else base.moveRight(defaultX);
}
private void moveAI() {
for(SIinvader s : invaders) {
s.changeImage();
int defaultX = 5;
if (waveDirection) s.moveRight(defaultX);
else s.moveLeft(defaultX);
}
}
private void moveMissileBase() {
if (invaders.isEmpty()) return;
int movement = -5, bound = 0;
SImissile missile = missileBase.get(0);
missile.moveDown(movement);
SIinvader lowestInvader = getLowestInvader();
if (missile.getY() < (lowestInvader.getY() + lowestInvader.getHeight())) {
for (SIinvader s:bottomRow) {
if (checkCollision(missile, s)) {
s.setHit();
dead.add(s);
cast.remove(missile);
missileBase.clear();
score += s.value;
return;
}
}
if (mysteryCount > 0) {
if (checkCollision(missile, mysteryShip)) {
mysteryShip.setHit();
dead.add(mysteryShip);
cast.remove(missile);
missileBase.clear();
score += mysteryShip.value;
return;
}
}
if (missile.getY() < bound) {
missileBase.remove(missile);
cast.remove(missile);
}
}
}
private SIinvader getLowestInvader() {
SIinvader lowest = bottomRow[0];
for (SIinvader invader : bottomRow) {
if (invader.getY() > lowest.getY()) {
lowest = invader;
}
}
return lowest;
}
private void moveMissileInvader() {
int movement = 5, bound = (int) panelDimension.getHeight();
for (SImissile missile : missileInvader) {
missile.moveDown(movement);
if(missile.getY() >= base.getY()) {
if (checkCollision(missile, base)) {
base.setHit();
gameOver = true;;
missileInvader.remove(missile);
cast.remove(missile);
return;
} else if (missile.getY() >= bound-25) {
missileInvader.remove(missile);
cast.remove(missile);
return;
}
}
}
}
private boolean checkCollision(SIthing missile, SIthing ship) {
Rectangle2D rect1 = new Rectangle2D.Double(
missile.getX(),
missile.getY(),
missile.getWidth(),
missile.getHeight()
);
Rectangle2D rect2 = new Rectangle2D.Double(
ship.getX(),
ship.getY(),
ship.getWidth(),
ship.getHeight()
);
return rect1.intersects(rect2);
}
private void switchBack() {
int defaultY = 12;
for (SIinvader s : invaders) {
if (s.getY() > getHeight()) {
gameOver = true;
return;
}
s.moveDown(defaultY);
}
}
private void gameOver() {
pause(true);
SI.setGameOverLabelVisibile(true);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.GREEN);
Font font = new Font("Arial", 0, 20);
setFont(font);
String score = "Score: "+this.score;
Rectangle2D rect = font.getStringBounds(score, g2.getFontRenderContext());
int screenWidth = 0;
try { screenWidth = (int) panelDimension.getWidth(); }
catch (NullPointerException e) {}
g2.setColor(Color.GREEN);
g2.drawString(score, (int) (screenWidth - (10 + rect.getWidth())), 20);
for(SIthing a:cast) {
a.paint(g);
}
}
public SIpanel() {
super();
setBackground(Color.BLACK);
cast = new ArrayList<SIthing>();
missileBase = new ArrayList<SImissile>();
score = invaderPace = mysteryCount = pulseRate = 0;
sound = new Music("AmbientMusic.wav");
panel = this;
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : left = true; break;
case KeyEvent.VK_RIGHT : right = true; break;
case KeyEvent.VK_SPACE : space = true; break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : left = false; break;
case KeyEvent.VK_RIGHT : right = false; break;
case KeyEvent.VK_SPACE : space = false; break;
}
}
});
setFocusable(true);
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pulse();
}
});
}
public void reset() {
SI.setGameOverLabelVisibile(false);
score = invaderPace = mysteryCount = 0;
pulseRate = 50;
cast = new ArrayList<SIthing>();
invaders = new ArrayList<SIinvader>();
dead = new ArrayList<SIinvader>();
missileBase = new ArrayList<SImissile>();
missileInvader = new ArrayList<SImissile>();
base = new SIbase(230, 370, 26, 20);
waveDirection = true;
gameOver = false;
sound.stop();
sound.loop();
panelDimension = SI.getFrameDimensions();
bottomRow = getBottomRow();
newWave();
timer.start();
runningTimer=true;
}
public SIpanel getPanel() {
return this.panel;
}
public void pause(boolean paused) {
if (paused) timer.stop();
else timer.start();
}
}
I believe that collision detection may be the reason for lagging and you should simply investigate it by trying to increase and decrease count of enemies or missiles drastically to see if that makes a difference.
Consider garbage collector your enemy. In your checkCollision method you are instantiating two (very simple) objects. It may not seem like a lot, but consider that your might be creating them for each collision check, and that at 60fps it adds up until it may reach critical mass when GC says "stop the world" and you see noticeable lag.
If that is the case, possible solution to that would be to not instantiate any objects in a method called so frequently. You may create Rectangle2D once, and then update its position, instead of creating a new one each time, so you will avoid unnecessary memory allocation.

Change the color of a JPanel with a Mouse-Click

How to change the color of a JPanel with a mouse click event?
public class Board extends JPanel{
public Board() {
setLayout(new GridLayout(8, 8));
setBackground(Color.white);
setPreferredSize(new Dimension(700, 700));
JPanel[][] squares = new JPanel[8][8];
for(int i = 0; i < squares.length; i++) {
for(int j = 0; j < squares[i].length; j++) {
squares[i][j] = new JPanel();
add(squares[i][j]);
squares[i][j].addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent click) {
}
});
if(click.getsource() == squares[i][j]) {
squares[i][j].setBackground(Color.blue);
}
if((i+j)%2 == 0)
squares[i][j].setBackground(Color.white);
else
squares[i][j].setBackground(Color.black);
}
}
}
}
You should move the if statement inside the mouseClicked method, something like this:
final int iCopy = i;
final int jCopy = j;
#Override
public void mouseClicked(MouseEvent click) {
if ((iCopy+jCopy)%2==0) {
squares[iCopy][jCopy].setBackground(Color.white);
} else {
squares[iCopy][jCopy].setBackground(Color.black);
}
}
Furthermore I would suggest always use {} in if statements. Otherwise your code could suffer from unexpected errors, since:
if (true)
a += 1;
b += 2;
is the same as
if (true) {
a += 1;
}
b += 2;
which is definitely not what you expected!

getGraphics() prevents my game from starting [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm learning about double buffering and the book I got from my teacher tells me to write what I have written. But when java tries to get the graphics object from the image it crashes.
frame = Image
engine = Graphics
Error
Exception in thread "main" java.lang.NullPointerException
at Engine.<init>(Engine.java:30)
at Game.<init>(Game.java:35)
at Game.main(Game.java:22)
Game.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
import java.util.Timer;
public class Game implements ActionListener {
private static Game hosmos2;
private JFrame frmMain;
private AntiCheat holyanticheat;
private Dimension screen;
private Engine holyengine;
private int sx, sy;
private Timer timCheat;
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
hosmos2 = new Game();
}
private Game() throws FileNotFoundException, InterruptedException {
frmMain = new JFrame("Hosmos 2");
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMain.setSize(1366, 768);
screen = Toolkit.getDefaultToolkit().getScreenSize();
sx = (int) ((screen.getWidth() - frmMain.getWidth()) / 2);
sy = (int) ((screen.getHeight() - frmMain.getHeight()) / 2);
frmMain.setLocation(sx, sy);
holyanticheat = new AntiCheat();
holyengine = new Engine();
timCheat = new Timer();
frmMain.setVisible(true);
timCheat.schedule(holyanticheat, 500);
Thread.sleep(1000);
timCheat.cancel();
}
public void actionPerformed(ActionEvent e) {
}
}
Engine.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
public class Engine extends JPanel {
private boolean countdown, quality;
private Font text, text2;
private Graphics engine;
private Image frame;
private ImageIcon background, button1, button21, button22, button3, button4, button51, button52, header;
private int weedbackground, fps, fps2;
public Rectangle box1, box2, box3, box4, box5;
public static void main(String[] args) {
}
public Engine() {
this.setBackground(Color.black);
frame = createImage(getSize().width, getSize().height);
text = new Font("Microsoft Sans Serif", Font.BOLD, 24);
text2 = new Font("Microsoft Sans Serif", Font.BOLD, 8);
engine = frame.getGraphics(); // Error
background = new ImageIcon("textures/background.png");
//background = background.GetThumbnailImage(source.ClientSize.Width, source.ClientSize.Height, null, IntPtr.Zero);
button1 = new ImageIcon("textures/button 1.png");
button21 = new ImageIcon("textures/button 2-1.png");
button22 = new ImageIcon("textures/button 2-2.png");
button3 = new ImageIcon("textures/button 3.png");
button4 = new ImageIcon("textures/button 4.png");
button51 = new ImageIcon("textures/button 5-1.png");
button52 = new ImageIcon("textures/button 5-2.png");
header = new ImageIcon("textures/header.png");
box1 = new Rectangle(20, 20, 87, 37);
box2 = new Rectangle(20, 60, 96, 37);
box3 = new Rectangle(20, 103, 182, 43);
box4 = new Rectangle(20, 146, 83, 43);
box5 = new Rectangle(20, 189, 206, 43);
}
public Rectangle GetBox1() {
return box1;
}
public Rectangle GetBox2() {
return box2;
}
public Rectangle GetBox3() {
return box3;
}
public Rectangle GetBox4() {
return box4;
}
public Rectangle GetBox5() {
return box5;
}
public void FPS()
{
fps2 = fps;
fps = 0;
}
public void Quality(boolean quality2)
{
quality = quality2;
}
public void Render(boolean music, boolean effect, int time, int spawned, int points, int cracktime, int crackend, int shieldtime, int shieldend, int weedtime, int weedend, ImageIcon malcolm, int malcolmX, int malcolmY, int item, ImageIcon crack, int crackX, int crackY, ImageIcon nuke, int nukeX, int nukeY, ImageIcon shield, int shieldX, int shieldY, ImageIcon skull, int skullX, int skullY, ImageIcon trollface, int trollfaceX, int trollfaceY, ImageIcon weed, int weedX, int weedY, LinkedList<Hosmin> hosmins) {
engine = frame.getGraphics();
super.paintComponent(engine);
if (effect == false) {
if (quality == false) {
background.paintIcon(this, engine, 0, 0);
}
else {
this.setBackground(Color.black);
}
}
else {
if (weedbackground == 1) {
this.setBackground(Color.green);
weedbackground++;
}
else if (weedbackground == 2) {
this.setBackground(Color.yellow);
weedbackground++;
}
else if (weedbackground == 3) {
this.setBackground(Color.red);
weedbackground = 1;
}
}
header.paintIcon(this, engine, 547, 10);
button1.paintIcon(this, engine, 20, 20);
if (music == false) {
button21.paintIcon(this, engine, 20, 60);
}
else {
button22.paintIcon(this, engine, 20, 60);
}
button3.paintIcon(this, engine, 20, 103);
button4.paintIcon(this, engine, 20, 146);
if (quality == false) {
button51.paintIcon(this, engine, 20, 189);
}
else {
button52.paintIcon(this, engine, 20, 189);
}
engine.setFont(text2);
engine.setColor(Color.green);
engine.drawString("FPS: " + fps2, 1293, 9);
engine.setFont(text);
engine.setColor(Color.red);
engine.drawString("Time: " + time, 1178, 22);
engine.drawString("Hosmins: " + spawned, 1124, 59);
engine.drawString("Points: " + points, 1160, 96);
engine.setFont(text2);
engine.setColor(Color.green);
engine.drawString("Developer: HolyDuFF", 1229, 708);
malcolm.paintIcon(this, engine, malcolmX, malcolmY);
if (countdown == true) {
if (crackend - cracktime == 0) {
countdown = false;
}
else if (cracktime >= 0) {
engine.setFont(text);
engine.setColor(Color.red);
crackend = crackend - cracktime;
if (crackend != 10) {
engine.drawString("" + crackend, malcolmX + 17, malcolmY - 40);
}
else {
engine.drawString("" + crackend, malcolmX + 7, malcolmY - 40);
}
}
else if (shieldtime >= 0) {
engine.setFont(text);
engine.setColor(Color.red);
shieldend = shieldend - shieldtime;
if (shieldend != 10) {
engine.drawString("" + shieldend, malcolmX + 17, malcolmY - 40);
}
else {
engine.drawString("" + shieldend, malcolmX + 7, malcolmY - 40);
}
}
else if (weedtime >= 0) {
engine.setFont(text);
engine.setColor(Color.blue);
weedend = weedend - weedtime;
if (weedend != 10) {
engine.drawString("" + weedend, malcolmX + 17, malcolmY - 40);
}
else {
engine.drawString("" + weedend, malcolmX + 7, malcolmY - 40);
}
}
}
for (int i = 0; i < hosmins.size(); i++) {
Hosmin temp = hosmins.get(i);
temp.Draw().paintIcon(this, engine, temp.GetX(), temp.GetY());
}
if (item == 1) {
crack.paintIcon(this, engine, crackX, crackY);
}
else if (item == 2) {
nuke.paintIcon(this, engine, nukeX, nukeY);
}
else if (item == 3) {
shield.paintIcon(this, engine, shieldX, shieldY);
}
else if (item == 4) {
skull.paintIcon(this, engine, skullX, skullY);
}
else if (item == 5) {
trollface.paintIcon(this, engine, trollfaceX, trollfaceY);
}
else if (item == 6) {
weed.paintIcon(this, engine, weedX, weedY);
}
engine.dispose();
repaint();
fps++;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(frame, 0, 0, this);
}
public void SetBackground(int background2) {
weedbackground = background2;
}
public void SetCountdown(boolean countdown2) {
countdown = countdown2;
}
public void SetBox2(int mode) {
if (mode == 1) {
box2.width = 96;
box2.height = 37;
}
else {
box2.width = 76;
box2.height = 43;
}
}
public void SetBox5(int mode) {
if (mode == 1) {
box5.width = 206;
}
else {
box5.width = 213;
}
}
}
You're calling getGraphics() on a null Image variable. If you look at the API for Component's createImage() you'll see why this is so:
returns an off-screen drawable image, which can be used for double buffering. The return value may be null if the component is not displayable. This will always happen if GraphicsEnvironment.isHeadless() returns true.
Engine is not displayed yet in its constructor. The GUI must be rendered first by calling pack() or setVisible(true) on the top level window before this JPanel will be displayed.

Categories