Adding buttons to a JDialog? - java

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.

Related

Java Swing GridLayout Change Grid Sizes

I'm trying to create a program that lists movies in a Netflix style to learn Front-End coding.
How I want it to look in the end:
My guess is that every movie is a button component with an image a name label and a release year label.
I'm struggling to recreate this look. This is how it looks when I try it:
The navigationbar in my image is at the page start of a border layout. Below the navigationbar the movie container is in the center of the border layout.
My idea was creating a GridLayout and then create a button for each movie and adding it to the GridLayout.
You can recreate this with this code:
public class Main {
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel moviePanel = new JPanel();
GridLayout layout = new GridLayout(0, 10);
layout.setHgap(3);
layout.setVgap(3);
moviePanel.setLayout(layout);
moviePanel.setBackground(new Color(32, 32, 32));
ArrayList<String> exampleList = new ArrayList<>();
// Add stuff to the example list
for(int i = 0; i < 120; i++) {
exampleList.add(Integer.toString(i));
}
final File root = new File("");
for(final String movie : exampleList) {
JLabel picLabel = new JLabel();
try {
File imageFile = new File(root.getAbsolutePath() + "\\src\\images\\" + "imageName.jpg"); // Try to find the cover image
if(imageFile.exists()) {
BufferedImage movieCover = ImageIO.read(imageFile);
picLabel = new JLabel(new ImageIcon(movieCover));
} else {
BufferedImage movieCover = ImageIO.read(new File(root.getAbsolutePath() + "\\src\\images\\temp.jpg")); // Get a temp image
picLabel = new JLabel(new ImageIcon(movieCover));
}
} catch (IOException e) {
e.printStackTrace();
}
JLabel movieName = new JLabel("New Movie");
movieName.setForeground(Color.WHITE);;
JButton movieButton = new JButton();
movieButton.setLayout(new GridLayout(0, 1));
//movieButton.setContentAreaFilled(false);
//movieButton.setBorderPainted(false);
//movieButton.setFocusPainted(false);
movieButton.add(picLabel);
movieButton.add(movieName);
moviePanel.add(movieButton);
}
return moviePanel;
}
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
}
I noticed that the GridLayout always tries to fit everything onto the window.
All that's needed is a properly configured JButton in a GridLayout.
E.G.
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 1; ii < 21; ii++) {
JButton picButton = new JButton("Mov " + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
Here is a complete source for the above with a tweak to put the year on a new line. It uses HTML in the JButton to break the button text into two lines.
The input focus is on the first button, whereas the mouse hovers over the '2009' movie:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class MovieGrid {
MovieGrid() {
JFrame f = new JFrame("Movie Grid");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(createMoviePanel());
f.pack();
f.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(
9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 2001; ii < 2021; ii++) {
JButton picButton = new JButton(
"<html>Movie<br>" + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new MovieGrid();
}
};
SwingUtilities.invokeLater(r);
}
}
Same idea's from Andrew Thompson answer but with some minor text alignment changes and hover effect
final class Testing
{
public static void main(String[] args)
{
JFrame frame=new JFrame("NEFLIX");
frame.setContentPane(new GridDisplay());
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final class GridDisplay extends JPanel implements ActionListener
{
private GridDisplay()
{
super(new GridLayout(0,5,20,20));
setBackground(new Color(0,0,0,255));
BufferedImage image=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)image.getGraphics();
g2d.setColor(Color.BLUE);
g2d.fillRect(0,0,image.getWidth(),image.getHeight());
HoverPainter painter=new HoverPainter();
for(int i=0;i<10;i++)
{
TVShowCard card=new TVShowCard(image,"Show "+i,"199"+i);
card.addMouseListener(painter);
add(card);
}
}
//highlight only on hover
private final class HoverPainter extends MouseAdapter
{
#Override
public void mouseExited(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(false);
}
#Override
public void mouseEntered(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(true);
}
}
private final class TVShowCard extends JButton
{
private TVShowCard(BufferedImage preview,String name,String year)
{
super();
setContentAreaFilled(false);
setBackground(new Color(0,0,0,0));
setFocusPainted(false);
setBorderPainted(false);
//I didn't use image icon & text horizontal alignment because the text always horizontally centered aligned but from the expected output it was left so created 2 labels for the job
setLayout(new GridBagLayout());
addIcon(preview);
addLabel(name,year);
addActionListener(GridDisplay.this);
}
private void addIcon(BufferedImage preview)
{
JLabel icon=new JLabel();
icon.setIcon(new ImageIcon(preview));
add(icon,new GridBagConstraints(0,0,1,1,1.0f,0.0f,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0));
}
private void addLabel(String name,String year)
{
JLabel label=new JLabel("<html><body>"+name+"<br>"+year+"</body></html>");
label.setForeground(Color.white);
label.setBackground(new Color(0,0,0,0));
add(label,new GridBagConstraints(0,1,1,1,1.0f,1.0f,GridBagConstraints.SOUTHWEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));
}
}
#Override
public void actionPerformed(ActionEvent e)
{
TVShowCard card=(TVShowCard)e.getSource();
//do stuff with it
}
}
}

GUI is showing up blank. No Errors during compiling

I tried to run my code and it went through without any issues, but the GUI is showing a blank when I run it. This is the main class for my project, I have several other subclasses. I've looked over it several times to figure out what's wrong and I can't seem to. Did I use setVisible incorrectly? The project 3 class should generate a GUI which allows the user to input the type of shape they want, the color of the shape, and the fill type of the shape.
public class Project3 extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel shapeType, fillType, color, Width, Height, xCoordinate, yCoordinate;
JTextField xCoor, yCoor, jWidth, jHeight;
JPanel left, right, down;
String shapetoDraw, shapeColor, filltype;
Rectangular rect;
Oval ov;
Drawing drawing= new Drawing();
Project3(){
setTitle("Geometric Drawing");
setLayout(null);
setSize(600,500);
left = new JPanel(new GridLayout(2,2,10,10));
right = new JPanel(new GridLayout(0, 2));
right.setBorder(BorderFactory.createTitledBorder("Shape Drawing"));
down = new JPanel(new GridLayout(2,2,10,10));
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
shapeType = new JLabel("Shape Type");
fillType = new JLabel("Fill Type");
color = new JLabel("Color");
Width = new JLabel("Width");
Height = new JLabel("Height");
xCoordinate = new JLabel("x coordinate");
yCoordinate = new JLabel("y coordinate");
xCoor = new JTextField(10);
yCoor = new JTextField(10);
jWidth = new JTextField(10);
jHeight = new JTextField(10);
left.add(shapeType);
String[] shape = {"Rectangle","Oval"};
JComboBox<String> shapeCombo = new JComboBox<String>(shape);
left.add(color);
String[] colors = {"Black", "Red", "Orange","Yellow","Green","Blue","Magenta"};
JComboBox<String> colorCombo = new JComboBox<String>(colors);
left.add(fillType);
String[] fill = {"Hollow", "Solid"};
JComboBox<String> filltypeCombo = new JComboBox<String>(fill);
left.add(Width);
left.add(jWidth);
left.add(Height);
left.add(jHeight);
left.add(xCoordinate);
left.add(xCoor);
left.add(yCoordinate);
left.add(yCoor);
JButton drawButton = new JButton("Draw");
drawButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapetoDraw=shapeCombo.getSelectedItem().toString();
shapeColor=colorCombo.getSelectedItem().toString();
filltype=filltypeCombo.getSelectedItem().toString();
drawing.drawShape(shapetoDraw, shapeColor, filltype);
}});
down.add(drawButton);
}
public static void main(String[] args) {
Project3 mainFrame = new Project3();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public void paint(Graphics g) {
super.paintComponents(g);
//g.setFont(new Font("Times", Font.BOLD, 12));
//g.drawString(Integer.toString(Shape.getNoOfShapes()),10, 30);
//rect.draw(g);
}}

Paint a parabola using JTextField values in Java

The program consists of drawing a parabola using the values from the A, B and C jtextfields every time the button is pressed:
It also has to be on two separate classes, the View which displays the menu and the Controller which takes the inputs from the first class and paints the parabola.
My actual code:
public static void main(String[] args) {
JFrame frame = new JFrame("Parabola");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
textA.getText();
textB.getText();
textC.getText();
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
double a=2, b=1, c=0;
public void section (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public void graphic(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
public void paint (Graphics g){
section(g);
graphic(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
I`ve managed to do it in one class without the textfields working and have no idea how to separate the graphic into another class so it can do the operations and send them back to the view class again.
Solved it:
Class View
public class View extends JFrame {
public View() {
JFrame frame = new JFrame("Equation");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Controller.a = Double.parseDouble(textA.getText());
Controller.b = Double.parseDouble(textB.getText());
Controller.c = Double.parseDouble(textC.getText());
repaint();
frame.pack();
frame.setSize(420,490);
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
public void paint(Graphics g){
super.paint(g);
Controller.grid(g);
Controller.Graphic1(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
View frame = new View();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Class Controller
public class Controller {
static double a=2, b=1, c=0;
public static void grid (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public static void Graphic1(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
}

JOptionPane shows up not in the right moment

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();
});

MineSweeper with GUI, How to change the size of the field and then refresh the JFrame?

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();

Categories