JCompenents Not Moving With JFrame - java

I am trying to create a game about war. I am starting off with just creating a single window. I am using swing to create windows. However, when the user tries to resize the JFrame, the elements don't move with the frame. I am resizing the buttons that I use, as well as my JPanel. My code can be seen below:
Main.java:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import Numbers.Numbers;
public class Main implements ActionListener {
static JFrame frame;
static JPanel titlePane;
static JButton playButton;
static JButton explanationButton;
static JPanel explanationPane;
static JButton nextButton;
static JLabel explanationLabel;
static JButton backButton;
static int frameSize = 500;
public Main(boolean run) {
if (run) {
frame = new JFrame("War");
titlePane = new JPanel(null);
playButton = new JButton("PLAY");
explanationButton = new JButton("HOW TO PLAY");
explanationPane = new JPanel(null);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
titlePane.setSize(frameSize, frameSize);
titlePane.add(playButton);
playButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
playButton.setBackground(Color.GRAY);
playButton.setForeground(Color.WHITE);
playButton.setVisible(true);
explanationButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/(25/11)), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
explanationButton.setBackground(Color.GRAY);
explanationButton.setForeground(Color.WHITE);
explanationButton.setVisible(true);
explanationPane.setSize(frameSize, frameSize);
explanationPane.add(nextButton);
nextButton.setBounds(225, 50, 50, 15);
nextButton.setBackground(Color.GRAY);
nextButton.setForeground(Color.WHITE);
nextButton.setVisible(true);
backButton.setBounds(225, 450, 50, 15);
backButton.setBackground(Color.GRAY);
backButton.setForeground(Color.WHITE);
backButton.setVisible(true);
frame.setSize(frameSize, frameSize);
frame.add(titlePane);
frame.add(explanationPane);
titlePane.setVisible(false);
explanationPane.setVisible(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public void switchPane(String pane) {
switch (pane) {
case "title":
titlePane.setVisible(true);
explanationPane.setVisible(false);
break;
case "explanation":
titlePane.setVisible(false);
explanationPane.setVisible(true);
break;
}
}
#Override
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
Main war = new Main(true);
war.switchPane("title");
while (true) {
if (frame.getX() != frameSize) {
frameSize = frame.getX();
}
else if (frame.getY() != frameSize) {
frameSize = frame.getY();
}
frame.setSize(frameSize, frameSize);
titlePane.setSize(frameSize, frameSize);
explanationPane.setSize(frameSize, frameSize);
playButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
explanationButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/(25/11)), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
}
}
}
Numbers.java:
package Numbers;
public class Numbers {
public static int doubleToInt(double toConvert) {
int toReturn = (int) toConvert;
return toReturn;
}
}
Any help would be appreciated! :)
Please note I am not close to finishing so please ignore the empty method.

Related

JButton size & location

Hello fellow programmers! I'm starting to learn java, and as a project, i put in my mind to make a visual calculator. My problem is that i can't set an exact location or size for my button, and i would like some help please!
import javax.swing.*;
import java.awt.*;
public class Calculator{
public static void main(String[] args) {
//Frame & sizes
JFrame f = new JFrame("Calculator");
f.setSize(400, 500);
f.setLocation(300,200);
//Text area
final JTextArea textArea = new JTextArea(10, 40);
f.getContentPane().add(BorderLayout.NORTH, textArea);
//Buttons
final JButton button1 = new JButton("1");
button1.setBounds(160, 100, 410, 100);
}
}
There is a lot of additional set-up you need to do, for a tutorial please refer to this article. They do a great job walking you through the steps, I simply pasted the final solution if you want to try it out on your end. To replicate simply create a new Java class called JavaCalculator and run the main method, hopefully this helps!
JavaCalculator:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
public class JavaCalculator implements ActionListener{
JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new JavaCalculator();
}
});
}
public JavaCalculator()
{
guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Simple Calculator");
guiFrame.setSize(300,300);
guiFrame.setLocationRelativeTo(null);
numberCalc = new JTextField();
numberCalc.setHorizontalAlignment(JTextField.RIGHT);
numberCalc.setEditable(false);
guiFrame.add(numberCalc, BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4,4));
guiFrame.add(buttonPanel, BorderLayout.CENTER);
for (int i=0;i<10;i++)
{
addNumberButton(buttonPanel, String.valueOf(i));
}
addActionButton(buttonPanel, 1, "+");
addActionButton(buttonPanel, 2, "-");
addActionButton(buttonPanel, 3, "*");
addActionButton(buttonPanel, 4, "/");
addActionButton(buttonPanel, 5, "^2");
JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (!numberCalc.getText().isEmpty())
{
int number = Integer.parseInt(numberCalc.getText());
if (calcOperation == 1)
{
int calculate = currentCalc + number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 2)
{
int calculate = currentCalc - number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 3)
{
int calculate = currentCalc * number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 4)
{
int calculate = currentCalc / number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 5)
{
int calculate = currentCalc * currentCalc;
numberCalc.setText(Integer.toString(calculate));
}
}
}
});
buttonPanel.add(equalsButton);
guiFrame.setVisible(true);
}
private void addNumberButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
but.addActionListener(this);
parent.add(but);
}
private void addActionButton(Container parent, int action, String text)
{
JButton but = new JButton(text);
but.setActionCommand(text);
OperatorAction addAction = new OperatorAction(1);
but.addActionListener(addAction);
parent.add(but);
}
public void actionPerformed(ActionEvent event)
{
String action = event.getActionCommand();
numberCalc.setText(action);
}
private class OperatorAction implements ActionListener
{
private int operator;
public OperatorAction(int operation)
{
operator = operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
}
}

JComboBox return index value

I have been trying to write a game recently, and I've been coding the GUI. Since I'm a new programmer, and want to keep it simple, I want to use only a resolution selector (fullscreen maybe later). I have the CB, I have an action listener to return the value, and a button to substitute the new resolution measurements. However, every time I run the code, I try to change the resolution and nothing happens.
Anyone have any ideas?
And also, I was wondering how to make it so that there is a stock resolution on first run, but it then saves your selected resolution.
Thank you!
Jack
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Scanner;
public class GUI_Test{
private JPanel window;
private JPanel settings;
private JFrame main;
private JFrame optionsScreen;
private JLabel headerLabel;
private JLabel optionsLabel;
private JLabel resolution;
private JComboBox resolutonOption;
String[] resolutionOptions = new String[] {
"640x480", "1024x768", "1366x768", "1600x900", "1920x1080"
};
int tempResX, tempResY, res;
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int resX = gd.getDisplayMode().getWidth();
int resY = gd.getDisplayMode().getHeight();
public GUI_Test(){
prepareGUI();
}
public static void main(String[] args) {
GUI_Test GUI = new GUI_Test();
GUI.showGUIDemo();
}
private void showGUIDemo() {
JButton exit = new JButton("EXIT");
JButton options = new JButton("OPTIONS");
JButton back = new JButton("BACK");
JButton apply = new JButton("APPLY");
JComboBox <String> resolutionOption = new JComboBox<>(resolutionOptions);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsScreen.setVisible(true);
settings.setVisible(true);
window.setVisible(false);
main.setVisible(false);
}
});
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsScreen.setVisible(false);
settings.setVisible(false);
window.setVisible(true);
main.setVisible(true);
}
});
resolutionOption.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
res = resolutionOption.getSelectedIndex();
switch (res) {
case 0:
tempResX = 640;
tempResY = 480;
break;
case 1:
tempResX = 1024;
tempResY = 768;
break;
case 2:
tempResX = 1366;
tempResY = 768;
break;
case 3:
tempResX = 1600;
tempResY = 900;
break;
case 4:
tempResX = 1920;
tempResY = 1080;
break;
}
}
});
apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resX = tempResX;
resY = tempResY;
}
});
window.add(exit);
window.add(options);
settings.add(back);
settings.add(resolutionOption);
settings.add(apply);
main.setVisible(true);
}
private void prepareGUI() {
main = new JFrame("Basic GUI");
main.setSize(resX, resY);
main.setLayout(new GridLayout(3,1));
main.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
optionsScreen = new JFrame("Options");
optionsScreen.setSize(resX, resY);
optionsScreen.setLayout(new GridLayout(4,1));
optionsScreen.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("AGame", JLabel.CENTER);
headerLabel.setSize(100, 50);
optionsLabel = new JLabel("Settings", JLabel.CENTER);
optionsLabel.setSize(100, 50);
resolution = new JLabel("Resolution", JLabel.CENTER);
window = new JPanel();
window.setLayout(new FlowLayout());
settings = new JPanel();
settings.setLayout(new FlowLayout());
main.add(headerLabel);
main.add(window);
main.setVisible(true);
optionsScreen.add(optionsLabel);
optionsScreen.add(settings);
optionsScreen.add(resolution);
optionsScreen.setVisible(false);
settings.setVisible(false);
}
}
you should call setSize() after you change the resolution .and then call setVisible(true) for main frame. if you want to hide optionscreen window call setVisible(false) or dispose() method.
apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resX = tempResX;
resY = tempResY;
main.setSize(resX, resY);// apply resolution
main.setVisible(true);
//optionsScreen.setVisible(false); // hide optionscreen frame
}
});

BufferedImage not displaying in gui

I've read read and read some more only to lead to more confusion. Here's my problem: I have three classes following the model view controller design. I am having trouble loading the image from the model and displaying onto the view. I have read to use icon, copy from bufferedimage to bufferedimage, display it on a jpanel but none have worked. heres the basic outline:
Model:
import java.awt.Graphics;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.image.BufferedImage;
class Testee{
final public String desktopImage = "TestPicture.jpg";
private String imageURI;
private static BufferedImage bImage;
private Graphics graphics;
private int xLocation, yLocation;
public Testee(){
}
public void setImageURI(String uri){
imageURI = uri;
}
public Graphics getImageGraphics(){
return graphics;
}
public BufferedImage getImage(){
return bImage;
}
public void setImageBuffer(String imageName){
try{
bImage = ImageIO.read(new File(imageName));
graphics = bImage.createGraphics();
}
catch(Exception ex){}
}
public void clearImage(){
bImage = null;
graphics = null;
}
public void setSelectedLocation(int x, int y){
xLocation = x;
yLocation = y;
}
public int getSelectedX(){
return xLocation;
}
public int getSelectedY(){
return yLocation;
}
public int getPixelCount(BufferedImage image){
if(image != null){
int pixelCount = image.getWidth() * image.getHeight();
return pixelCount;
}
else
return 0;
}
public int getSelectedPixel(BufferedImage image, int x, int y){
if(image != null){
int pixelNumber;
int IMAGEWIDTH = image.getWidth();
//if(y <= 1){
//needs work
//}
pixelNumber = (IMAGEWIDTH * (y - 1)) + x;
return pixelNumber;
}
else{
return 0;
}
}
public int getPixelLocation(BufferedImage image, int x, int y){
if(image != null){
return image.getRGB(x, y);
}
else{
return 0;
}
}
public int getPixelRGB(int pixel){
int rgb = pixel;
return rgb;
}
public int getPixelAlpha(int pixel){
int alpha = (pixel >> 24) & 0xff;
return alpha;
}
public int getPixelRed(int pixel){
int red = (pixel >> 16) & 0xff;
return red;
}
public int getPixelGreen(int pixel){
int green = (pixel >> 8) & 0xff;
return green;
}
public int getPixelBlue(int pixel){
int blue = (pixel) & 0xff;
return blue;
}
void blankSlate(){
clearImage();
graphics = null;
}
}
View:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
class Testing{
private Testee testee;
private JFrame mainFrame;
private JPanel mainPane;
private Thread canvasThread;
private JPanel picturePane;
private JPanel canvas;
private JPanel imageControlPane;
private JPanel imageButtonHolder;
private JButton uploadButton;
private JButton clearButton;
private JPanel infoPane;
private JPanel pixelCountPane;
private JPanel pixelLocationPane;
private JPanel pixelSelectedPane;
private JPanel pixelRGBPane;
private JPanel pixelAlphaPane;
private JPanel pixelRedPane;
private JPanel pixelGreenPane;
private JPanel pixelBluePane;
private JPanel pixelColorPane;
final private JLabel pixelCountLabel = new JLabel("# of pixels");
private JTextField pixelCountText;
final private JLabel pixelSelectedLabel = new JLabel("pixel selected");
private JTextField pixelSelectedText;
final private JLabel pixelLocationLabel = new JLabel("pixel location");
private JTextField pixelLocationText;
final private JLabel pixelRGBLabel = new JLabel("pixel RGB");
private JTextField pixelRGBText;
final private JLabel pixelAlphaLabel = new JLabel("Alpha");
private JTextField pixelAlphaText;
final private JLabel pixelRedLabel = new JLabel("Red");
private JTextField pixelRedText;
final private JLabel pixelGreenLabel = new JLabel("Green");
private JTextField pixelGreenText;
final private JLabel pixelBlueLabel = new JLabel("Blue");
private JTextField pixelBlueText;
public Testing(Testee model){
testee = model;
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run(){
setupGUI();
}
});
} catch (InterruptedException | InvocationTargetException ex) {
System.exit(1);
}
}
private void setupGUI(){
System.out.println("Created GUI on EDT? "
+ SwingUtilities.isEventDispatchThread());
mainFrame = new JFrame();
mainPane = new JPanel(new BorderLayout());
mainFrame.setTitle(this.getClass().getSimpleName());
mainFrame.setSize(500,500);
mainFrame.setResizable(false);
mainFrame.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
picturePane = new JPanel(new FlowLayout());
canvas = new DrawBoard();
generateCanvas();
picturePane.add(canvas);
mainPane.add(picturePane,BorderLayout.CENTER);
imageControlPane = new JPanel(new BorderLayout());
imageButtonHolder = new JPanel(new GridLayout(1,2,10,5));
uploadButton = new JButton("UPLOAD");
clearButton = new JButton("CLEAR");
imageButtonHolder.add(uploadButton);
imageButtonHolder.add(clearButton);
imageControlPane.add(imageButtonHolder, BorderLayout.WEST);
mainPane.add(imageControlPane, BorderLayout.SOUTH);
infoPane = new JPanel();
BoxLayout boxLayout = new BoxLayout(infoPane, BoxLayout.Y_AXIS);
infoPane.setLayout(boxLayout);
pixelCountPane = new JPanel(new BorderLayout(5,5));
pixelCountText = new JTextField(8);
pixelCountText.setEditable(false);
pixelCountPane.add(pixelCountLabel, BorderLayout.WEST);
pixelCountPane.add(pixelCountText, BorderLayout.EAST);
infoPane.add(pixelCountPane);
pixelSelectedPane = new JPanel(new BorderLayout(5,5));
pixelSelectedText = new JTextField(8);
pixelSelectedText.setEditable(false);
pixelSelectedPane.add(pixelSelectedLabel, BorderLayout.WEST);
pixelSelectedPane.add(pixelSelectedText, BorderLayout.EAST);
infoPane.add(pixelSelectedPane);
pixelLocationPane = new JPanel(new BorderLayout(5,5));
pixelLocationText = new JTextField(8);
pixelLocationText.setEditable(false);
pixelLocationPane.add(pixelLocationLabel, BorderLayout.WEST);
pixelLocationPane.add(pixelLocationText, BorderLayout.EAST);
infoPane.add(pixelLocationPane);
pixelRGBPane = new JPanel(new BorderLayout(5,5));
pixelRGBText = new JTextField(8);
pixelRGBText.setEditable(false);
pixelRGBPane.add(pixelRGBLabel, BorderLayout.WEST);
pixelRGBPane.add(pixelRGBText, BorderLayout.EAST);
infoPane.add(pixelRGBPane);
pixelAlphaText = new JTextField(8);
pixelAlphaText.setEditable(false);
pixelRedText = new JTextField(8);
pixelRedText.setEditable(false);
pixelGreenText = new JTextField(8);
pixelGreenText.setEditable(false);
pixelBlueText = new JTextField(8);
pixelBlueText.setEditable(false);
//pixelColorPane = new JPanel(new GridLayout(4,1));
pixelAlphaPane = new JPanel(new BorderLayout(5,5));
pixelAlphaPane.add(pixelAlphaLabel, BorderLayout.WEST);
pixelAlphaPane.add(pixelAlphaText, BorderLayout.EAST);
infoPane.add(pixelAlphaPane);
pixelRedPane = new JPanel(new BorderLayout(5,5));
pixelRedPane.add(pixelRedLabel, BorderLayout.WEST);
pixelRedPane.add(pixelRedText, BorderLayout.EAST);
infoPane.add(pixelRedPane);
pixelGreenPane = new JPanel(new BorderLayout(5,5));
pixelGreenPane.add(pixelGreenLabel, BorderLayout.WEST);
pixelGreenPane.add(pixelGreenText, BorderLayout.EAST);
infoPane.add(pixelGreenPane);
pixelBluePane = new JPanel(new BorderLayout(5,5));
pixelBluePane.add(pixelBlueLabel, BorderLayout.WEST);
pixelBluePane.add(pixelBlueText, BorderLayout.EAST);
infoPane.add(pixelBluePane);
//infoPane.add(pixelColorPane);
mainPane.add(infoPane,BorderLayout.EAST);
mainFrame.getContentPane().add(mainPane);
mainFrame.setVisible(true);
}
public class DrawBoard extends JPanel{
BufferedImage image;
public DrawBoard(){
image = testee.getImage();
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
private void generateCanvas(){
canvasReset();
canvasThread = new Thread(new Runnable(){
#Override
public void run() {
}
});
canvasThread.start();
}
public JPanel getCanvas(){
return canvas;
}
public void canvasReset(){
canvas.setPreferredSize(new Dimension(300,300));
canvas.setBackground(Color.white);
canvas.repaint();
}
void setPixelCount(String text){
pixelCountText.setText(text);
}
void setPixelSelected(String text){
pixelSelectedText.setText(text);
}
void setPixelLocation(int x, int y){
pixelLocationText.setText(x + ", " + y);
}
void setPixelRGB(String text){
pixelRGBText.setText(text);
}
void setPixelAlpha(String text){
pixelAlphaText.setText(text);
}
void setPixelRed(String text){
pixelRedText.setText(text);
}
void setPixelGreen(String text){
pixelGreenText.setText(text);
}
void setPixelBlue(String text){
pixelBlueText.setText(text);
}
void canvasAction(MouseListener mla){
canvas.addMouseListener(mla);
}
void uploadAction(ActionListener ual){
uploadButton.addActionListener(ual);
}
void clearAction(ActionListener al){
clearButton.addActionListener(al);
}
void blankGUI(){
canvasReset();
pixelCountText.setText(null);
pixelSelectedText.setText(null);
pixelLocationText.setText(null);
pixelRGBText.setText(null);
pixelAlphaText.setText(null);
pixelRedText.setText(null);
pixelBlueText.setText(null);
pixelGreenText.setText(null);
}
}
Controller:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
class Tester{
public Testing testing;
public Testee testee;
public Tester(Testing gui, Testee model){
testing = gui;
testee = model;
gui.uploadAction(new Upload());
gui.clearAction(new Clear());
gui.canvasAction(new Mouse());
}
public class Upload implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
testee.setImageBuffer(testee.desktopImage);
testing.setPixelCount(Integer.toString(testee.getPixelCount(testee.getImage())));
if(testee.getImage() != null){
}
}
}
public class Clear implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
testing.blankGUI();
testee.blankSlate();
}
}
public class Mouse extends MouseAdapter{
#Override
public void mouseClicked(MouseEvent me){
testee.setSelectedLocation(me.getX(), me.getY());
testing.setPixelLocation(testee.getSelectedX(), testee.getSelectedY());
testing.setPixelSelected(Integer.toString(testee.getSelectedPixel(testee.getImage(), testee.getSelectedX(), testee.getSelectedY())));
try{
int pixelColor = testee.getPixelLocation(testee.getImage(), testee.getSelectedX(), testee.getSelectedY());
testing.setPixelRGB(Integer.toString(testee.getPixelRGB(pixelColor)));
testing.setPixelAlpha(Integer.toString(testee.getPixelAlpha(pixelColor)));
testing.setPixelRed(Integer.toString(testee.getPixelRed(pixelColor)));
testing.setPixelGreen(Integer.toString(testee.getPixelGreen(pixelColor)));
testing.setPixelBlue(Integer.toString(testee.getPixelBlue(pixelColor)));
}
catch(NullPointerException ex){
}
}
}
}
I have tried many different solutions but nothing paints the jpanel. also the image is a jpg on my desktop, path is correct, can load the data from the image, just cant make it appear on the gui. Further questions to follow... Thanks
EDIT: Sorry if duplicate, cant seem to find right answer
So, when I finally got all your code put together...I did something like...
Testee t = new Testee();
t.setImageBuffer("path/to/my/image");
new Testing(t);
And it worked just fine...
I don't see any reason for Testee.bImage to be static and in fact, I can see a lot of reasons why it shouldn't be...
You're throwing away the exception that may be raised by ImageIO.read which may actually tell you what's going wrong...
There is no way for Testee to tell interested parties that it's contents has changed, like the graphics have actually been cleared...
Using JFrame#setDefaultCloseOpertation and setting it to EXIT_ON_CLOSE would save you having to use a WindowAdaptor to exit the system, it would also be advisable not to use SwingUtilities.invokeAndWait, but that's just me...
You should consider using pack over setSize, it calculates the window size based on the needs of it's content...
DrawBoard should override the getPreferredSize method and return a more reliable value
In a MVC framework, the controller needs to be passing information between the model and the view, coordinating functionality. For a controller should have no idea of the view logic (what controls exist or what they do), it should only have a contract by which it can communicate states to it and get response back (the same goes for the model)
So, basically, you have three class, some can effecting the other one or two, but nobody knows what's going on...

Nullpointerexception when adding an array of JButtons to a JFrame

I am making a clone of minesweeper with (slightly modified) JButtons. Because there are so many game tiles in minesweeper, I am storing them as an array. When I try and add the buttons to the Frame using a for loop, I get a nullpointerexception on the buttons. The class ButtonObject is extended from the JButton class with just two extra variables and getter/setter methods. What is going wrong?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Minesweeper extends JFrame implements ActionListener{
JLabel starttitle;
ButtonObject[] minefield;
JFrame frame;
Random r = new Random();
int rand;
JPanel startscreen;
JPanel gamescreen;
int gamesize;
JButton ten;
JButton tfive;
JButton fifty;
GridLayout layout;
public Minesweeper()
{
frame = new JFrame("Minesweeper");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);;
startscreen = new JPanel();
startScreen();
}
public void startScreen()
{
ten = new JButton("10 x 10");
tfive = new JButton("25 x 25");
fifty = new JButton("50 x 50");
starttitle = new JLabel("Welcome to minesweeper. Click a game size to begin.");
frame.add(startscreen);
startscreen.add(starttitle);
startscreen.add(ten);
startscreen.add(tfive);
startscreen.add(fifty);
ten.addActionListener(this);
tfive.addActionListener(this);
fifty.addActionListener(this);
}
public void initializeGame()
{
minefield = new ButtonObject[gamesize];
for(int i = 0;i<gamesize;i++)
{
minefield[i]=new ButtonObject();
rand = r.nextInt(5);
if(rand==5)
{
minefield[i].setButtonType(true);//this tile is a mine
}
}
}
public void gameScreen()
{
frame.getContentPane().removeAll();
frame.repaint();
initializeGame();
for(int i = 0;i<minefield.length;i++)
{
gamescreen.add(this.minefield[i]);//EXCEPTION HERE
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ten)
{
gamesize = 99;
gameScreen();
}
else if(e.getSource()==tfive)
{
gamesize = 624;
gameScreen();
}
else if(e.getSource()==fifty)
{
gamesize = 2499;
gameScreen();
}
else
{
System.out.println("Fatal error");
}
}
public static void main(String[] args)
{
new Minesweeper();
}
}
Well, you never initialize your gamescreen variable, so that's totally normal you get a NullPointerException at this line.

bring JInternalFrame to the front

I have a JDesktopPane which contains a number of JInternalFrames. I'd like to be able to bring any JInternalFrame to the front, overlaying any other active frames. I found a number of code samples to do this, but none seem to work - the frame does NOT go on top of other active JInternalFrames. E.g.
public static void moveToFront(final JInternalFrame fr) {
if (fr != null) {
processOnSwingEventThread(new Runnable() {
public void run() {
fr.moveToFront();
fr.setVisible(true);
try {
fr.setSelected(true);
if (fr.isIcon()) {
fr.setIcon(false);
}
fr.setSelected(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
fr.requestFocus();
fr.toFront();
}
});
}
}
According to the API toFront or moveToFront should work (though toFront looks to be the better of the two from my reading of the API). Are these JInternalFrames sitting in a JDesktopPane? According to your post it seems they are. I wonder if the error lies elsewhere.
Consider creating and posting an SSCCE (please click on the link), a small compilable, runnable program that demonstrates your best attempt at solving this. Then we can inspect your code, run it, modify it and best be able to help you fix it.
Here is my example of an SSCCE:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Random;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class InternalFrameToFront extends JPanel {
private static final int FRAME_MAX = 21;
private static final int DT_WIDTH = 700;
private static final int DT_HEIGHT = 500;
private static final Dimension DESKTOP_SIZE = new Dimension(DT_WIDTH, DT_HEIGHT);
private static final int IF_WIDTH = 150;
private static final int IF_HEIGHT = 100;
private static final Dimension INT_FRAME_SIZE = new Dimension(IF_WIDTH, IF_HEIGHT);
private Random random = new Random();
private JInternalFrame[] internalFrames = new JInternalFrame[FRAME_MAX];
public InternalFrameToFront() {
JDesktopPane desktop = new JDesktopPane();
desktop.setPreferredSize(DESKTOP_SIZE);
for (int i = 0; i < internalFrames.length; i++) {
JInternalFrame intFrame = new JInternalFrame("Frame Number " + i);
intFrame.setSize(INT_FRAME_SIZE);
int x = random.nextInt(DT_WIDTH - IF_WIDTH);
int y = random.nextInt(DT_HEIGHT - IF_HEIGHT);
intFrame.setLocation(x, y);
intFrame.setVisible(true);
desktop.add(intFrame);
internalFrames[i] = intFrame;
}
JSlider slider = new JSlider(0, FRAME_MAX - 1, 0);
slider.setMajorTickSpacing(5);
slider.setMinorTickSpacing(1);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
JPanel sliderPanel = new JPanel();
sliderPanel.add(slider);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
JSlider slider = (JSlider) ce.getSource();
if (!slider.getValueIsAdjusting()) {
int value = slider.getValue();
internalFrames[value].toFront();
}
}
});
setLayout(new BorderLayout());
add(desktop, BorderLayout.CENTER);
add(sliderPanel, BorderLayout.SOUTH);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("InternalFrameToFront");
frame.getContentPane().add(new InternalFrameToFront());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories