List of DisplayModes contains each mode 3 times - java

I'm trying to get a list of available display modes for my laptop. I'm running the following code:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice display = ge.getDefaultScreenDevice();
DisplayMode[] availableModes = display.getDisplayModes();
This returns 112 possible display modes. When I print the list however I can see a lot of doubles. All most all display modes are printed 3 times. Would anyone know the cause of this?
800x600 8 bit 60 Hz
800x600 8 bit 60 Hz
800x600 8 bit 60 Hz
800x600 16 bit 60 Hz
800x600 16 bit 60 Hz
800x600 16 bit 60 Hz
800x600 32 bit 60 Hz
800x600 32 bit 60 Hz
800x600 32 bit 60 Hz
Kind regards

please to try that with this code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class DisplayModeModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
private DisplayMode[] modes;
public DisplayModeModel(DisplayMode[] modes) {
this.modes = modes;
}
public DisplayMode getDisplayMode(int r) {
return modes[r];
}
#Override
public String getColumnName(int c) {
return DisplayModeTest.COLUMN_NAMES[c];
}
#Override
public int getColumnCount() {
return DisplayModeTest.COLUMN_WIDTHS.length;
}
#Override
public boolean isCellEditable(int r, int c) {
return false;
}
#Override
public int getRowCount() {
if (modes == null) {
return 0;
}
return modes.length;
}
#Override
public Object getValueAt(int rowIndex, int colIndex) {
DisplayMode dm = modes[rowIndex];
switch (colIndex) {
case DisplayModeTest.INDEX_WIDTH:
return Integer.toString(dm.getWidth());
case DisplayModeTest.INDEX_HEIGHT:
return Integer.toString(dm.getHeight());
case DisplayModeTest.INDEX_BITDEPTH: {
int bitDepth = dm.getBitDepth();
String ret;
if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
ret = "Multi";
} else {
ret = Integer.toString(bitDepth);
}
return ret;
}
case DisplayModeTest.INDEX_REFRESHRATE: {
int refreshRate = dm.getRefreshRate();
String ret;
if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
ret = "Unknown";
} else {
ret = Integer.toString(refreshRate);
}
return ret;
}
}
throw new ArrayIndexOutOfBoundsException("Invalid column value");
}
}
class DisplayModeTest extends JFrame implements ActionListener, ListSelectionListener {
private static final long serialVersionUID = 1L;
private boolean waiting = false;
private GraphicsDevice device;
private DisplayMode originalDM;
private JButton exit = new JButton("Exit");
private JButton changeDM = new JButton("Set Display");
private JLabel currentDM = new JLabel();
private JTable dmList = new JTable();
private JScrollPane dmPane = new JScrollPane(dmList);
private boolean isFullScreen = false;
public static final int INDEX_WIDTH = 0;
public static final int INDEX_HEIGHT = 1;
public static final int INDEX_BITDEPTH = 2;
public static final int INDEX_REFRESHRATE = 3;
public static final int[] COLUMN_WIDTHS = new int[]{
100, 100, 100, 100
};
public static final String[] COLUMN_NAMES = new String[]{
"Width", "Height", "Bit Depth", "Refresh Rate"
};
public DisplayModeTest(GraphicsDevice device) {
super(device.getDefaultConfiguration());
this.device = device;
setTitle("Display Mode Test");
originalDM = device.getDisplayMode();
setDMLabel(originalDM);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Make sure a DM is always selected in the list
exit.addActionListener(this);
changeDM.addActionListener(this);
changeDM.setEnabled(device.isDisplayChangeSupported());
}
#Override
public void actionPerformed(ActionEvent ev) {
Object source = ev.getSource();
if (source == exit) {
device.setDisplayMode(originalDM);
System.exit(0);
} else { // if (source == changeDM)
int index = dmList.getSelectionModel().getAnchorSelectionIndex();
if (index >= 0) {
DisplayModeModel model = (DisplayModeModel) dmList.getModel();
DisplayMode dm = model.getDisplayMode(index);
device.setDisplayMode(dm);
setDMLabel(dm);
setSize(new Dimension(dm.getWidth(), dm.getHeight()));
validate();
}
}
}
#Override
public void valueChanged(ListSelectionEvent ev) {
changeDM.setEnabled(device.isDisplayChangeSupported());
}
private void initComponents(Container c) {
setContentPane(c);
c.setLayout(new BorderLayout());
JPanel currentPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// Current DM
c.add(currentPanel, BorderLayout.NORTH);
JLabel current = new JLabel("Current Display Mode : ");
currentPanel.add(current);
currentPanel.add(currentDM);
JPanel modesPanel = new JPanel(new GridLayout(1, 2));// Display Modes
c.add(modesPanel, BorderLayout.CENTER);
for (int i = 0; i < COLUMN_WIDTHS.length; i++) { // List of display modes
TableColumn col = new TableColumn(i, COLUMN_WIDTHS[i]);
col.setIdentifier(COLUMN_NAMES[i]);
col.setHeaderValue(COLUMN_NAMES[i]);
dmList.addColumn(col);
}
dmList.getSelectionModel().setSelectionMode( ListSelectionModel.SINGLE_SELECTION);
dmList.getSelectionModel().addListSelectionListener(this);
modesPanel.add(dmPane);
JPanel controlsPanelA = new JPanel(new BorderLayout());// Controls
modesPanel.add(controlsPanelA);
JPanel controlsPanelB = new JPanel(new GridLayout(2, 1));
controlsPanelA.add(controlsPanelB, BorderLayout.NORTH);
JPanel exitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// Exit
controlsPanelB.add(exitPanel);
exitPanel.add(exit);
JPanel changeDMPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// Change DM
controlsPanelB.add(changeDMPanel);
changeDMPanel.add(changeDM);
controlsPanelA.add(new JPanel(), BorderLayout.CENTER);
}
#Override
public void setVisible(boolean isVis) {
super.setVisible(isVis);
if (isVis) {
dmList.setModel(new DisplayModeModel(device.getDisplayModes()));
}
}
private void setDMLabel(DisplayMode newMode) {
int bitDepth = newMode.getBitDepth();
int refreshRate = newMode.getRefreshRate();
String bd, rr;
if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
bd = "Multi";
} else {
bd = Integer.toString(bitDepth);
}
if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
rr = "Unknown";
} else {
rr = Integer.toString(refreshRate);
}
currentDM.setText(
COLUMN_NAMES[INDEX_WIDTH] + ": " + newMode.getWidth() + " "
+ COLUMN_NAMES[INDEX_HEIGHT] + ": " + newMode.getHeight() + " "
+ COLUMN_NAMES[INDEX_BITDEPTH] + ": " + bd + " "
+ COLUMN_NAMES[INDEX_REFRESHRATE] + ": " + rr);
}
public void begin() {
isFullScreen = device.isFullScreenSupported();
setUndecorated(isFullScreen);
setResizable(!isFullScreen);
if (isFullScreen) {
device.setFullScreenWindow(this); // Full-screen mode
validate();
} else {
pack();// Windowed mode
setVisible(true);
}
}
public static void main(String[] args) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = env.getScreenDevices();
// REMIND : Multi-monitor full-screen mode not yet supported
for (int i = 0; i < 1 /* devices.length */; i++) {
DisplayModeTest test = new DisplayModeTest(devices[i]);
test.initComponents(test.getContentPane());
test.begin();
}
}
}

Related

Adding JPanels to JScrollPane

I'm trying to show multiple smaller JPanel on a JScrollPane.
To achieve this I currently add them to another JPanel and set this panel as the ViewportView of the scrollPane.
Is there a way to add the panels directly to the scrollpane?
What didn't work is this:
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(480, 480));
scrollPane.setSize(new Dimension(480, 480));
scrollPane.setMinimumSize(new Dimension(480, 40));
scrollPane.setViewportBorder(null);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
System.out.println("start");
for (int i=0; i<5;i++)
{
SingleClientPanel x = new SingleClientPanel();
x.setLocation(0, 45 *i);
scrollPane.getViewport().add(x);
}
To achieve this I currently add them to another JPanel and set this panel as the viewport of the scrollPane.
Not quite. You would not make the container JPanel the viewport but rather the viewport's view. The viewport itself is a very specialized container with its own layout manager, and this would be messed up if you simply replaced it with a JPanel.
i.e.,
JViewport viewport = myScrollPane.getViewport();
viewport.setView(myContainerJPanel);
or more concisely
myScrollPane.setViewportView(myContainerJPanel);
Note that this worries me: x.setLocation(0, 45 *i); and suggests use of null layouts somewhere. Whatever you do, don't do this, don't use null layouts, especially within JScrollPanes as it will muck it all up.
For more detailed help, consider creating and posting an sscce or a minimal example program/mcve where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem. Also consider posting an image of your desired output.
For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class ScrollPaneEg extends JPanel {
private static final int PREF_W = 480;
private static final int PREF_H = PREF_W;
public ScrollPaneEg() {
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportBorder(null);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel container = new JPanel(new GridLayout(0, 1)); // 1 column variable
// number of rows
for (int i = 0; i < 15; i++) {
SingleClientPanel x = new SingleClientPanel(String.valueOf(i + 1));
// x.setLocation(0, 45 *i);
container.add(x);
}
scrollPane.setViewportView(container);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
ScrollPaneEg mainPanel = new ScrollPaneEg();
JFrame frame = new JFrame("ScrollPaneEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class SingleClientPanel extends JPanel {
private static final int PREF_H = 60;
public SingleClientPanel(String text) {
setBorder(BorderFactory.createTitledBorder("Single Client"));
setLayout(new GridBagLayout());
add(new JLabel("Panel: " + text, SwingConstants.CENTER));
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(superSz.width, prefH);
}
}
Also, consider using a JTable to display your tabular data. For instance,...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.AbstractTableModel;
public class ClientOverviewTest {
private static void createAndShowGui() {
ClientOverviewPanel2 mainPanel = new ClientOverviewPanel2();
JFrame frame = new JFrame("ClientOverviewPanel");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class ClientOverviewPanel2 extends JPanel {
private static final int CLIENTS = 5;
private static final int PREF_W = 600;
private static final int PREF_H = 200;
private ClientTableModel model = new ClientTableModel();
private JTable table = new JTable(model);
public ClientOverviewPanel2() {
for (int i = 0; i < CLIENTS; i++) {
String ip = "127.000.000.001";
UUID uuid = UUID.randomUUID();
boolean isLocal = true;
SingleClient client = new SingleClient(ip, uuid, isLocal);
model.addRow(client);
}
table.getColumnModel().getColumn(1).setPreferredWidth(150); //!!
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(new JButton(new OkAction("OK")), BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = PREF_W;
int prefH = Math.min(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class OkAction extends AbstractAction {
public OkAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component source = (Component) e.getSource();
Window window = SwingUtilities.getWindowAncestor(source);
if (window != null) {
window.dispose();
}
}
}
}
class ClientTableModel extends AbstractTableModel {
public final static String[] COLUMNS = { "IP", "UUID", "Local" };
private List<SingleClient> clientList = new ArrayList<>();
#Override
public int getColumnCount() {
return COLUMNS.length;
}
#Override
public int getRowCount() {
return clientList.size();
}
#Override
public String getColumnName(int column) {
return COLUMNS[column];
}
public void addRow(SingleClient client) {
clientList.add(client);
int index = clientList.size() - 1;
fireTableRowsInserted(index, index);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex >= getRowCount() || rowIndex < 0) {
String text = "for rowIndex: " + rowIndex;
throw new IllegalArgumentException(text);
}
if (columnIndex < 0 || columnIndex >= COLUMNS.length) {
String text = "for columnIndex: " + columnIndex;
throw new IllegalArgumentException(text);
}
SingleClient client = clientList.get(rowIndex);
switch (columnIndex) {
case 0:
return client.getIp();
case 1:
return client.getUuid();
case 2:
return client.isLocal();
}
return null;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex < 0 || columnIndex >= COLUMNS.length) {
String text = "for columnIndex: " + columnIndex;
throw new IllegalArgumentException(text);
}
switch (columnIndex) {
case 0:
return String.class;
case 1:
return UUID.class;
case 2:
return Boolean.class;
}
// default value
return super.getColumnClass(columnIndex);
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 2;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
SingleClient client = clientList.get(rowIndex);
switch (columnIndex) {
case 0:
break;
case 1:
break;
case 2:
boolean isLocal = (boolean) aValue;
client.setLocal(isLocal);
default:
break;
}
}
}
class SingleClient {
private String ip;
private UUID uuid;
private boolean isLocal;
public SingleClient(String ip, UUID uuid2, boolean isLocal) {
this.ip = ip;
this.uuid = uuid2;
this.isLocal = isLocal;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public boolean isLocal() {
return isLocal;
}
public void setLocal(boolean isLocal) {
this.isLocal = isLocal;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ip == null) ? 0 : ip.hashCode());
result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SingleClient other = (SingleClient) obj;
if (ip == null) {
if (other.ip != null)
return false;
} else if (!ip.equals(other.ip))
return false;
if (uuid == null) {
if (other.uuid != null)
return false;
} else if (!uuid.equals(other.uuid))
return false;
return true;
}
}
Thanks to the help I was able to get it working. I'll just add my solution including changes for reference and further comments:
public class SingleClientPanel extends JPanel
{
private JTextField ipTextfield;
private JTextField uuidTextField;
public SingleClientPanel()
{
this("127.000.000.001",UUID.randomUUID().toString(),true);
}
public SingleClientPanel(String ip, String uuid,boolean isLocal)
{
/*
removed:
setSize(new Dimension(440, 35));
setPreferredSize(new Dimension(440, 35));
setMaximumSize(new Dimension(440, 35));
setMinimumSize(new Dimension(440, 35));*/
setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); // added this
ipTextfield = new JTextField();
ipTextfield.setHorizontalAlignment(SwingConstants.CENTER);
ipTextfield.setAlignmentX(Component.LEFT_ALIGNMENT);
ipTextfield.setFocusable(false);
ipTextfield.setEditable(false);
add(ipTextfield);
ipTextfield.setColumns(15);
ipTextfield.setText(ip);
uuidTextField = new JTextField();
uuidTextField.setHorizontalAlignment(SwingConstants.CENTER);
uuidTextField.setEditable(false);
uuidTextField.setFocusable(false);
add(uuidTextField);
uuidTextField.setColumns(30);
uuidTextField.setText(uuid);
JButton button = new JButton(">");
button.setEnabled(!isLocal);
add(button);
this.revalidate();
}
}
public class ClientOverviewPanel extends JPanel
{
public ClientOverviewPanel()
{
setLayout(new BorderLayout(0, 0));
JButton btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
Window x = SwingUtilities.getWindowAncestor(ClientOverviewPanel.this);
if(x != null) x.dispose();
}
});
add(btnOk, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane();
/*
removed:
scrollPane.setPreferredSize(new Dimension(480, 480));
scrollPane.setSize(new Dimension(480, 480));
scrollPane.setMinimumSize(new Dimension(480, 40));*/
scrollPane.setViewportBorder(null);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
Box box = new Box(BoxLayout.PAGE_AXIS); //added
for (int i=0; i<5;i++)
{
SingleClientPanel cpan = new SingleClientPanel();
//cpan.setLocation(0, 45 *i); removed
box.add(cpan); //changed
}
scrollPane.setViewportView(box); //changed
add(scrollPane, BorderLayout.CENTER);
this.revalidate();
}
}

java Swing timer to perform few tasks one after another

I am perfectly aware very similar questions few asked before. I have tried to implement solutions offered - in vain. ...The problem i am facing is to blink buttons ONE AFTER ANOTHER. I can do it for one, but when put the order of blinking in a loop - everything breaks. Any help to a new person to Java is appreciated. P.S. I am not allowed to use Threads. What i am having now is:
Timer colorButton = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < pcArray.length; i++) {
playSquare = pcArray[i];
System.out.println("PlaySquare " + playSquare);
if (playSquare == 1) {
if (alreadyColoredRed) {
colorBack.start();
colorButton.stop();
} else {
red.setBackground(Color.red);
alreadyColoredRed = true;
System.out.println("RED DONE");
}
} else if (playSquare == 2) {
if (alreadyColoredGreen) {
colorBack.start();
colorButton.stop();
} else {
green.setBackground(Color.green);
alreadyColoredGreen = true;
System.out.println("GREEN DONE");
}
}
}
}
});
Timer colorBack = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < pcArray.length; i++) {
playSquare = pcArray[i];
System.out.println("PlaySquare " + playSquare);
if (playSquare == 1) {
red.setBackground(Color.gray);
alreadyColoredRed = false;
System.out.println("RED PAINTED BACK");
colorBack.stop();
} else if (playSquare == 2) {
green.setBackground(Color.gray);
alreadyColoredGreen = false;
System.out.println("GREEN PAINTED BACK");
colorBack.stop();
}
}
}
});
I don't think that having two Timer instances is the way to go. The Swing Timer is notorious for 'drifting' away from the perfect beat over time.
Better to create a single timer with the logic needed to control all actions.
E.G. Showing the allowable moves for a Chess Knight.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class KnightMove {
KnightMove() {
initUI();
}
ActionListener animationListener = new ActionListener() {
int blinkingState = 0;
#Override
public void actionPerformed(ActionEvent e) {
final int i = blinkingState % 4;
chessSquares[7][1].setText("");
chessSquares[5][0].setText("");
chessSquares[5][2].setText("");
switch (i) {
case 0:
setPiece(chessSquares[5][0], WHITE + KNIGHT);
break;
case 1:
case 3:
setPiece(chessSquares[7][1], WHITE + KNIGHT);
break;
case 2:
setPiece(chessSquares[5][2], WHITE + KNIGHT);
}
blinkingState++;
}
};
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new GridLayout(8, 8));
ui.setBorder(new CompoundBorder(new EmptyBorder(4, 4, 4, 4),
new LineBorder(Color.BLACK,2)));
boolean black = false;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
JLabel l = getColoredLabel(black);
chessSquares[r][c] = l;
ui.add(l);
black = !black;
}
black = !black;
}
for (int c = 0; c < 8; c++) {
setPiece(chessSquares[0][c], BLACK + STARTING_ROW[c]);
setPiece(chessSquares[1][c], BLACK + PAWN);
setPiece(chessSquares[6][c], WHITE + PAWN);
setPiece(chessSquares[7][c], WHITE + STARTING_ROW[c]);
}
Timer timer = new Timer(750, animationListener);
timer.start();
}
private void setPiece(JLabel l, int piece) {
l.setText("<html><body style='font-size: 60px;'>&#" + piece + ";");
}
private final JLabel getColoredLabel(boolean black) {
JLabel l = new JLabel();
l.setBorder(new LineBorder(Color.DARK_GRAY));
l.setOpaque(true);
if (black) {
l.setBackground(Color.GRAY);
} else {
l.setBackground(Color.WHITE);
}
return l;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
KnightMove o = new KnightMove();
JFrame f = new JFrame("Knight Moves");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.setResizable(false);
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
private JComponent ui = null;
JLabel[][] chessSquares = new JLabel[8][8];
public static final int WHITE = 9812, BLACK = 9818;
public static final int KING = 0, QUEEN = 1,
ROOK = 2, KNIGHT = 4, BISHOP = 3, PAWN = 5;
public static final int[] STARTING_ROW = {
ROOK, KNIGHT, BISHOP, KING, QUEEN, BISHOP, KNIGHT, ROOK
};
}

Hello I am creating a TicTacToe game for myself to understand Java better

however I am not sure where I am supposed to enter the whoWins() method. Do I enter this method in the actionperformed Method of the buttons or do i need to something different. Please help.
public class TTT extends JFrame implements ActionListener {
private JButton buttons[] = new JButton[9];
private JButton exitButton;
public JLabel title;
public JPanel titlePanel, panel;
private int count = 0;
int symbolCount = 0;
private boolean win = false;
public TTT() {
title = new JLabel("Welcome to my Tic Tac Toe Game!");
titlePanel = new JPanel();
title.setFont(new Font(Font.SERIF, 0, 30));
titlePanel.add(title);
this.add(titlePanel, BorderLayout.NORTH);
panel = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
panel.add(buttons[i]);
buttons[i].setEnabled(true);
buttons[i].addActionListener(this);
}
this.add(panel, BorderLayout.CENTER);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
exitButton = new JButton("Quit");
panel1.add(exitButton);
this.add(panel1, BorderLayout.SOUTH);
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(WIDTH);
}
});
}
public void whoWins() {
//Determines who wins using for the horizontal rows.
if (buttons[0].getText() == buttons[1].getText() && buttons[1].getText() == buttons[2].getText() && buttons[0].getText() != "") {
win = true;
} else if (buttons[3].getText() == buttons[4].getText() && buttons[4].getText() == buttons[5].getText() && buttons[3].getText() != "") {
win = true;
} else if (buttons[6].getText() == buttons[7].getText() && buttons[7].getText() == buttons[8].getText() && buttons[6].getText() != "") {
win = true;
} //Determines the verticles wins
else if (buttons[0].getText() == buttons[3].getText() && buttons[3].getText() == buttons[6].getText() && buttons[0].getText() != "") {
win = true;
} else if (buttons[1].getText() == buttons[4].getText() && buttons[4].getText() == buttons[7].getText() && buttons[1].getText() != "") {
win = true;
} else if (buttons[2].getText() == buttons[5].getText() && buttons[5].getText() == buttons[8].getText() && buttons[2].getText() != "") {
win = true;
}
// Diagnol Wins
else if (buttons[0].getText()==buttons[4].getText()&&buttons[4].getText()==buttons[8].getText()&& buttons[0].getText()!= "") {
win = true;
}else if (buttons[2].getText()==buttons[4].getText()&&buttons[4].getText()==buttons[6].getText()&& buttons[1].getText()!= "") {
win = true;
}else {
win = false;
}
//who won
if (win = true) {
JOptionPane.showMessageDialog(null, "wins");
}else if (count == 9 && win == false) {
JOptionPane.showMessageDialog(null, "Tie game");
}
}
public static void main(String[] args) {
TTT ref1 = new TTT();
ref1.setTitle("Tic Tac Toe");
ref1.setVisible(true);
ref1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ref1.setSize(500, 500);
ref1.setLocationRelativeTo(null);
// ref1.whoWins();
}
#Override
public void actionPerformed(ActionEvent e) {
count++;
for (JButton button : buttons) {
if (button == e.getSource()) {
if (symbolCount % 2 == 0) {
button.setText("X");
button.setEnabled(false);
} else {
button.setText("O");
button.setEnabled(false);
}
}
}
if (count >= buttons.length) {
JOptionPane.showMessageDialog(null, "End");
}
symbolCount++;
}
}
If you really want to do this right, then I suggest making some big changes, some M-V-C type changes:
First and foremost, separate out the logic of the game from the game GUI. This would mean that the code that determines who wins should not be in any code that contains GUI type code. This will be your "model"
Next you should never have GUI code implement listener interfaces, so try to get that out of the GUI and possibly have it go into its own class, the "Control" class.
Finally the GUI or "View" class will concern itself with displaying the model's state and getting input from the user and transmitting this input to the control.
For example,...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.EnumMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
public class TicTacToeMain {
private static void createAndShowGui() {
TttView view = null;
try {
view = new TttView();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
TttModel model = new TttModel();
new TttControl(model, view);
JFrame frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(view.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
enum TttPiece {
EMPTY, X, O
}
class TttView {
public static final String IMAGE = "/imgFolder/TicTacToe.png";
private static final int GAP = 5;
private JPanel mainPanel = new JPanel();
private JPanel tttPanel = new JPanel();
private Map<TttPiece, Icon> iconMap = new EnumMap<>(TttPiece.class);
private JLabel[][] grid = new JLabel[TttModel.ROWS][TttModel.COLS];
private TttControl control;
public TttView() throws IOException {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream(IMAGE));
Icon[] imgIcons = splitImg(img);
iconMap.put(TttPiece.X, imgIcons[0]);
iconMap.put(TttPiece.O, imgIcons[1]);
iconMap.put(TttPiece.EMPTY, createEmptyIcon(imgIcons[0]));
tttPanel.setLayout(new GridLayout(grid.length, grid[0].length, GAP, GAP));
tttPanel.setBackground(Color.black);
MyMouseAdapter mouseAdapter = new MyMouseAdapter();
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
grid[row][col] = new JLabel(iconMap.get(TttPiece.EMPTY));
grid[row][col].setOpaque(true);
grid[row][col].setBackground(Color.LIGHT_GRAY);
grid[row][col].addMouseListener(mouseAdapter);
tttPanel.add(grid[row][col]);
}
}
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(new JButton(new ClearAction("Clear", KeyEvent.VK_C)));
btnPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
int blGap = 2;
mainPanel.setLayout(new BorderLayout(blGap, blGap));
mainPanel.setBorder(BorderFactory.createEmptyBorder(blGap, blGap, blGap,
blGap));
mainPanel.add(tttPanel, BorderLayout.CENTER);
mainPanel.add(btnPanel, BorderLayout.SOUTH);
}
public void setControl(TttControl control) {
this.control = control;
}
public JComponent getMainPanel() {
return mainPanel;
}
private Icon createEmptyIcon(Icon icon) {
int width = icon.getIconWidth();
int height = icon.getIconHeight();
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
return new ImageIcon(img);
}
private Icon[] splitImg(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
int gap = 5;
Icon[] icons = new ImageIcon[2];
icons[0] = new ImageIcon(img.getSubimage(0, 0, w / 2 - gap, h / 2 - gap));
icons[1] = new ImageIcon(img.getSubimage(w / 2 + gap, 0, w / 2 - gap, h
/ 2 - gap));
return icons;
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
if (control == null) {
return;
}
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
if (grid[row][col] == e.getSource()) {
control.gridPress(row, col);
}
}
}
}
}
private class ClearAction extends AbstractAction {
public ClearAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (control != null) {
control.clear();
}
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (control != null) {
control.exit(evt);
}
}
}
public void setGridIcon(int row, int col, TttPiece tttPiece) {
grid[row][col].setIcon(iconMap.get(tttPiece));
}
}
class TttControl {
private TttModel model;
private TttView view;
public TttControl(TttModel model, TttView view) {
this.model = model;
this.view = view;
view.setControl(this);
model.addPropertyChangeListener(new ModelListener());
}
public void exit(ActionEvent evt) {
Window win = SwingUtilities
.getWindowAncestor((Component) evt.getSource());
win.dispose();
}
public void gridPress(int row, int col) {
try {
model.gridPress(row, col);
} catch (TttException e) {
// TODO: notify user
// e.printStackTrace();
}
}
public void clear() {
model.clear();
}
private class ModelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (TttModel.GRID_POSITION.equals(evt.getPropertyName())) {
TttPiece[][] tttGrid = model.getTttGrid();
for (int row = 0; row < tttGrid.length; row++) {
for (int col = 0; col < tttGrid[row].length; col++) {
view.setGridIcon(row, col, tttGrid[row][col]);
}
}
}
}
}
}
class TttModel {
public static final int ROWS = 3;
public static final int COLS = ROWS;
public static final String GRID_POSITION = "grid position";
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
this);
private TttPiece[][] tttGrid = new TttPiece[ROWS][COLS];
private TttPiece player = TttPiece.X;
private boolean gameOver;
public TttModel() {
clear();
}
public void setGridPosition(int row, int col, TttPiece piece)
throws TttException {
if (gameOver) {
return;
}
if (tttGrid[row][col] == TttPiece.EMPTY) {
tttGrid[row][col] = piece;
checkForWin(row, col, piece);
nextPlayer();
pcSupport.firePropertyChange(GRID_POSITION, null, tttGrid);
} else {
String message = "Invalid setGridPosition for row: %d, col: %d, piece: %s. "
+ "Spot already occupied by piece: %s";
message = String.format(message, row, col, piece, tttGrid[row][col]);
throw new TttException(message);
}
}
public TttPiece[][] getTttGrid() {
return tttGrid;
}
public void gridPress(int row, int col) throws TttException {
setGridPosition(row, col, player);
}
public void nextPlayer() {
player = player == TttPiece.X ? TttPiece.O : TttPiece.X;
}
private void checkForWin(int row, int col, TttPiece piece) {
// TODO finish
}
public void clear() {
for (int row = 0; row < tttGrid.length; row++) {
for (int col = 0; col < tttGrid[row].length; col++) {
tttGrid[row][col] = TttPiece.EMPTY;
}
}
player = TttPiece.X;
pcSupport.firePropertyChange(GRID_POSITION, null, tttGrid);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
}
#SuppressWarnings("serial")
class TttException extends Exception {
public TttException() {
super();
}
public TttException(String message) {
super(message);
}
}
Using for my images:
With GUI looking like:
I am also interested in writing a Tic Tac Toe game, so I copied your code, and did a little modification, and it passed test, check following:
package eric.j2se.swing;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* <p>
* Simple game of Tic Tac Toe.
* </p>
*
* #author eric
* #date Apr 16, 2014 11:03:48 AM
*/
#SuppressWarnings("serial")
public class TicTacToe extends JFrame implements ActionListener {
// 2 players
public static final char playerX = 'X';
public static final char playerO = 'O';
// null player
public static final char playerN = 'N';
// the winer, init to null player
private Character winner = playerN;
// indicate whether game over
private boolean gameOver = false;
// count of button used,
private int count = 0;
private Character buttonPlayers[] = new Character[9];
private JButton buttons[] = new JButton[9];
private JButton exitButton;
public JLabel title;
public JPanel titlePanel, panel;
public TicTacToe() {
// init buttonPlayers
for (int i = 0; i < 9; i++) {
buttonPlayers[i] = playerN;
}
// init title
title = new JLabel("Welcome to Tic Tac Toe!");
titlePanel = new JPanel();
title.setFont(new Font(Font.SERIF, 0, 30));
titlePanel.add(title);
this.add(titlePanel, BorderLayout.NORTH);
// init 9 button
panel = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
panel.add(buttons[i]);
buttons[i].setEnabled(true);
buttons[i].addActionListener(this);
}
// init exit button
this.add(panel, BorderLayout.CENTER);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
exitButton = new JButton("Quit");
panel1.add(exitButton);
this.add(panel1, BorderLayout.SOUTH);
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(WIDTH);
}
});
}
public void whoWins() {
// determine winner - horizontal rows
if (!gameOver) {
for (int i = 0; i < 3; i++) {
if ((buttonPlayers[0 + i * 3] != playerN) && (buttonPlayers[0 + i * 3].equals(buttonPlayers[1 + i * 3]))
&& buttonPlayers[1 + i * 3].equals(buttonPlayers[2 + i * 3])) {
winner = buttonPlayers[0 + i * 3];
gameOver = true;
break;
}
}
}
// determine winner - vertical rows
if (!gameOver) {
for (int i = 0; i < 3; i++) {
if ((buttonPlayers[i + 0 * 3] != playerN) && (buttonPlayers[i + 0 * 3].equals(buttonPlayers[i + 1 * 3]))
&& buttonPlayers[i + 1 * 3].equals(buttonPlayers[i + 2 * 3])) {
winner = buttonPlayers[i + 0 * 3];
gameOver = true;
break;
}
}
}
// determine winner - diagonal rows
if (!gameOver) {
int winButtonIndex = -1;
if ((buttonPlayers[0] != playerN) && (buttonPlayers[0].equals(buttonPlayers[4])) && buttonPlayers[4].equals(buttonPlayers[8])) {
winButtonIndex = 0;
} else if ((buttonPlayers[2] != playerN) && (buttonPlayers[2].equals(buttonPlayers[4])) && buttonPlayers[4].equals(buttonPlayers[6])) {
winButtonIndex = 2;
}
if (winButtonIndex >= 0) {
winner = buttonPlayers[winButtonIndex];
gameOver = true;
}
}
// full
if (count == 9) {
gameOver = true;
}
if (gameOver) {
String tip = "";
switch (winner) {
case playerO:
tip = "Player O win!";
break;
case playerX:
tip = "Player X win!";
break;
default:
tip = "Draw game!";
break;
}
JOptionPane.showMessageDialog(null, tip);
}
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
JButton button = buttons[i];
if (button == e.getSource()) {
Character currentPlayer = (count % 2 == 1 ? playerX : playerO);
button.setText(String.valueOf(currentPlayer));
buttonPlayers[i] = currentPlayer;
button.setEnabled(false);
break;
}
}
count++;
whoWins();
}
public static void main(String[] args) {
TicTacToe ref1 = new TicTacToe();
ref1.setTitle("Tic Tac Toe");
ref1.setVisible(true);
ref1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ref1.setSize(500, 500);
ref1.setLocationRelativeTo(null);
}
}
about when to call the win check:
check each time you click 1 of the 9 buttons,
about the flag:
I use 2 flag instead of 1 flag to indicate game over & winner, because in TTT game, draw game is very usual, after play several times, you always get draw game ...
a little suggestion to your code:
when compare string, use equals(), not ==,
define const values in variable, not write it in logic, e.g. 'O' 'X',
don't repeat code, try use logic control to make it short & easy to read & easy to maintain,

Fixing method latency in Java

Another problem, same program:
The following is MainGUI.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MainGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 4149825008429377286L;
private final double version = 8;
public static int rows;
public static int columns;
private int totalCells;
private MainCell[] cell;
public static Color userColor;
JTextField speed = new JTextField("250");
Timer timer = new Timer(250,this);
String generationText = "Generation: 0";
JLabel generationLabel = new JLabel(generationText);
int generation = 0;
public MainGUI(String title, int r, int c)
{
rows = r;
columns = c;
totalCells = r*c;
System.out.println(totalCells);
cell = new MainCell[totalCells];
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Timer set up
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.setActionCommand("timer");
//set up menu bar
JMenuBar menuBar = new JMenuBar();
JMenu optionsMenu = new JMenu("Options");
JMenu aboutMenu = new JMenu("About");
menuBar.add(optionsMenu);
menuBar.add(aboutMenu);
JMenuItem helpButton = new JMenuItem("Help!");
helpButton.addActionListener(this);
helpButton.setActionCommand("help");
aboutMenu.add(helpButton);
JMenuItem aboutButton = new JMenuItem("About");
aboutButton.addActionListener(this);
aboutButton.setActionCommand("about");
aboutMenu.add(aboutButton);
JMenuItem colorSelect = new JMenuItem("Select a Custom Color");
colorSelect.addActionListener(this);
colorSelect.setActionCommand("colorSelect");
optionsMenu.add(colorSelect);
JMenuItem sizeChooser = new JMenuItem("Define a Custom Size");
sizeChooser.addActionListener(this);
sizeChooser.setActionCommand("sizeChooser");
optionsMenu.add(sizeChooser);
//Create text field to adjust speed and its label
JPanel speedContainer = new JPanel();
JLabel speedLabel = new JLabel("Enter the speed of a life cycle (in ms):");
speedContainer.add(speedLabel);
speedContainer.add(speed);
speedContainer.add(generationLabel);
Dimension speedDim = new Dimension(100,25);
speed.setPreferredSize(speedDim);
//Create various buttons
JPanel buttonContainer = new JPanel();
JButton randomizerButton = new JButton("Randomize");
randomizerButton.addActionListener(this);
randomizerButton.setActionCommand("randomize");
buttonContainer.add(randomizerButton);
JButton nextButton = new JButton("Next"); //forces a cycle to occur
nextButton.addActionListener(this);
nextButton.setActionCommand("check");
buttonContainer.add(nextButton);
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
buttonContainer.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
buttonContainer.add(stopButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
buttonContainer.add(clearButton);
//holds the speed container and button container, keeps it neat
JPanel functionContainer = new JPanel();
BoxLayout functionLayout = new BoxLayout(functionContainer, BoxLayout.PAGE_AXIS);
functionContainer.setLayout(functionLayout);
functionContainer.add(speedContainer);
speedContainer.setAlignmentX(CENTER_ALIGNMENT);
functionContainer.add(buttonContainer);
buttonContainer.setAlignmentX(CENTER_ALIGNMENT);
//finish up with the cell container
GridLayout cellLayout = new GridLayout(rows,columns);
JPanel cellContainer = new JPanel(cellLayout);
cellContainer.setBackground(Color.black);
int posX = 0;
int posY = 0;
for(int i=0;i<totalCells;i++)
{
MainCell childCell = new MainCell();
cell[i] = childCell;
childCell.setName(String.valueOf(i));
childCell.setPosX(posX);
posX++;
childCell.setPosY(posY);
if(posX==columns)
{
posX = 0;
posY++;
}
cellContainer.add(childCell);
childCell.deactivate();
Graphics g = childCell.getGraphics();
childCell.paint(g);
}
//make a default color
userColor = Color.yellow;
//change icon
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
//add it all up and pack
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
container.add(cellContainer);
container.add(functionContainer);
add(menuBar);
setJMenuBar(menuBar);
add(container);
pack();
}
private void checkCells()
{
//perform check for every cell
for(int i=0;i<totalCells;i++)
{
cell[i].setNeighbors(checkNeighbors(i));
}
//use value from check to determine life
for(int i=0;i<totalCells;i++)
{
int neighbors = cell[i].getNeighbors();
if(cell[i].isActivated())
{
System.out.println(cell[i].getName()+" "+neighbors);
if(neighbors==0||neighbors==1||neighbors>3)
{
cell[i].deactivate();
}
}
if(cell[i].isActivated()==false)
{
if(neighbors==3)
{
cell[i].activate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
//help button, self-explanatory
if(e.getActionCommand().equals("help"))
{
JOptionPane.showMessageDialog(this, "The game is governed by four rules:\nFor a space that is 'populated':"
+ "\n Each cell with one or no neighbors dies, as if by loneliness."
+ "\n Each cell with four or more neighbors dies, as if by overpopulation."
+ "\n Each cell with two or three neighbors survives."
+ "\nFor a space that is 'empty' or 'unpopulated':"
+ "\n Each cell with three neighbors becomes populated."
+ "\nLeft click populates cells. Right click depopulates cells.","Rules:",JOptionPane.PLAIN_MESSAGE);
}
//shameless self promotion
if(e.getActionCommand().equals("about"))
{
JOptionPane.showMessageDialog(this, "Game made and owned by *****!"
+ "\nFree usage as see fit, but give credit where credit is due!\nVERSION: "+version,"About:",JOptionPane.PLAIN_MESSAGE);
}
//clears all the cells
if(e.getActionCommand().equals("clear"))
{
timer.stop();
generation = 0;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
}
}
//starts timer
if(e.getActionCommand().equals("start"))
{
if(Integer.parseInt(speed.getText())>0)
{
timer.setDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
else
{
JOptionPane.showMessageDialog(this, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
}
//stops timer
if(e.getActionCommand().equals("stop"))
{
timer.stop();
}
//run when timer
if(e.getActionCommand().equals("timer"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
timer.stop();
checkCells();
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
//see checkCells()
if(e.getActionCommand().equals("check"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
checkCells();
}
//color select gui
if(e.getActionCommand().equals("colorSelect"))
{
userColor = JColorChooser.showDialog(this, "Choose a color:", userColor);
if(userColor==null)
{
userColor = Color.yellow;
}
}
//size chooser!
if(e.getActionCommand().equals("sizeChooser"))
{
SizeChooser size = new SizeChooser();
size.setLocationRelativeTo(null);
size.setVisible(true);
}
}
private int checkNeighbors(int c)
{
//if a LIVE neighbor is found, add one
int neighbors = 0;
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=0)
{
if(c-columns-1>=0)
{
if(cell[c-columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=0)
{
if(c-columns>=0)
{
if(cell[c-columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=0)
{
if(c-columns+1>=0)
{
if(cell[c-columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0)
{
if(c-1>=0)
{
if(cell[c-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1)
{
if(c+1<totalCells)
{
if(cell[c+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=rows-1)
{
if(c+columns-1<totalCells)
{
if(cell[c+columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=rows-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns<totalCells)
{
if(cell[c+columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns+1<totalCells)
{
if(cell[c+columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns+1].getName());
neighbors++;
}
}
}
return neighbors;
}
}
The following is MainCell.java:
public class MainCell extends JPanel implements MouseListener
{
//everything here should be self-explanatory
private static final long serialVersionUID = 1761933778208900172L;
private boolean activated = false;
public static boolean leftMousePressed;
public static boolean rightMousePressed;
private int posX = 0;
private int posY = 0;
private int neighbors = 0;
private URL cellImgURL_1 = getClass().getResource("images/cellImage_1.gif");
private ImageIcon cellImageIcon_1 = new ImageIcon(cellImgURL_1);
private Image cellImage_1 = cellImageIcon_1.getImage();
private URL cellImgURL_2 = getClass().getResource("images/cellImage_2.gif");
private ImageIcon cellImageIcon_2 = new ImageIcon(cellImgURL_2);
private Image cellImage_2 = cellImageIcon_2.getImage();
private URL cellImgURL_3 = getClass().getResource("images/cellImage_3.gif");
private ImageIcon cellImageIcon_3 = new ImageIcon(cellImgURL_3);
private Image cellImage_3 = cellImageIcon_3.getImage();
public MainCell()
{
Dimension dim = new Dimension(17, 17);
setPreferredSize(dim);
addMouseListener(this);
}
public void activate()
{
setBackground(MainGUI.userColor);
System.out.println(getName()+" "+posX+","+posY+" activated");
setActivated(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
else if(getPosY()!=0&&getPosX()!=MainGUI.columns-1)
{
g.drawImage(cellImage_1,0,0,null);
}
else if(getPosY()==0)
{
g.drawImage(cellImage_2,0,0,null);
}
else if(getPosX()==MainGUI.columns-1)
{
g.drawImage(cellImage_3,0,0,null);
}
}
public void setActivated(boolean b)
{
activated = b;
}
public void deactivate()
{
setBackground(Color.gray);
System.out.println(getName()+" "+posX+","+posY+" deactivated");
setActivated(false);
}
public boolean isActivated()
{
return activated;
}
public void setNeighbors(int i)
{
neighbors = i;
}
public int getNeighbors()
{
return neighbors;
}
public int getPosX()
{
return posX;
}
public void setPosX(int x)
{
posX = x;
}
public int getPosY()
{
return posY;
}
public void setPosY(int y)
{
posY = y;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
if(leftMousePressed&&SwingUtilities.isLeftMouseButton(e))
{
activate();
}
if(rightMousePressed&&SwingUtilities.isRightMouseButton(e))
{
deactivate();
}
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e)&&!leftMousePressed)
{
deactivate();
rightMousePressed = true;
}
if(SwingUtilities.isLeftMouseButton(e)&&!rightMousePressed)
{
activate();
leftMousePressed = true;
}
}
public void mouseReleased(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e))
{
rightMousePressed = false;
}
if(SwingUtilities.isLeftMouseButton(e))
{
leftMousePressed = false;
}
}
}
The following is SizeChooser.java:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SizeChooser extends JFrame
{
private static final long serialVersionUID = -6431709376438241788L;
public static MainGUI GUI;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField rowsTextField = new JTextField(String.valueOf((screenSize.height/17)-15));
JTextField columnsTextField = new JTextField(String.valueOf((screenSize.width/17)-10));
private static int rows = screenSize.height/17-15;
private static int columns = screenSize.width/17-10;
public SizeChooser()
{
setResizable(false);
setTitle("Select a size!");
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
add(container);
JLabel rowsLabel = new JLabel("Rows:");
container.add(rowsLabel);
container.add(rowsTextField);
JLabel columnsLabel = new JLabel("Columns:");
container.add(columnsLabel);
container.add(columnsTextField);
JButton confirmSize = new JButton("Confirm");
confirmSize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GUI.setVisible(false);
GUI = null;
if(Integer.parseInt(rowsTextField.getText())>0)
{
rows = Integer.parseInt(rowsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
if(Integer.parseInt(columnsTextField.getText())>0)
{
columns = Integer.parseInt(columnsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
setVisible(false);
}
});
container.add(confirmSize);
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
pack();
}
public static void main(String[]args)
{
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
}
}
So the problem now is, when the randomize button is pressed, or a large number of cells exist and then the timer is started, the cells aren't as snappy as they would be with less active cells. For example, with 100 columns and 50 rows, when the randomize button is pressed, one cell activates, then the next, then another, and so forth. Can I have them all activate at exactly the same time? Is this just a problem with too many things calculated at once? Would concurrency help?
QUICK EDIT: Is the swing timer the best idea for this project?
I havent read through your code completely but I am guessing that your listener methods are fairly computationally intensive and hence the lag in updating the display.
This simple test reveals that your randomize operation should be fairly quick:
public static void main(String args[]) {
Random rn = new Random();
boolean b[] = new boolean[1000000];
long timer = System.nanoTime();
for (int i = 0; i < b.length; i++) {
b[i] = rn.nextInt(6) == 0;
}
timer = System.nanoTime() - timer;
System.out.println(timer + "ns / " + (timer / 1000000) + "ms");
}
The output for me is:
17580267ns / 17ms
So this leads me into thinking activate() or deactivate() is causing your UI to be redrawn.
I am unable to run this because I don't have your graphical assets, but I would try those changes to see if it works:
In MainGUI#actionPerformed, change:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
to:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
// This will not cause the object to be redrawn and should
// be a fairly cheap operation
cell[i].setActivated(rn.nextInt(6)==0);
}
// Cause the UI to repaint
repaint();
}
Add this to MainCell
// You can specify those colors however you like
public static final Color COLOR_ACTIVATED = Color.RED;
public static final Color COLOR_DEACTIVATED = Color.GRAY;
And change:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
to:
protected void paintComponent(Graphics g)
{
// We now make UI changes only when the component is painted
setBackground(activated ? COLOR_ACTIVATED : COLOR_DEACTIVATED);
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}

Java JCombobox do not change the image in JPanel

I have a problem.
I have an element that would JPanel.
In this JPanel would be four JButtons and image.
This image is 'green LED lights' that would change depending on which JButton would be pressed.
It works very well.
But also I want the JComboBox to change this paramter.
And here's the problem.
Although the parameter (from 1 to 4) is changing,(this shows JLabel near LEDs),
but the picture (LED lights) do not want to change it to the right one.
screenshot
The program is divided into 3 classes.
MyFrame.class This main class.
public class MyFrame extends JFrame {
int ctrlTriggers = 1;
private JLabel label = new JLabel();
private Triggers triggers;
private String[] typeTrig = {"1", "2", "3", "4"};
public MyFrame() {
JFrame frame = new JFrame("JComboBox Problem");
frame.setBounds(50, 0, 800, 240);
frame.setLayout(new BorderLayout());
int tvalue = 1;
String tstr = Integer.toString(tvalue);
JPanel panelTrig = new JPanel(new BorderLayout());
label = new JLabel(tstr, 4);
panelTrig.add(label);
final JLabel et = label;
triggers = new Triggers(typeTrig, "trigger " + Integer.toString(1));
triggers.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Triggers tr = (Triggers) e.getSource();
int vol;
vol = (int) tr.getValue();
et.setText(Integer.toString(vol));
}
});
panelTrig.add(triggers, BorderLayout.LINE_START);
// JCOMBOBOX
JPanel pCombo = new JPanel();
pCombo.setLayout(new FlowLayout());
Presets combo = new Presets();
combo.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Presets presetcombo = (Presets) e.getSource();
int tval;
tval = (int) presetcombo.getValue(ctrlTriggers);
label.setText(Integer.toString(tval));
triggers.setValue(tval);
}
});
pCombo.add(combo, BorderLayout.CENTER);
frame.add(pCombo, BorderLayout.CENTER);
frame.add(panelTrig, BorderLayout.LINE_START);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.show();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyFrame();
}
});
}
}
Triggers.class This class is JPanel where is 4 JButton and 'LED like image'
public class Triggers extends JPanel
implements ActionListener, ItemListener {
public Triggers(String s[], String name) {
JPanel panel = new JPanel(new BorderLayout());
this.value = Integer.parseInt(s[selected]);
for (int i = 0; i < s.length; i++) {
ImageIcon cup = new ImageIcon();
button[i] = new JButton(z[i], cup);
button[i].setPreferredSize(new Dimension(70, 25));
Font font = button[i].getFont();
button[i].setFont(new Font(font.getFontName(), font.getStyle(), 10));
button[i].setActionCommand(s[i]);
if (i == selected) {
button[i].setSelected(true);
} else {
button[i].setSelected(false);
}
}
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < s.length; i++) {
group.add(button[i]);
button[i].addActionListener(this);
button[i].addItemListener(this);
}
diody = new JLabel(createImageIcon("/resources/diody/"
+ this.value
+ ".png"));
diody.setPreferredSize(new Dimension(20, 100));
JPanel triggs = new JPanel(new FlowLayout());
triggs.setPreferredSize(new Dimension(80, 120));
for (int i = 0; i < s.length; i++) {
triggs.add(button[i]);
}
panel.add(triggs, BorderLayout.LINE_START);
panel.add(diody, BorderLayout.LINE_END);
add(panel);
}
public void actionPerformed(ActionEvent e) {
cmd = e.getActionCommand();
diody.setIcon(createImageIcon("/resources/diody/"
+ cmd
+ ".png"));
if (cmd.equals("1")) {
setValue(1);
} else if (cmd.equals("2")) {
setValue(2);
} else if (cmd.equals("3")) {
setValue(3);
} else if (cmd.equals("4")) {
setValue(4);
}
}
public static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Triggers.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public int setController() {
return value;
}
public void setValue(int k) {
this.value = k;
cmd = Integer.toString(this.value);
repaint();
fireChangeEvent();
}
public int getValue() {
return this.value;
}
public void setSel(int k) {
selected = k;
repaint();
fireChangeEvent();
}
public void itemStateChanged(ItemEvent ie) {
String s = (String) ie.getItem();
}
public void addChangeListener(ChangeListener cl) {
listenerList.add(ChangeListener.class, cl);
}
public void removeChangeListener(ChangeListener cl) {
listenerList.remove(ChangeListener.class, cl);
}
protected void fireChangeEvent() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
private ChangeEvent changeEvent = null;
private EventListenerList listenerList = new EventListenerList();
private JLabel diody;
private int x = 1;
private int y = 4;
private JButton button[] = new JButton[y];
double border = 4;
double vborder = 1;
int controller[] = new int[4];
String z[] = {"1", "2", "3", "4"};
private int selected;
private int value;
private String cmd;
}
class Presets Here is JCombobox.
public class Presets extends JPanel
implements ActionListener {
private int value;
private int[] ctrlIdx = new int[27];
private int controller;
private ChangeEvent changeEvent = null;
private EventListenerList listenerList = new EventListenerList();
private JLabel label;
private String[][] presets = {
{"0", "3"},
{"1", "2"},
{"2", "3"},
{"3", "1"},
{"4", "4"},
{"5", "2"},};
String[] ctrlName = {"preset 1 (value 3)", "preset 2 (value 2)", "preset 3 (value 3)", "preset 4 (value 1)", "preset 5 (value 4)", "preset 5 (value 2)"};
public Presets() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(600, 30));
JComboBox combolist = new JComboBox(ctrlName);
combolist.setSelectedIndex(2);
combolist.addActionListener(this);
combolist.setPreferredSize(new Dimension(300, 30));
label = new JLabel();
label.setFont(label.getFont().deriveFont(Font.ITALIC));
label.setHorizontalAlignment(JLabel.CENTER);
int indeks = combolist.getSelectedIndex();
updateLabel(ctrlName[combolist.getSelectedIndex()], indeks);
label.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
label.setPreferredSize(new Dimension(300, 30));
panel.add(combolist, "East");
add(panel);
setPreferredSize(new Dimension(600, 40));
}
public void setSelectedItem(int a) {
}
public void setValue(int c, int v) {
controller = c;
value = v;
ctrlIdx[controller] = value;
repaint();
fireChangeEvent();
}
public int getController() {
return controller;
}
public int getValue(int c) {
int w = (int) ctrlIdx[c];
return (int) w;
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String pres = (String) cb.getSelectedItem();
int indeks = cb.getSelectedIndex();
updateLabel(pres, indeks);
for (int i = 0; i < ctrlName.length; i++) {
for (int j = 0; j < 2; j++) {
setValue(j, Integer.parseInt(presets[indeks][j]));
}
}
}
protected void updateLabel(String name, int ii) {
label.setToolTipText("A drawing of a " + name.toLowerCase());
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Presets.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public void addChangeListener(ChangeListener cl) {
listenerList.add(ChangeListener.class, cl);
}
public void removeChangeListener(ChangeListener cl) {
listenerList.remove(ChangeListener.class, cl);
}
protected void fireChangeEvent() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
}
Could someone help me, what am I doing wrong?
Your image is only begin loaded in the actionPerformed method of your Triggers class, which means when you call setValue in response to the stateChanged event thrown by the Presets class, no new image is begin loaded.
Move your image loading logic so it is either in the setValue method or triggered by the setValue method

Categories