Quick question, I have developed 3 A.I's each with a different depth.
Currently to choose what A.I you want to play against you have to go into the java file called Main.java and change it to whichever one you want. The line to change is:
chessGame.setPlayer(Piece.COLOR_BLACK, ai3);//Here A.I is assigned
I want to allow the user to have an option at the start of the game to choose the A.I. I was hoping for some help with the interface, I was thinking something something like a JOptionpane might work.
(I'm just not sure how to do one for the A.I selection)
Current A.I's
ai1
ai2
ai3
package chess;
import chess.ai.SimpleAiPlayerHandler;
import chess.gui.ChessGui;
import chess.logic.ChessGame;
import chess.logic.Piece;
public class Main {
public static void main(String[] args) {
// Creating the Game
ChessGame chessGame = new ChessGame();
// Creating the Human Player
//Human Player is the Object chessGui
ChessGui chessGui = new ChessGui(chessGame);
//Creating the A.I's
SimpleAiPlayerHandler ai1 = new SimpleAiPlayerHandler(chessGame);//Super Dumb
SimpleAiPlayerHandler ai2 = new SimpleAiPlayerHandler(chessGame);//Dumb
SimpleAiPlayerHandler ai3 = new SimpleAiPlayerHandler(chessGame);//Not So Dumb
// Set strength of AI, how far they can see ahead
ai1.maxDepth = 1;
ai1.maxDepth = 2;
ai3.maxDepth = 3;
//Assign the Human to White
chessGame.setPlayer(Piece.COLOR_WHITE, chessGui);
//Assign the not so dumb A.I to black
chessGame.setPlayer(Piece.COLOR_BLACK, ai3);
// in the end we start the game
new Thread(chessGame).start();
}
}
Thanks for any help.
You should probably use a JComboBox to allow the user to select among the 3 options available. If you make a splash JFrame with this JComboBox you can then create your main game frame afterward and pass it the value from the JComboBox.
For example, you could have the JComboBox give options of difficulty setting Easy, Medium, and Hard. Using an action listener on a JButton get the selected value from the JComboBox and convert it to int value appropriate for your minimax algorithm. That is, pass 1 for easy, 2 for medium, and 3 for hard.
Next change your ai class so that maxDepth is in the constructor. Then when you instantiate your ai, just give it the value that was passed forward from the previous frame and you will have created the only ai you need at the right difficulty setting.
EDIT:
It looks like you managed to get something similar working which is great! In case it helps you, I have included a brief example of how I would have done this below. Note that I also set it up such that your SimpleAiPlayerHandler constructor also takes an int value for instantiating the maxDepth variable. You'll need to add this. Since it uses classes I don't have, I can't compile it. However, if anyone else needs to do something similar, just remove everything in the DifficultyListener except the print statement and the line that get's the difficulty from the JComboBox and you'll see it working (and compiling).
import javax.swing.*;
import java.awt.event.*;
public class ChessSplash extends JFrame {
private final JComboBox<Difficulty> difficultySetting;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ChessSplash gui = new ChessSplash();
gui.setVisible(true);
}
});
}
public enum Difficulty {
EASY(1, "Easy"), MEDIUM(2, "Medium"), HARD(3, "Hard");
private final int intValue;
private final String stringValue;
private Difficulty(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
#Override
public String toString() {
return stringValue;
}
};
public ChessSplash() {
super("Chess Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
difficultySetting = new JComboBox<>(Difficulty.values());
JButton startButton = new JButton("Start Game");
startButton.addActionListener(new DifficultyListener());
JPanel mainPanel = new JPanel();
add(mainPanel);
mainPanel.add(difficultySetting);
mainPanel.add(startButton);
pack();
}
private class DifficultyListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//Declare AI
SimpleAiPlayerHandler ai;
//Declare and Instantiate Chess Game
ChessGame chessGame = new ChessGame();
//Human Player is the Object chessGui
ChessGui chessGui = new ChessGui(chessGame);
//Assign Human Player to White
chessGame.setPlayer(Piece.COLOR_WHITE, chessGui);
//Get the selected difficulty setting
Difficulty difficulty = (Difficulty)difficultySetting.getSelectedItem();
//Instantiate Computer AI pass it the maxDepth for use in the constructor
ai = new SimpleAiPlayerHandler(difficulty.intValue, chessGame);
//Assign Computer Player to Black
chessGame.setPlayer(Piece.COLOR_BLACK, ai);
//Demonstrate the enum combobox works
System.out.println(difficulty.intValue);
//Dispose of the splash JFrame
ChessSplash.this.dispose();
//Start your game thread (I would probably do something to move this
//onto the EDT if you're doing this is swing personally
new Thread(chessGame).start();
}
}
}
Related
I'm building a game where the object is to move a knight around a world and be able to fight other knights.
I've got a class Main that starts the game:
public class Main {
public static void main(String[] args) {
new Game();
}
}
A class Game that creates a JFrame:
import java.awt.GridLayout;
import javax.swing.JFrame;
public class Game {
public Game() {
JFrame frame = new JFrame();
frame.setTitle("Knights Tournament");
frame.add(new Board());
frame.setSize(700, 700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And a class Board which (you guessed it!) creates the GameBoard:
public class Board extends JPanel {
Tile[][] grid = new Tile[15][15];
public Board(){
// Create the grid
CreateGrid();
// Add the player
grid[0][0] = new Player(0, 0);
}
// Method that creates a grid of tiles
private void CreateGrid() {
setLayout(new GridLayout (15, 15));
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
grid[i][j] = new Tile(i, j);
add(grid[i][j]);
}
}
}
}
The grid initialy consists of 15x15 tiles.
public class Tile extends JButton implements ActionListener {
public int xCo;
public int yCo;
public Tile(int x, int y) {
setXCo(x);
setYCo(y);
}
public void setXCo(int x) {
this.xCo = x;
}
public void setYCo(int y) {
this.yCo = y;
}
public int getXCo() {
return xCo;
}
public int getYCo() {
return yCo;
}
}
The problem i'm facing is the following: I would like to replace grid[0][0] by another class Player that expands tile. The difference between tile and player would be that the Jbutton gets a text saying 'P' i've tried this:
public class Player extends Tile{
public Player(int x, int y) {
super(x, y);
this.setText("P");
}
}
In the constructor of the class board i tried changing grid[0][0] from tile to player so it would display P, but it doesn't do so for some reason (It does change the type of grid[0][0] to player...) I hope someone can help.
You shouldn't try and maintain the state of the object with the UI, per se. Rather the UI should visualise the state of the underlying logic of the game (or model). This allows you to modify the model, change the rules, add/remove elements (think adding new monsters or loot for example), without need to physically modify the UI or how it visualise this state (to a large degree).
The idea is, the Player attributes should be maintain with an class of it's own, which is managed by the model. The UI would then be used to visualise the state the model.
When clicked the Tile would notify the "controller". The controller would request stateful information from the games "model" and based on this information the "controller" would change the state of the button(s) to meet the requirements of the "model"
This would simply require the "controller" to update the button(s) information (text/icons) without needing to change the physical buttons.
This separates the responsibilities into defined layers and reduces the coupling of the code, so one or more layers can change, but the overall structure doesn't break down or need to be heavily modified to handle these changes.
The model is responsible for maintaining the virtual state of the game, for managing the interactions between the individual game objects (combat etc).
The UI is responsible for providing a visualisation of the model for the user and the controller is used to manage the interaction between the take, taking user input and pass it to the model, monitoring changes to the model's state and telling the UI when it needs to update.
The Model–view–controller paradigm is a common approach used in GUI development across different lanuguages. Take a look at Model–view–controller for more details.
This is for a project in school I have two different questions I would like advice on please. Here are the requirements from the teacher:
"Use Java collections to store pairs of unique colors and their unique hexadecimal values. Store up to 20 of these pairs. Then write a GUI that displays the color and/or hexadecimal values using radio buttons to select a value. When selected the background of the GUI should change to that color."
I read this to mean store them as pairs THEN make a GUI that uses JRadioButtons to change the color of the background.
I have this done and working fine. My issue is that I really feel there should be a more efficient way to make the jrb from the treeMap. I am thinking along the lines of calling the next set to fill the jrb, similar to using an array maybe.
Second part is the colors themselves. I see only a limited amount of colors in netbeans (i.e. no purple!) How can I get these colors included in this project for accuracy?
Not sure but any advise will be very much appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public final class FinalProject extends JFrame {
private static final int FRAME_WIDTH = 700;
private static final int FRAME_HEIGHT = 800;
private JRadioButton redButton;
private JRadioButton greenButton;
private JRadioButton blueButton;
private JRadioButton aquaButton;
private JRadioButton grayButton;
private JRadioButton fuchsiaButton;
private JRadioButton blackButton;
private JRadioButton limeButton;
private JRadioButton silverButton;
private JRadioButton maroonButton;
private JRadioButton navyButton;
private JRadioButton oliveButton;
private JRadioButton purpleButton;
private JRadioButton tealButton;
private JRadioButton yellowButton;
private JRadioButton cyanButton;
private JRadioButton orangeButton;
private JRadioButton tanButton;
private JRadioButton lavanderButton;
private JRadioButton plumButton;
private ActionListener listener;
public FinalProject()
{
TreeMap<String,String> colorselect = new TreeMap<String,String>();
colorselect.put("00FFFF","Aqua");
colorselect.put("008000","green");
colorselect.put("808080","gray");
colorselect.put("ff00ff","fuchaia");
colorselect.put("0000ff","blue");
colorselect.put("000000","black");
colorselect.put("00ff00","lime");
colorselect.put("c0c0c0","silver");
colorselect.put("800000","Maroon");
colorselect.put("000080","olive");
colorselect.put("ff0000","red");
colorselect.put("800080","purple");
colorselect.put("008080","teal");
colorselect.put("ffff00","yellow");
colorselect.put("00ffff","cyan");
colorselect.put("ffa500","orange");
colorselect.put("d2b4bc","tan");
colorselect.put("e6e6fa","lavander");
colorselect.put("dda0dd","plum");
// This listener is shared among all components
class ChoiceListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
setColor();
}
}
listener = new ChoiceListener();
createControlPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createControlPanel()
{
JPanel styleGroupPanel = createRadioButtons();
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout());
controlPanel.add(styleGroupPanel);
add(controlPanel, BorderLayout.NORTH);
}
public JPanel createRadioButtons()
{
redButton = new JRadioButton("Red");
redButton.addActionListener(listener);
greenButton = new JRadioButton("Green");
greenButton.addActionListener(listener);
aquaButton = new JRadioButton("aqua");
aquaButton.addActionListener(listener);
grayButton = new JRadioButton("gray");
grayButton.addActionListener(listener);
fuchsiaButton = new JRadioButton("fuchsia");
fuchsiaButton.addActionListener(listener);
blackButton = new JRadioButton("black");
blackButton.addActionListener(listener);
limeButton = new JRadioButton("lime");
limeButton.addActionListener(listener);
silverButton = new JRadioButton("silver");
silverButton.addActionListener(listener);
maroonButton = new JRadioButton("maroon");
maroonButton.addActionListener(listener);
navyButton = new JRadioButton("navy");
navyButton.addActionListener(listener);
oliveButton = new JRadioButton("olive");
oliveButton.addActionListener(listener);
purpleButton = new JRadioButton("purple");
purpleButton.addActionListener(listener);
tealButton = new JRadioButton("teal");
tealButton.addActionListener(listener);
yellowButton = new JRadioButton("yellow");
yellowButton.addActionListener(listener);
cyanButton = new JRadioButton("cyan");
cyanButton.addActionListener(listener);
orangeButton = new JRadioButton("orange");
orangeButton.addActionListener(listener);
tanButton = new JRadioButton("tan");
tanButton.addActionListener(listener);
lavanderButton = new JRadioButton("lavander");
lavanderButton.addActionListener(listener);
plumButton = new JRadioButton("plum");
plumButton.addActionListener(listener);
blueButton = new JRadioButton("Blue");
blueButton.addActionListener(listener);
blueButton.setSelected(true);
getContentPane().setBackground(Color.BLUE);
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(greenButton);
group.add(blueButton);
group.add(plumButton);
group.add(aquaButton);
group.add(grayButton);
group.add(fuchsiaButton);
group.add(blackButton);
group.add(limeButton);
group.add(silverButton);
group.add(maroonButton);
group.add(navyButton);
group.add(oliveButton);
group.add(purpleButton);
group.add(tealButton);
group.add(yellowButton);
group.add(cyanButton);
group.add(orangeButton);
group.add(tanButton);
group.add(lavanderButton);
JPanel panel = new JPanel();
panel.add(redButton);
panel.add(greenButton);
panel.add(blueButton);
panel.add(aquaButton);
panel.add(grayButton);
panel.add(fuchsiaButton);
panel.add(blackButton);
panel.add(limeButton);
panel.add(silverButton);
panel.add(maroonButton);
panel.add(navyButton);
panel.add(oliveButton);
panel.add(purpleButton);
panel.add(tealButton);
panel.add(yellowButton);
panel.add(cyanButton);
panel.add(orangeButton);
panel.add(tanButton);
panel.add(lavanderButton);
panel.add(plumButton);
panel.setPreferredSize(new Dimension(100,200));
return panel;
}
public void setColor()
{
if(redButton.isSelected())
{
getContentPane().setBackground(Color.RED);
}
if(greenButton.isSelected())
{
getContentPane().setBackground(Color.GREEN);
}
if(blueButton.isSelected())
{
getContentPane().setBackground(Color.BLUE);
}
if(aquaButton.isSelected())
{
getContentPane().setBackground(Color.GREEN);
}
if(grayButton.isSelected())
{
getContentPane().setBackground(Color.GRAY);
}
if(fuchsiaButton.isSelected())
{
getContentPane().setBackground(Color.PINK);
}
if(blackButton.isSelected())
{
getContentPane().setBackground(Color.BLACK);
}
if(limeButton.isSelected())
{
getContentPane().setBackground(Color.green);
}
if(silverButton.isSelected())
{
getContentPane().setBackground(Color.LIGHT_GRAY);
}
if(maroonButton.isSelected())
{
getContentPane().setBackground(Color.RED);
}
if(navyButton.isSelected())
{
getContentPane().setBackground(Color.BLUE);
}
if(oliveButton.isSelected())
{
getContentPane().setBackground(Color.green);
}
if(purpleButton.isSelected())
{
getContentPane().setBackground(Color.MAGENTA);
}
if(tealButton.isSelected())
{
getContentPane().setBackground(Color.BLUE);
}
if(yellowButton.isSelected())
{
getContentPane().setBackground(Color.YELLOW);
}
if(cyanButton.isSelected())
{
getContentPane().setBackground(Color.CYAN);
}
if(orangeButton.isSelected())
{
getContentPane().setBackground(Color.ORANGE);
}
if(tanButton.isSelected())
{
getContentPane().setBackground(Color.darkGray);
}
if(lavanderButton.isSelected())
{
getContentPane().setBackground(Color.MAGENTA);
}
if(plumButton.isSelected())
{
getContentPane().setBackground(Color.MAGENTA);
}
}
}
First, I think you are misinterpreting your teacher's instructions. I think when he says "Store up to 20 pairs" it means that your program should be flexible enough to accept up to 20 pairs, not exactly 20 pairs. And this implies that the program does not know the colors in advance. Also, when he says "unique", I believe he means you have to use Java collections to make sure that the colors and their values are unique.
And he most certainly did not intend that you will just fill up a collection without using it. The idea is to use the collection to build the GUI.
Be that as it may, creating a separate variable for each color button and going through a list of if statement is not good programming practice. Whenever you encounter a large group of similar items, on which you have to perform similar actions, it should be your cue to use a collection/array and a loop rather than write the same code over and over. Especially if you don't know if you need to use 10 colors or 20.
So:
Decide on a way to input the colors into the program - from command line, from a file, or whatever.
Decide on collections that will help you keep both the color name and the color value unique.
Write a loop that reads the input, checking for uniqueness, and stopping at 20 or when the data is done.
When you have the colors in the collections, use iteration to create buttons and add them to the button group and panel.
Even if you decide that you don't want to work hard on doing input, at the very least put the colors in a static array where you can quickly change it, add and remove colors, and make sure you read from that array into your collections using a loop and not one by one - just as if you were getting it from some kind of input source.
The important part is to have only one place where you change the data. In the way you implemented this, if you now decide to use maroon instead of teal, you have to go through many parts of the code, look for the teal, delete it and use maroon instead.
Now, about your ActionListener. Again, if you get to write dozens of similar if statements, you are on the wrong path. But here, what you are missing is the fact that you have a reference to the actual selected button within the ActionEvent that is passed to actionPerformed. You can use this reference to know which color to use. For example, when you create the button, if you set the name of the button to be the color, you can use
Object eventSource = event.getSource();
String colorName;
if ( eventSource instanceof JRadioButton ) {
colorName = ((JRadioButton)eventSource).getName();
// Now get the color value from the collection, build a Color and change the background.
}
There are other options like using a Map<JRadioButton,Color>. When you create the radio buttons, also create the associated Color and put the pair in this map. Now in actionPerformed you can simply look up the eventSource you got in this map, and you immediately get the Color object.
Something like this should do the trick. You can iterate around the entries in a hashmap and once you know that the repartition disappears
public final class FinalProject extends JFrame {
private Map<String, Color> colors = new TreeMap<String, Color>();
public FinalProject() {
colors.put("aqua", Color.decode("#00ffff"));
colors.put("green", Color.decode("#008000"));
colors.put("gray", Color.decode("#808080"));
colors.put("fuchsia", Color.decode("#ff00ff"));
colors.put("blue", Color.decode("#0000ff"));
colors.put("black", Color.decode("#000000"));
colors.put("lime", Color.decode("#00ff00"));
colors.put("silver", Color.decode("#c0c0c0"));
colors.put("maroon", Color.decode("#800000"));
colors.put("olive", Color.decode("#000080"));
colors.put("red", Color.decode("#ff0000"));
colors.put("purple", Color.decode("#800080"));
colors.put("teal", Color.decode("#008080"));
colors.put("yellow", Color.decode("#ffff00"));
colors.put("cyan", Color.decode("#00ffff"));
colors.put("orange", Color.decode("#ffa500"));
colors.put("tan", Color.decode("#d2b4bc"));
colors.put("lavender", Color.decode("#e6e6fa"));
colors.put("plum", Color.decode("#dda0dd"));
final JPanel colorSwash = new JPanel();
colorSwash.setPreferredSize(new Dimension(600, 600));
JPanel colorRadio = new JPanel();
colorRadio.setLayout(new GridLayout(2, 10, 20, 20));
for(final Map.Entry<String, Color> entry : colors.entrySet()){
JRadioButton rb = new JRadioButton(entry.getKey());
rb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
colorSwash.setBackground(entry.getValue());
}
});
colorRadio.add(rb);
}
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(BorderLayout.NORTH, colorRadio);
this.getContentPane().add(BorderLayout.CENTER, colorSwash);
}
public static void main(String[] args) {
FinalProject fp = new FinalProject();
fp.pack();
fp.setVisible(true);
fp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You can also add this small class right before the end of your class:
protected static class TreeMapBuilder {
private TreeMap<String,String> treeMap = new TreeMap<String, String>();
public TreeMapBuilder put(String color, String colorName) {
treeMap.put(color, colorName);
return this;
}
public TreeMap<String, String> end() {
return treeMap;
}
}
It will allow you to create the TreeMap this way:
TreeMap<String,String> colorselect = new TreeMapBuilder()
.put("00FFFF","Aqua")
.put("008000","green")
.put("808080", "grey")
.put(.............) (all your colors)
.end();
and can get you some extra points for style :)
Its been a while since i built a desktop JAVA application.. after lots of documentation and doing implementation tests, i still have not found an image grid solution.
Either Java lacks such a ready-to-use component (?!) or you tell me to brush up my google-fu. :)
I have a very simple technical premises: a JDialog that allows the user to pick an image. Input is a Map<Integer, String> list that holds filenames. Output is the Integer key the user chose. GUI also is simple: user chooses 1 image using mouse or keyboard, and dialog closes. All images are 80x80px and loaded from filename, not a resource.
I tried several approaches so far this morning:
Search for components/widgets that show scrollable imagegrid that can flow to the left. (no dice)
Search for components/widgets that show scrollable imagegrid (no dice)
Search for any components/widgets/gui-libs (no dice .. do these even exist?!)
Try and implement myJList.setModel(), but i cant get it to just take my Map<> and show thumbnails. (overcomplicates!)
Try and implement myJPanel.setlayout(new FlowLayout(..)) with several myJPanel.add(new JButton(..)) which just creates a bunch of JButton on a JPanel, which each need a event handler. I wonder how scrolling and keyboard input is going to work out, and how i'm supposed to keep/reference my Map<> key values. (overcomplicates?)
In lieu of your answer, i am now working on the latter, which should work but i cant believe everyone needs to reinvent the same GUI wheel here. How to have the user select an image from my Map<Integer, String>? Are there JAVA libraries/widgets/components that i should look to avoid this?
I hope this isn't being modded down, i have no working implementation with error to show you guys.. this question is about how/where to find the components or what approaches would be better. Its 2014 and i cant believe that JAVA still requires me to build my own "GUI component" just to see some images.. not even Delphi or Mono does that.
If all you want is a grid of images, and having them selectable, consider using a JList, filling it with appropriate ImageIcons, and giving it a ListSelectionListener. In the Listener you can close the enclosing dialog when a selection has been made.
You state:
Try and implement myJList.setModel(), but i cant get it to just take my Map<> and show thumbnails. (overcomplicates!)
You need to use your Map to populate your ListModel, and set that Model to the JList's model.
For example:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
#SuppressWarnings("serial")
public class ImageGridPanel extends JPanel {
public static final String PATH = "http://images-2.drive.com.au/2011/";
public static final String[] CARS = {
"04/15/2308961/giulietta_1024-80x80.jpg",
"11/18/2781958/audi-a1-sportback_600-80x80.jpg",
"12/23/2856762/fiat-500-80x80.jpg",
"01/12/2129944/Honda-Civic-Sedan-concept-1_600-80x80.jpg",
"12/23/2856581/mini-roadster-80x80.jpg",
"12/23/2856571/hyundai-veloster-80x80.jpg",
"12/23/2856771/hyundai-i30-80x80.jpg",
"12/23/2856580/mini-coupe-80x80.jpg" };
private DefaultListModel<Car> carModel = new DefaultListModel<>();
final JTextField textField = new JTextField(20);
public ImageGridPanel() {
for (String carPath : CARS) {
String path = PATH + carPath;
try {
URL imgUrl = new URL(path);
BufferedImage img = ImageIO.read(imgUrl);
ImageIcon icon = new ImageIcon(img);
String name = carPath.substring(carPath.lastIndexOf("/"));
name = name.substring(1, name.lastIndexOf("-"));
carModel.addElement(new Car(name, icon));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
ShowGridAction showAction = new ShowGridAction("Car Grid", carModel);
JButton showGridBtn = new JButton(showAction);
add(showGridBtn);
add(textField);
}
private class ShowGridAction extends AbstractAction {
private CarGridPanel carGridPanel;
public ShowGridAction(String name, DefaultListModel<Car> carModel) {
super(name);
carGridPanel = new CarGridPanel(carModel);
}
public CarGridPanel getCarGridPanel() {
return carGridPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((Component) e.getSource());
JDialog dialog = new JDialog(win, "Cars", ModalityType.APPLICATION_MODAL);
dialog.add(carGridPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
int x = dialog.getLocation().x;
int y = dialog.getLocation().y - 150;
dialog.setLocation(x, y);
dialog.setVisible(true);
Car selectedCar = carGridPanel.getSelectedCar();
if (selectedCar != null) {
textField.setText(selectedCar.getName());
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ImageGrid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ImageGridPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Car {
String name;
Icon icon;
public Car(String name, Icon icon) {
this.name = name;
this.icon = icon;
}
public String getName() {
return name;
}
public Icon getIcon() {
return icon;
}
}
#SuppressWarnings("serial")
class CarGridPanel extends JPanel {
private JList<Car> carList = new JList<>();
private Car selectedCar;
public CarGridPanel(ListModel<Car> model) {
carList.setModel(model);
carList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
carList.setVisibleRowCount(2);
carList.setCellRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) {
Car carValue = (Car) value;
value = carValue.getIcon();
} else {
value = "";
}
return super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
}
});
setLayout(new BorderLayout());
add(new JScrollPane(carList));
carList.addListSelectionListener(new ListListener());
}
public Car getSelectedCar() {
return selectedCar;
}
private class ListListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
selectedCar = carList.getSelectedValue();
Window win = SwingUtilities.getWindowAncestor(CarGridPanel.this);
win.dispose();
}
}
}
No, Java doesn't have what you want.
Java is a general-purpose programming language, not a toolset, particularly not a specialized desktop GUI toolset. This is not a denigration of the language, just a statement of a purpose that it was not developed to fulfill.
If Delphi or Mono or anything has your particular widget, then I suggest you program in that, instead. This is not a denigration of you, just an observation that, if you do not want to put together the widget you want from lower-level components and code, then Java is not the right language/tool for you to use to do it.
As for not believing that Java "still requires" you to build your own component, I can only say that you don't get to choose which languages provide which features. I'm just as glad Java isn't littered with your component and the hundreds of others that people like you would come up with that they think Java should provide. It's big enough as it is.
So, I'm working on a project that uses a GridLayout and an array of tictactoetile, which is a class which extends JButton.
For an example of the first thing I'm trying to do, I want to find out what button is clicked, and then set that button's text to equal either x or o depending on which turn it is. I have the logic for that down, I just don't know how to get the row and column of the button clicked.
Sorry if this is not worded well.
public class tictactoetile extends JButton implements ActionListener {
private int cory;
private int corx;
//Create your own GameObj class with the necessary members
//Some examples for members below...
private GameObj game;
public tictactoetile(int x,int y,GameObj gam) {
cory = y;
corx = x;
game = gam;
super();
}
public void actionPerformed(ActionEvent e) {
this.setText(game.getTurnMarker()); //returns either x or o
game.updateGameState(game.getTurn(),cory,corx);
game.nextTurn();
}
}
I started using jMonekyEngine and it's easy way of interacting with Swing GUI.
Following their tutorial here http://jmonkeyengine.org/wiki/doku.php/jme3:advanced:swing_canvas
It all works and I get everything loaded,however I'm having trouble modifying things.
According to their tutorial, the constant update and happens here:
public void simpleUpdate(float tpf) {
geom.rotate(0, 2 * tpf, 0);
}
(this is an example from the tutorial on rotating objects).
what i'm trying to do is just increasing and decreasing the speed of rotation (by changing the 2 or tpf with a variable which gets update inside an ActionListener in the Swing gui.
However, since in their tutorial they stated that the swing gui is to be created inside the main method, I have to create a variable which is static in order to change it.
static float rotate = 0.0f;
it gets modified inside the main method, but when trying to use it like so:
public void simpleUpdate(float tpf) {
geom.rotate(0, rotate * tpf, 0);
}
it remains constant to the initial value.
I tried creating a GUI class to build the gui (extends JPanel) and using getters and setters, but still not go..
Any help would be appreciated!
Thanks!
EDIT:
Here's how I change the rotate value:
JButton faster = new JButton("Faster");
faster.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
rotate +=0.1f;
}
});
inside the main method. rotate is a static field.
This is working for me
http://test.jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_main_event_loop
http://test.jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_input_system?s[]=input
Is your action listener really triggering the event on click? maybe you have a problem there and not in the rotate variable. Note that I'm not using swing on this example..
import com.jme3.app.SimpleApplication;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
/** Sample 4 - how to trigger repeating actions from the main update loop.
* In this example, we make the player character rotate. */
public class HelloLoop extends SimpleApplication {
public static void main(String[] args){
HelloLoop app = new HelloLoop();
app.start();
}
protected Geometry player;
#Override
public void simpleInitApp() {
Box b = new Box(Vector3f.ZERO, 1, 1, 1);
player = new Geometry("blue cube", b);
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
player.setMaterial(mat);
rootNode.attachChild(player);
initKeys();
}
/* This is the update loop */
#Override
public void simpleUpdate(float tpf) {
// make the player rotate
player.rotate(0, val*tpf, 0);
}
float val = 2f;
private void initKeys() {
// Adds the "u" key to the command "coordsUp"
inputManager.addMapping("sum", new KeyTrigger(KeyInput.KEY_ADD));
inputManager.addMapping("rest", new KeyTrigger(KeyInput.KEY_SUBTRACT));
inputManager.addListener(al, new String[]{"sum", "rest"});
}
private ActionListener al = new ActionListener() {
public void onAction(String name, boolean keyPressed, float tpf) {
if (name.equals("sum") ) {
val++;
}else if (name.equals("rest")){
val--;
}
}
};
}