I have problem with JOptionPane. I have created contructor in which I defined JOptionPane. I need to create object of that class in another class where I created JFrame. The problem is that JOptionPane opens before JFrame does and I want it to be just the opposite.
Every time i create an object of the class with JOptionPane it shows up.
I simply want to JOptionPane show and change "delay" only when I click "play" on my JMenu.
public class Gameplay extends Paint implements KeyListener, ActionListener {
private Timer timer;
private int q = 0;
private int delay;
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay=Integer.parseInt(JOptionPane.showInputDialog("set Speed")), this);
timer.start();
}
public class PlayGame implements IbeVisible {
JFrame f2 = new JFrame("Snake");
Gameplay gameplay = new Gameplay();
public void openGame() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
f2.setSize(900, 700);
f2.setResizable(false);
f2.setLocation(dim.width / 2 - f2.getWidth() / 2, dim.height / 2 - f2.getHeight() / 2);
f2.add(gameplay);
}
public void beVisible() {
f2.setVisible(true);
}
public class Menu {
PlayGame playGame = new PlayGame();
JFrame menu = new JFrame();
void create() throws IOException {
createMenuBar();
menu.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("logo.png")))));
menu.setTitle("Menu");
menu.setVisible(true);
menu.setSize(355, 400);
menu.setResizable(false);
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem play = new JMenuItem("Play");
play.addActionListener((ActionEvent event) -> {
playGame.openGame();
playGame.beVisible();
});
Related
I am building a simple snake game, and I want to change speed (variable "delay") of snake in game menu (JMenuBar) before game starts.
I have a problem with changing this variable. I can't change its value in my Menu, it's always equal to set value (100). I tried many things but none of them works. I'm almost done. Here's my code:
package Snake;
public class Menu {
PlayGame playGame = new PlayGame();
Help help = new Help();
JFrame menu = new JFrame();
void create() throws IOException {
createMenuBar();
menu.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("logo.png")))));
menu.setTitle("Menu");
menu.setVisible(true);
menu.setSize(355, 400);
menu.setResizable(false);
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
ImageIcon iconPlay = new ImageIcon("downmouth.png");
ImageIcon iconHelp = new ImageIcon("help.png");
ImageIcon iconAbout = new ImageIcon("about.png");
ImageIcon iconExit = new ImageIcon("exit.png");
JMenu fileMenu = new JMenu("File");
JMenu settingsMenu = new JMenu("Settings");
JMenu helpMenu = new JMenu("Help");
JMenu speedMenu = new JMenu("Speed");
JMenu boardMenu = new JMenu("Board");
JMenuItem faster = new JMenuItem("Faster");
JMenuItem normal = new JMenuItem("Normal");
JMenuItem slower = new JMenuItem("Slower");
JMenuItem theSlowest = new JMenuItem("The Slowest");
JMenuItem noWall = new JMenuItem("Without the wall");
JMenuItem wall = new JMenuItem("With wall");
JMenuItem play = new JMenuItem("Play", iconPlay);
play.addActionListener((ActionEvent event) -> {
playGame.openGame();
playGame.beVisible();
});
JMenuItem exit = new JMenuItem("Exit", iconExit);
exit.addActionListener((ActionEvent event) -> {
System.exit(0);
});
JMenuItem instructions = new JMenuItem("Instructions", iconHelp);
instructions.addActionListener((ActionEvent event) -> {
help.instructions();
});
JMenuItem about = new JMenuItem("About", iconAbout);
about.addActionListener((ActionEvent event) -> {
help.about();
});
JMenuItem theFastest = new JMenuItem("The Fastest");
theFastest.addActionListener((ActionEvent event) -> {
// ???????
});
// and rest of speed variables...
speedMenu.add(theFastest);
speedMenu.addSeparator();
speedMenu.add(faster);
speedMenu.addSeparator();
speedMenu.add(normal);
speedMenu.addSeparator();
speedMenu.add(slower);
speedMenu.addSeparator();
speedMenu.add(theSlowest);
boardMenu.add(noWall);
boardMenu.addSeparator();
boardMenu.add(wall);
fileMenu.add(play);
fileMenu.addSeparator();
fileMenu.add(exit);
settingsMenu.add(speedMenu);
settingsMenu.addSeparator();
settingsMenu.add(boardMenu);
helpMenu.add(instructions);
helpMenu.addSeparator();
helpMenu.add(about);
menubar.add(fileMenu);
menubar.add(settingsMenu);
menubar.add(helpMenu);
menu.setJMenuBar(menubar);
}}
package Snake;
public class Gameplay extends Paint implements KeyListener, ActionListener {
private Timer timer;
private int q = 0;
private int delay = 100;
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);//????????
timer.start();
}
In this class (Gameplay) there's more code which needs timer.
package Snake;
public class PlayGame extends Gameplay implements IbeVisible {
JFrame f2 = new JFrame("Snake");
Gameplay gameplay = new Gameplay();
public void openGame() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
f2.setSize(900, 700);
f2.setResizable(false);
f2.setLocation(dim.width / 2 - f2.getWidth() / 2, dim.height / 2 - f2.getHeight() / 2);
f2.add(gameplay);
}
#Override
public void beVisible() {
f2.setVisible(true);
}}
I am making a Simon Says style game, there are four colored squares and the computer does a sequence, then you copy that, etc. and am at a point where I want to add some more advanced features. The current feature I am looking at is looking to change the color panels actual colors at the users will and being able to change them individually from one another.
How can I get the 'color panel(s)' to change to a new color via JColorChooser while keeping everything else set up?
At the moment I have it split up into a few different classes and am having issues getting them all to communicate and just work properly.
Main class(Only a snippet):
public class Simonish implements ActionListener, MouseListener {
private ColorPanel colorPanel[] = new ColorPanel[4];
private ScorePanel scorePanel = new ScorePanel();
private Menu menuBar = new Menu();
private JPanel gameBoard = new JPanel();
private Random rand = new Random();
private ArrayList<ColorPanel> compSeq = new ArrayList<ColorPanel>();
private Iterator<ColorPanel> iter;
private JFrame frame = new JFrame();
private boolean playerTurn = false;
private int speed = 500;
public Simonish(Color[] colors){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = (JPanel)frame.getContentPane();
pane.setLayout(new BorderLayout());
gameBoard.setLayout(new GridLayout(2,2));
gameBoard.setPreferredSize(new Dimension(400,400));
for (int i=0;i<colorPanel.length;i++){
colorPanel[i] = new ColorPanel(colors[i]);
colorPanel[i].addMouseListener(this);
gameBoard.add(colorPanel[i]);
}
scorePanel.addStartListener(this);
frame.setJMenuBar(menuBar);
pane.add(scorePanel, BorderLayout.NORTH);
pane.add(gameBoard, BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
My Menu code (builds the menubar and implements the actions):
public class Menu extends JMenuBar {
private JMenuBar menuBar = new JMenuBar();
private JMenu settings = new JMenu("Settings");
private JMenu stats = new JMenu("Stats");
private JMenu help = new JMenu("Help");
private JMenuItem chooseColor = new JMenuItem(new ChooseColorAction("Choose Color"));
private JMenuItem colorMode = new JMenuItem(new ColorModeAction("Color Mode"));
private JMenuItem hScore = new JMenuItem("High Scores");
private JMenuItem history = new JMenuItem("History");
private JMenuItem about = new JMenuItem("About");
private JMenuItem rules = new JMenuItem("Rules");
public Menu(){
this.add(settings);
this.add(stats);
this.add(help);
settings.add(chooseColor);
settings.add(colorMode);
stats.add(hScore);
stats.add(history);
help.add(about);
help.add(rules);
}
}
Action class to house the color changing code:
public class ColorModeAction extends AbstractAction {
public ColorModeAction(String name){
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Color[] colors = {Color.CYAN, Color.BLACK, Color.WHITE, Color.GREEN};
//new Simonish(colors);
//JOptionPane.showMessageDialog(null, "Color Mode");
}
}
Use interfaces to communicate your classes. For example; ColorModeAction needs to change colors so it should take an interface as parameter which able to change colors:
public interface ColorChanger {
public void changeColor(int index, Color newColor);
}
Make Simonish implement that interface:
public class Simonish implements ActionListener, MouseListener, ColorChanger {
public void changeColor(int index, Color new Color) {
//Change the given panel's color
}
}
Pass Simonish as parameter to the menu, and move new ColorModeAction("Color Mode") to the constructor. Then pass ColorChanger to the ColorModeAction as a parameter.
public class Menu extends JMenuBar {
...
private JMenuItem colorMode;
...
public class Menu(ColorChanger colorChanger) {
colorMode = new JMenuItem(new ColorModeAction(colorChanger, "Color Mode"));
}
}
And the new ColorModeAction:
public class ColorModeAction extends AbstractAction {
private ColorChanger colorChanger;
public ColorModeAction(ColorChanger colorChanger, String name) {
super(name);
this.colorChanger = colorChanger;
}
#Override
public void actionPerformed(ActionEvent e) {
Color[] colors = { Color.CYAN, Color.BLACK, Color.WHITE, Color.GREEN };
colorChanger.changeColor(index, Color)
}
}
It is not fully working code but I think you got the idea.
I was just messing around with GUI in Java and created a little game. In it, 105 randomly placed buttons are created and then an instruction screen pops up, telling the user which button to find. I've tried to figure out how to program a "Loading..." JDialog, which will pop up while the buttons are being created in the background. The trouble is, when I run the program the JDialog doesn't load until AFTER all the buttons have been created, which kind of defeats the purpose of the box in the first place. How can I force the "Loading..." box to load BEFORE the buttons begin to be created??? Thanks in advance.
Because I've just been tinkering, my code is not perfect but here it is:
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.ProgressMonitor;
public class ButtonGame {
private static int butNum = 1;
private static JFrame frame;
private static ActionListener notIt;
private static ActionListener it;
private static Random rand = new Random();
private static int butToFind = rand.nextInt(105);
private static JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
//actionlistener for all incorrect buttons (buttons that are "not it")
notIt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame5 = (JFrame) SwingUtilities.getRoot(component);
frame5.dispose();
}
};
//actionlistener for the correct button (the button that's "it")
it = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame youWin = new JFrame("YOU WON!");
//removes all panels to begin game again
JButton again = new JButton("Play again");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
java.awt.Window windows[] = java.awt.Window.getWindows();
for(int i=0;i<windows.length;i++){
if (windows[i] != frame) { windows[i].dispose(); }
butToFind = rand.nextInt(105);
butNum = 1;
youWin.dispose();
}
frame.setVisible(true);
}
});
//quits game
JButton win = new JButton("Quit");
win.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//layout
youWin.setSize(775, 300);
youWin.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Fantastic!");
Font font1 = new Font("Courier", Font.BOLD,120);
label1.setFont(font1);
label1.setHorizontalAlignment(JLabel.CENTER);
JLabel label2 = new JLabel("You beat the game!");
Font font2 = new Font("Courier", Font.BOLD,60);
label2.setFont(font2);
label2.setHorizontalAlignment(JLabel.CENTER);
youWin.add(label1);
youWin.add(label2);
JPanel panel = new JPanel();
youWin.add(panel);
panel.add(again);
panel.add(win);
youWin.setLocation(260, 100);
youWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
youWin.setVisible(true);
java.awt.Window windows[] = java.awt.Window.getWindows();
}
};
//start window
frame = new JFrame("Window");
frame.setLocation(400, 200);
JButton button1 = new JButton("Click to begin");
//button to begin game
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDialog load = new JDialog();
// load.setAlwaysOnTop(true);
// load.setSize(500,500);
// load.setVisible(true);
// load.add(new Label("Loading..."));
// load.pack();
frame.setVisible(false); // "start" window's visibility
// try {
// Thread.sleep(100000);
// } catch (Exception t) {
// }
// creates buttons
for (int i = 0; i < 105; i++) {
JFrame nextFrame = newFrame(butNum);
nextFrame.setVisible(true);
butNum++;
}
//creates instructions and tells user what button to find
JFrame instructions = new JFrame("How to play");
instructions.setSize(300,175);
instructions.setLayout(new GridLayout(4,1));
JPanel instPanel = new JPanel();
//button to remove instruction panel
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
instructions.dispose();
}
});
instPanel.add(ok);
instructions.setLocation(400,200);
//layout of instruction panel
JLabel find = new JLabel("Your goal is to find Button " + butToFind + ".");
find.setHorizontalAlignment(JLabel.CENTER);
JLabel find2 = new JLabel("Click a button to make it disappear.");
find2.setHorizontalAlignment(JLabel.CENTER);
JLabel find3 = new JLabel("Good luck!");
find3.setHorizontalAlignment(JLabel.CENTER);
instructions.add(find);
instructions.add(find2);
instructions.add(find3);
instructions.add(instPanel);
instructions.setVisible(true);
}
});
frame.add(button1);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//creates frame with button in it
public static JFrame newFrame(int num) {
JFrame frame2 = new JFrame();
JButton button = new JButton("Button " + num);
if (num == butToFind) {
button.addActionListener(it);
frameToClose = frame2;
} else {
button.addActionListener(notIt);
}
frame2.add(button);
frame2.setSize(randNum(90,200), randNum(50,100));
frame2.setLocation(rand.nextInt(1200), rand.nextInt(800));
frame2.getContentPane().setBackground(new Color(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
frame2.setVisible(true);
return frame2;
}
//provides random number between high and low
public static int randNum(int low, int high) {
int result = -1;
while (result < low || result > high) {
result = rand.nextInt(high);
}
return result;
}
}
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static? Thanks!
First take a look at The Use of Multiple JFrames, Good/Bad Practice? and understand why I freaked out when I ran your code...
Instead of creating a bunch of frames, why not use something like JButton on another JPanel and add it to the current frame (this would also be a good use for a CardLayout)
JPanel panel = new JPanel(new GridLayout(10, 0));
Random rnd = new Random();
// creates buttons
for (int i = 0; i < 105; i++) {
JButton btn = new JButton(String.valueOf(i));
panel.add(btn);
//JFrame nextFrame = newFrame(butNum);
//nextFrame.setVisible(true);
//butNum++;
}
frame.getContentPane().removeAll();
frame.add(panel);
frame.revalidate();
frame.pack();
Alternatively, if you're really hell bent on using "frames", consider using a JDesktopPane and JInternalFrame instead.
See How to Use Internal Frames for more details
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static?
As much as possible, none. Instead of trying to create the whole thing in the main method, use the classes constructor to initialise the UI and use another method to actually get the game rolling...
public class ButtonGame {
private int butNum = 1;
private JFrame frame;
private ActionListener notIt;
private ActionListener it;
private Random rand = new Random();
private int butToFind = rand.nextInt(105);
private JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
ButtonGame game = new ButtonGame();
game.start();
}
public ButtonGame() {
//... All the code that was once in main...
frame.add(button1);
frame.setSize(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
frame.setVisible(true);
}
Answering to your side questions:
a static method can only accept static global variables
You can put all your code in the constructor and use main to only run the program.
Constructor:
public ButtonGame() {
// All of your code goes here - except the static methods
}
You should also make all other methods non-static.
To run the program:
public static void main(String[] args) {
new ButtonGame();
}
I am trying to make a minesweeper game with GUI and when I am adding a menu where people can change the size of the field and number of mines, I wasn't be able to change JFrame. I want to change the number of buttons and mines if player enters something to the JTextBox and presses the submit button which are on a JDialog. Basically I want to change sizeX, sizeY, mines variables at the MineSweeper class and then refresh the frame with new values.
public class MineSweeper {
private static int sizeX=20;
private static int sizeY=20;
private static int mines=20;
private static JFrame frame;
public static void setX(int x){
sizeX = x;
}
public static void setY(int y){
sizeY = y;
}
public static void setM(int m){
mines = m;
}
public static void refreshFrame(){
frame.validate();
frame.repaint();
}
public static void main(String[] args){
frame = new JFrame("");
frame.setTitle("MineSweeper Game");
frame.setBackground(Color.white);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menu = new JMenuBar();
JMenu options = new JMenu("Options");
JMenuItem gameProperties = new JMenuItem("Game Properties");
menuHandler menuHandling = new menuHandler();
gameProperties.addActionListener(menuHandling);
options.add(gameProperties);
menu.add(options);
frame.setJMenuBar(menu);
frame.setSize(sizeX*sizeY, sizeX*sizeY);
if(gameProperties.isEnabled()) frame.validate();
frame.add(new MineSweeperGUI(sizeX, sizeY, mines));
frame.setVisible(true);
}
}
class menuHandler implements ActionListener{
JDialog dialog;
JButton button;
JPanel panel;
JLabel sizeRow, sizeCols, mineCount;
JTextField sizeX, sizeY, mines;
int x, y, m;
public menuHandler(){
dialog = new JDialog();
dialog.setSize(400,120);
panel = new JPanel(new GridLayout(4, 2));
sizeRow = new JLabel("Row size of the field: ");
sizeCols = new JLabel("Column size of the field: ");
mineCount = new JLabel("Number of mines: ");
sizeX = new JTextField(10);
sizeY = new JTextField(10);
mines = new JTextField(10);
panel.add(sizeRow);
panel.add(sizeX);
panel.add(sizeCols);
panel.add(sizeY);
panel.add(mineCount);
panel.add(mines);
button = new JButton("Submit");
panel.add(button);
dialog.add(panel);
}
public void actionPerformed(ActionEvent e) {
dialog.setVisible(true);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String sizeofRows = sizeX.getText();
String sizeofCols = sizeY.getText();
String countofMines = mines.getText();
MineSweeper.setX(Integer.parseInt(sizeofRows));
MineSweeper.setY(Integer.parseInt(sizeofCols));
MineSweeper.setM(Integer.parseInt(countofMines));
MineSweeper.refreshFrame();
dialog.dispose();
}
});
}
}
You might be able to adopt the approach used in this simple game. It uses a JPanel named buttonPanel that has a GridLayout of JToggleButton instances. When the user changes the size of the game, an ActionListener invokes resetGame(), which does
buttonPanel.validate();
I'm trying to make a JButton on a JDialog, but, the button will cover the entire JDialog, any help on this? This is what it looks like:
This is how I create the JDialog and the JButton:
class MenuStoreHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int) dim.getWidth();
int screenHeight = (int) dim.getHeight();
JDialog g = new JDialog();
g.setTitle("The Store");
g.setSize(200, 200);
g.setLocation(screenWidth / 2 - 150, screenHeight / 2 - 150);
JButton b = new JButton("Buy");
b.addActionListener( new StoreItem1Handler() );
b.setVisible(true);
g.add(b);
g.setVisible(true);
}
}
I'm just going to post my full MrStan.class, here it is:
package Progress;
public class MrStan extends JPanel{
private Timer timer = new Timer();
public static int points;
static File h = new File("text.txt");
public ImageIcon bg = new ImageIcon("D:/MrStan/bg.png");
static JMenuBar menubar;
Formatter x;
JMenu menu;
JMenuItem menuitem;
double version = 0.3;
class todoTask extends TimerTask{
public void run(){
points += 1;
repaint();
}
}
public int getPoints(){
return points;
}
public void setPoints( int points ){
this.points = points;
}
public MrStan(){
setIgnoreRepaint(true);
menubar = new JMenuBar();
menu = new JMenu("Menu");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription("Menu");
menubar.add(menu);
menuitem = new JMenuItem("Store (S)", new ImageIcon("coins.png"));
menuitem.setMnemonic(KeyEvent.VK_S);
menuitem.addActionListener( new MenuStoreHandler() );
menu.add(menuitem);
menuitem = new JMenuItem("Reset Points (R)", new ImageIcon("delete.png"));
menuitem.setMnemonic(KeyEvent.VK_R);
menuitem.addActionListener( new MenuResetPointHandler() );
menu.add(menuitem);
// add a separator
menu.addSeparator();
menuitem = new JMenuItem("Exit (E)", new ImageIcon("cross.png"));
menuitem.setMnemonic(KeyEvent.VK_E);
menuitem.addActionListener( new MenuExitHandler() );
menu.add(menuitem);
timer.schedule(new todoTask(), 0, 2000);
}
class MenuStoreHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int) dim.getWidth();
int screenHeight = (int) dim.getHeight();
JDialog g = new JDialog();
g.setTitle("The Store");
g.setSize(200, 200);
g.setLocation(screenWidth / 2 - 150, screenHeight / 2 - 150);
JButton b = new JButton("Buy");
b.addActionListener( new StoreItem1Handler() );
b.setVisible(true);
g.add(b);
g.setVisible(true);
}
}
class StoreItem1Handler implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("Store-Button 1 pressed.");
}
}
class MenuExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(1);
}
}
class MenuResetPointHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
points = 0;
repaint();
JOptionPane.showMessageDialog(null, "Points have been reset.");
}
}
public void paint(Graphics g){
g.setColor(Color.WHITE);
bg.paintIcon(this,g,0,0);
g.setColor(Color.BLACK);
g.drawString("Points: " + points, 75, 95);
g.drawString("Version: " + version, 2, 10);
}
public static void main(String[] args){
final MrStanCreateFile g = new MrStanCreateFile();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
public void run(){
if(h.exists()){
g.openFile();
g.addRecords();
g.closeFile();
}else{
System.out.println(h.getName() + "does not exist, not saving.");
}
}
}, "Shutdown-thread"));
readIt();
//Create new JFrame
JFrame frame = new JFrame();
frame.setTitle("MrStan");
frame.setSize(200, 200);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setJMenuBar(menubar);
//Set location of JFrame
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int) dim.getWidth();
int screenHeight = (int) dim.getHeight();
frame.setLocation(screenWidth / 2 - 200, screenHeight / 2 - 200);
//Set ContentPane to JPanel
MrStan panel = new MrStan();
frame.setContentPane(panel);
//Make the user not be able to resize
frame.setResizable(false);
//Make the JFrame visible
frame.setVisible(true);
}
public static void readIt(){
MrStanReadFile r = new MrStanReadFile();
r.openFile();
r.readFile();
r.closeFile();
}
}
Why is this covering my ENTIRE JDialog? I'm using the basic Layout Manager, it should just be fine.
Try adding the button to the contentPane first and setting the bounds later.
Container pane = dialog.getContentPane();
pane.setLayout(null);
JButton button = new JButton("Testbutton!");
pane.add(button);
button.setBounds(10,10,40,40);
Seems to work fine for me. Did you do call setLayout(null) for the dialog?
This is what I tried
JDialog dialog = new JDialog();
dialog.setSize(300, 200);
dialog.setLayout(null);
JButton button = new JButton("Testbutton!");
button.setVisible(true);
button.setBounds(10,10,40,40);
dialog.add(button);
//Make dialog visible
dialog.setVisible(true);
And usually it's not a good practice to not use a layout manager. Things can get complicated very quickly. Layout Managers help a lot.
The real problem for you code is that you add the components to the dialog AFTER you set the dialog visible. The second setVisible() does nothing because its already visible.
That is why you should be learning from the examples in the Swing tutorial. The examples show you the proper way to create a simple GUI.