I am trying to get the code below to display the coordinates in info_panel but it is not working. How would I get the coordinates from the mouseListener from SimpleFrameViewWidget to be displayed in the info_panel? I am using setText right now... Thanks!
public static void main(String[] args) throws IOException {
Frame f = A7Helper.readFromURL("http://www.cs.unc.edu/~kmp/kmp.jpg");
f.setTitle("");
SimpleFrameViewWidget simple_widget = new SimpleFrameViewWidget(f);
JFrame main_frame = new JFrame();
main_frame.setTitle("Assignment 7 Pixel Inspector");
main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel top_panel = new JPanel();
top_panel.setLayout(new BorderLayout());
top_panel.add(simple_widget, BorderLayout.CENTER);
main_frame.setContentPane(top_panel);
JPanel info_panel = new JPanel();
info_panel.setLayout(new BorderLayout());
top_panel.add(info_panel, BorderLayout.SOUTH);
JLabel x_label = new JLabel("");
x_label.setHorizontalAlignment(SwingConstants.CENTER);
x_label.addMouseListener(simple_widget);
x_label.setText(simple_widget.getStringInfo());
info_panel.add(x_label);
main_frame.setContentPane(top_panel);
main_frame.pack();
main_frame.setVisible(true);
}
This is the code that has the mouseListener and mouseClick. Thanks in advance!
public class SimpleFrameViewWidget extends JPanel implements MouseListener {
private FrameView frame_view;
private String stringInfo;
public SimpleFrameViewWidget(Frame f) {
setLayout(new BorderLayout());
frame_view = new FrameView(f);
frame_view.addMouseListener(this);
add(frame_view, BorderLayout.CENTER);
JLabel title_label = new JLabel(f.getTitle());
add(title_label, BorderLayout.SOUTH);
}
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
stringInfo = "X: " + x + "Y: " + y;
}
public String getStringInfo(){
return stringInfo;
}
You Could...
Register another MouseListener to SimpleFrameViewWidget that simply feed the results directly to info_panel or have info_panel do it all for you....
Related
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
}
}
}
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);
}
}
}
I'm trying to create a hangman game and so far it's coming along GREAT, but the layout design just doesn't seem to fall into place! The alphabet is supposed to end up in a FlowLayout order on top of the Hangman picture with the buttons "Restart", "Help" "Add New Word" and "Exit" at the bottom! What am I doing wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Hangman extends JFrame
{
int i = 0;
static JPanel panel;
static JPanel panel2;
static JPanel panel3;
public Hangman()
{
JButton[] buttons = new JButton[26];
panel = new JPanel(new FlowLayout());
panel2 = new JPanel();
panel3 = new JPanel();
JButton btnRestart = new JButton("Restart");
btnRestart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
JButton btnNewWord = new JButton("Add New Word");
btnNewWord.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie)
{
System.out.println("Error Thrown" + ie.getMessage());
}
}
});
JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String message = "The word to guess is represented by a row "
+ "of dashes, giving the number of letters and category of "
+ "the word. \nIf the guessing player suggests a letter "
+ "which occurs in the word, the other player writes it "
+ "in all its correct positions. \nIf the suggested "
+ "letter does not occur in the word, the other player "
+ "draws one element of the hangman diagram as a tally mark."
+ "\n"
+ "\nThe game is over when:"
+ "\nThe guessing player completes the word, or guesses "
+ "the whole word correctly"
+ "\nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ImageIcon icon = new ImageIcon("D:\\Varsity College\\Prog212Assign1_10-013803\\images\\Hangman1.jpg");
JLabel label = new JLabel();
label.setIcon(icon);
String b[]= {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
panel.add(buttons[i]);
}
panel2.add(label);
panel3.add(btnRestart);
panel3.add(btnNewWord);
panel3.add(btnHelp);
panel3.add(btnExit);
}
public static void main(String[] args)
{
Hangman frame = new Hangman();
frame.add(panel, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel3, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
Here are a few suggestions:
Use a GridLayout for the top panel; in this case, zero means the number of rows is determined by the specified number of columns and the total number of components in the layout:
JPanel north = new JPanel(new GridLayout(0, 9));
Here's an outline of how you can make your center panel have a reasonable initial size; note how you can draw relative to the current size:
JPanel center = new JPanel() {
private static final int N = 256;
private static final String S = "Todo...";
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int dx = (getWidth() - g.getFontMetrics().stringWidth(S)) / 2;
int dy = getHeight() / 2;
g.drawString(S, dx, dy);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(N, N);
}
};
You can construct your button names like this:
for (int i = 0; i < 26; i++) {
String letter = String.valueOf((char) (i + 'A'));
buttons[i] = new JButton(letter);
north.add(buttons[i]);
}
Make your panels instance variables and start on the event dispatch thread:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Hangman frame = new Hangman();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(frame.north, BorderLayout.NORTH);
frame.add(frame.center, BorderLayout.CENTER);
frame.add(frame.south, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
This problem is pretty well documented if you do some research - it seems all the panels (besides the CENTER one) aren't recalculated when resized. See How do I make this FlowLayout wrap within its JSplitPane? and http://www.velocityreviews.com/forums/t608472-wrap-flowlayout.html
But for a really quick fix, try changing your main method to this... (basically using a BoxLayout as your main container)
public static void main(String[] args)
{
TempProject frame = new TempProject();
Box mainPanel = Box.createVerticalBox();
frame.setContentPane(mainPanel);
mainPanel.add(panel);
mainPanel.add(panel2);
mainPanel.add(panel3);
frame.pack();
frame.setVisible(true);
}
I'm trying to make a bit of code that has a gui that gets the GCD of of 2 numbers. I keep getting an error when I try to compile my code
Error: Could not find or load main class Gooie.Gooie
Java Result: 1\
Can someone tell me what exactly I'm doing wrong?
my code
package Gooie;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gooie {
public static void main(String[] args) {
JFrame frame = new GcdFrame();
frame.setVisible(true);
}
}
class GcdFrame extends JFrame {
public GcdFrame() {
setTitle("Greatest Common Divisor Finder");
centerWindow(this);
setSize(267, 200);
//setResizable(false);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new GcdPanel();
this.add(panel);
}
private void centerWindow(Window w) {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width - w.getWidth()) / 2,
(d.height - w.getHeight()) / 2);
}
}
class GcdPanel extends JPanel implements ActionListener {
private JTextField xTextField, yTextField,
gcdTextField;
private JLabel xLabel, yLabel, gcdLabel;
private JButton calculateButton, exitButton;
public GcdPanel() {
// display panel
JPanel displayPanel = new JPanel();
// displayPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
displayPanel.setLayout(new GridLayout(4, 2));
// payment label
xLabel = new JLabel("X:");
displayPanel.add(xLabel);
// payment text field
xTextField = new JTextField(10);
displayPanel.add(xTextField);
// rate label
yLabel = new JLabel("Y:");
displayPanel.add(yLabel);
// rate text field
yTextField = new JTextField(10);
displayPanel.add(yTextField);
// future value label
gcdLabel = new JLabel("GCD:");
displayPanel.add(gcdLabel);
// future value text field
gcdTextField = new JTextField(10);
gcdTextField.setEditable(false);
gcdTextField.setFocusable(false);
displayPanel.add(gcdTextField);
// button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
// calculate button
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
buttonPanel.add(calculateButton);
// exit button
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
// add panels to main panel
this.setLayout(new BorderLayout());
this.add(displayPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == exitButton)
System.exit(0);
else if (source == calculateButton) {
int x = Integer.parseInt(xTextField.getText());
int y = Integer.parseInt(yTextField.getText());
int gcd = greatestCommonDivisor(x, y);
gcdTextField.getText();
}
}
private int greatestCommonDivisor(int x, int y) {
// TODO Auto-generated method stub
while (x != y) {
if (x > y) {
x = x - y;
} else {
y = y - x;
}
}
return y;
}
}
I ran your program in Eclipse and it seems to run fine....no errors ! Download IDE such as eclipse or anything that you like and try to run the program from there.
http://www.eclipse.org/downloads/
https://netbeans.org/
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();