So here is what i have so far for my sudoku game. Now my grid only displays textboxes where a user can input numbers but nothing will happen yet. I want to know how to make it so that the user can only input one character and only numbers. i would also like to know how to make some textboxes jdialogs displaying uneditable numbers that im taking from http://www.websudoku.com/ for the puzzle. Any help would be appreciated. Thanks.
Main Class
import javax.swing.JOptionPane;
public class Game{
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello. Welcome to a game of Sudoku by #### ####.");
Level select = new Level();
}
}
Difficulty Select Class
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Level extends JFrame {
private JLabel tag1;
private JButton butt1;
private JButton butt2;
private JButton butt3;
private JButton butt4;
public Level(){
super("Difficulty");
setLayout(new FlowLayout());
setSize(250,130);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tag1 = new JLabel("Please Select Your Difficulty.");
add(tag1);
butt1 = new JButton("Easy.");
butt1.setToolTipText("For players new to Sudoku.");
add(butt1);
butt2 = new JButton("Medium.");
butt2.setToolTipText("Your abilites will be tested.");
add(butt2);
butt3 = new JButton("Hard.");
butt3.setToolTipText("Your skills will be strained.");
add(butt3);
butt4 = new JButton("Evil!");
butt4.setToolTipText("You will not survive.");
add(butt4);
thehandler handler = new thehandler();
butt1.addActionListener(handler);
butt2.addActionListener(handler);
butt3.addActionListener(handler);
butt4.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==butt1){
dispose();
string = "Have fun!";
SudokuPanel Squares = new SudokuPanel();
}
else if(event.getSource()==butt2){
dispose();
string = "Good luck!";
SudokuPanel Squares = new SudokuPanel();
}
else if(event.getSource()==butt3){
dispose();
string = "Try to keep your head from exploding...";
SudokuPanel Squares = new SudokuPanel();
}
else if(event.getSource()==butt4){
dispose();
string = "Please refrain from smashing any keyboards.";
SudokuPanel Squares = new SudokuPanel();
}
JOptionPane.showMessageDialog(null, string);
}
}
}
Sudoku Panel Class
import java.awt.BorderLayout;
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.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class SudokuPanel extends JFrame {
public final int SQUARE_COUNT = 9;
public Squares [] squares = new Squares[SQUARE_COUNT];
public SudokuPanel(){
super("Sudoku");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3,3));
for(int i=0; i<SQUARE_COUNT; i++){
squares[i] = new Squares();
panel.add(squares[i]);
}
JPanel panel2 = new JPanel();
JButton startTime = new JButton();
JButton stop = new JButton();
JButton resetTimer = new JButton();
MyTimer timer = new MyTimer();
startTime = new JButton("Start Timer");
stop = new JButton("Stop Timer");
final JLabel timerLabel = new JLabel(" ...Waiting... ");
resetTimer = new JButton("Reset");
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem newDifficulty = new JMenuItem("Select New Difficulty");
menu.add(newDifficulty);
JMenuItem reset = new JMenuItem("Reset Puzzle");
menu.add(reset);
JMenuItem exit = new JMenuItem("Exit");
menu.add(exit);
exitaction e = new exitaction();
newDifficultyaction d = new newDifficultyaction();
resetaction f = new resetaction();
reset.addActionListener(f);
exit.addActionListener(e);
newDifficulty.addActionListener(d);
panel2.add(timer);
add(panel, BorderLayout.CENTER);
add(panel2, BorderLayout.PAGE_END);
setVisible(true);
setLocationRelativeTo(null);
}
public class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
public class newDifficultyaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
Level select = new Level();
}
}
public class resetaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
SudokuPanel Squares = new SudokuPanel();
}
}
}
Squares/Cells class
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Squares extends JPanel {
public final int CELL_COUNT = 9;
public Cell [] cells = new Cell[CELL_COUNT];
public Squares(){
this.setLayout(new GridLayout(3,3));
this.setBorder(new LineBorder(Color.BLACK,2));
for(int i =0; i<CELL_COUNT; i++){
cells[i] = new Cell();
this.add(cells[i]);
}
}
public class Cell extends JTextField{
private int number;
public Cell(){
}
public void setNumber(int number){
this.number = number;
this.setText("1");
}
public int getNumber(){
return number;
}
}
}
Timer Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyTimer extends Panel {
private JLabel timeDisplay;
private JButton resetButton;
private JButton startButton;
private JButton stopButton;
Timer timer;
public MyTimer(){
startButton = new JButton("Start Timer");
stopButton = new JButton("Stop Timer");
timeDisplay = new JLabel("...Waiting...");
this.add(startButton);
this.add(stopButton);
this.add(timeDisplay);
event e = new event();
startButton.addActionListener(e);
event1 c = new event1();
stopButton.addActionListener(c);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
int count = 0;
timeDisplay.setText("Elapsed Time in Seconds: " + count);
TimeClass tc = new TimeClass(count);
timer = new Timer(1000, tc);
timer.start();
}
}
public class TimeClass implements ActionListener{
int counter;
public TimeClass(int counter){
this.counter = counter;
}
public void actionPerformed(ActionEvent e){
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener{
public void actionPerformed (ActionEvent c){
timer.stop();
}
}
}
I want to know how to make it so that the user can only input one character and only numbers.
There are several ways, all easily discoverable by searching this site, as this problem is a common one. Two I'll mention: use a JFormattedTextField, or use a JTextField whose Document has a DocumentFilter added to it that prevents wrong input from being entered.
i would also like to know how to make some textboxes jdialogs displaying uneditable numbers that im taking from http://www.websudoku.com/ for the puzzle. Any help would be appreciated.
Several possible solutions to this one including
Set the component's enabled property to false.
Set the component's focusable property to false.
Some issues with your post:
You mention use of "textboxes". I recommend you avoid using non-Java non-Swing terms like "textboxes" as they only will serve to confuse. If you are using a specific type of text component and are asking about it, mention the component type by name as solutions may differ depending on the type.
You have posted a wall of code, most of it unrelated to your problem at hand. Please remember that we are volunteers, and please be kind to us. One way is to avoid posting too much unrelated code. Best would be to post a small minimal example program for questions that need this.
Related
Everything looks ok to me but for some reason, nothing is showing up properly, maybe I missed something but I'm not sure why it's not working, can someone help me out?
** task **
Improve your program by adding two
combo boxes in the frame. Through the combo boxes, the user should be able to
select their preferred fonts and font sizes. The displayed text will then be updated
accordingly (see the figure below).
Here is what its suppose to look like
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
public class ComboGUI extends JFrame implements ActionListener {
public JButton update;
public JTextField textField;
public JLabel textLabel;
public JComboBox<String> fontBox;
public JComboBox sizeBox;
public String font;
public String size;
public ComboGUI()
{
components();
panels();
actionListener();
}
public void components()
{
this.update = new JButton("update");
this.textField=new JTextField(20);
this.textField.setText("hello");
this.textLabel= new JLabel("GUI");
this.font="Arial";
this.size="20";
this.textLabel.setFont(new Font(this.font, Font.PLAIN, Integer.parseInt(this.size)));
this.fontBox=new JComboBox();
this.fontBox.addItem("Times New Roman");
this.fontBox.addItem("Calibri");
this.sizeBox= new JComboBox();
this.sizeBox.addItem("20");
this.sizeBox.addItem("30");
this.sizeBox.addItem("40");
this.setSize(400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
}
public void panels(){
JPanel northPanel =new JPanel();
JLabel fontLabel =new JLabel("Font: ");
JLabel sizeLabel =new JLabel("size: ");
northPanel.add(fontLabel);
//center
BGPanel centerPanel =new BGPanel();
centerPanel.add(this.textLabel);
this.add(centerPanel,BorderLayout.CENTER);
//south
BGPanel southPanel =new BGPanel();
southPanel.add(this.textLabel);
this.add(southPanel,BorderLayout.CENTER);
}
public void actionListener(){
this.update.addActionListener(this);
this.fontBox.addActionListener(this);
this.sizeBox.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==this.update){
this.textLabel.setText(this.textField.getText());
}
if(e.getSource()==this.fontBox || e.getSource()==this.sizeBox){
this.font=this.fontBox.getSelectedItem().toString();
this.size=this.sizeBox.getSelectedItem().toString();
this.textLabel.setFont(new Font(this.font,Font.PLAIN,Integer.parseInt(this.size)));
}
this.repaint();
}
public static void main(String[] args) {
ComboGUI comb =new ComboGUI();
combo.setVisible(true);
}
}
this is what im getting instead
It looks like you are missing this.setVisible(true); at the end of your constructor.
Your code should look like this:
public ComboGUI()
{
components();
panels();
actionListener();
this.setVisible(true);
}
incase anyone is trying to do something similar, this is the complete solution
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class ComboGUI extends JFrame implements ActionListener{
public void updateLabelText(){
size = fSize.getItemAt(fSize.getSelectedIndex());
font = fStyles.getItemAt(fStyles.getSelectedIndex());
updateLabel.setFont(new Font(font,Font.PLAIN,size));
}
public static BGPanel centrePanel;
public JComboBox<String> fStyles;
public JComboBox<Integer> fSize;
public JButton updateButton;
public JLabel updateLabel;
public JLabel fontLabel;
public JLabel sizeLabel;
public JTextField textField;
public JPanel BottomPanel;
public JPanel topPanel;
private String font;
private int size;
public ComboGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setLocation(0, 0);
//Top
topPanel = new JPanel();
fontLabel = new JLabel("Font:");
sizeLabel = new JLabel("Font Size:");
fStyles = new JComboBox<String>();
fStyles.addItem("Arial");
fStyles.addItem("TimesRoman");
fStyles.addItem("Serif");
fStyles.addItem("Monospaced");
fStyles.addActionListener(this);
fSize = new JComboBox<Integer>();
fSize.addItem(10);
fSize.addItem(20);
fSize.addItem(30);
fSize.addItem(40);
fSize.addActionListener(this);
topPanel.add(fontLabel);
topPanel.add(fStyles);
topPanel.add(sizeLabel);
topPanel.add(fSize);
//CentrePanel setup
centrePanel = new BGPanel();
updateLabel = new JLabel("I love PDC :)");
centrePanel.add(updateLabel);
//Bottom
BottomPanel = new JPanel();
updateButton = new JButton("Update");
textField = new JTextField(20);
textField.setText("I love PDC :)");
updateButton.addActionListener(this);
BottomPanel.add(textField);
BottomPanel.add(updateButton);
this.add(centrePanel,BorderLayout.CENTER);
this.add(BottomPanel,BorderLayout.SOUTH);
this.add(topPanel,BorderLayout.NORTH);
updateLabelText();
}
public static void main(String[] args) {
ComboGUI combo = new ComboGUI();
combo.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == updateButton){
updateLabel.setText(textField.getText().trim());
}
if(e.getSource() == fStyles){
updateLabelText();
}
if (e.getSource() == fSize){
updateLabelText();
}
}
}
So my code starts off this way in the Start Button Handler for my game. The goal is to have random buttons to select and then click those random buttons and print out the number of times you clicked the button into the console. But I have no idea how to do so. Here is my code so far :
My Start button class :
package code;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class StartButton implements ActionListener{
int clickCounter;
private JFrame _j;
public StartButton(JFrame frame){
_j = frame;
}
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("ABC");
frame2.setVisible(true);
frame2.setSize(200,200);
frame2.setLocationRelativeTo(null);
JLabel label = new JLabel("Game");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
_j.setVisible(false); //This creates a new game frame
JButton button = new JButton("A");
panel.add(button);
JButton button1 = new JButton("B");
panel.add(button1);
JButton button2 = new JButton("C");
panel.add(button2);
ButtonHandler b;
b = new ButtonHandler (button, button1, button2);
button.addActionListener(b);
button1.addActionListener(b);
button2.addActionListener(b);
Random r = new Random();
int x = r.nextInt(3);
if (x==0) {button.setEnabled(true); button1.setEnabled(false); button2.setEnabled(false);}
if (x==1) {button1.setEnabled(true); button.setEnabled(false); button2.setEnabled(false);}
if (x==2) {button2.setEnabled(true); button.setEnabled(false); button1.setEnabled(false);}
Timer t = new Timer (10000, null);
t.addActionListener(new GameCloser());
t.start();
}
}
My ButtonHandler Class :
package code;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
public class ButtonHandler implements ActionListener {
private JButton _b1;
private JButton _b2;
private JButton _b3;
public ButtonHandler(JButton button, JButton button1, JButton button2){
_b1 = button;
_b2=button1;
_b3=button2;
}
#Override
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
int x = r.nextInt(3);
if (x==0) {_b1.setEnabled(true); _b2.setEnabled(false); _b3.setEnabled(false);}
if (x==1) {_b2.setEnabled(true); _b1.setEnabled(false); _b3.setEnabled(false);}
if (x==2) {_b3.setEnabled(true); _b1.setEnabled(false); _b2.setEnabled(false);}
}
}
ANd here is my my class for closing the game:
package code;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameCloser implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Congrats, you clicked it "+" times");
System.exit(0);
HOW DO I FIT A COUNTER :( ??
Store the click counts in ButtonHandler private int field.
And then add the ButtonHandler to your GameCloser
public class GameCloser implements ActionListener {
private final ButtonHandler buttonHandler;
public GameCloser(ButtonHandler buttonHandler){
this.buttonHandler = buttonHalder;
}
#Override
public void actionPerformed(ActionEvent e) {
int clickTimes = buttonHandler.getClickTimes();
System.out.println("Congrats, you clicked it "+" times");
System.exit(0);
Update:
public class ButtonHandler implements ActionListener {
private JButton _b1;
private JButton _b2;
private JButton _b3;
/*The click counter <----*/
private int clickCounter = 0;
public ButtonHandler(JButton button, JButton button1, JButton button2){
_b1 = button;
_b2=button1;
_b3=button2;
}
#Override
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
int x = r.nextInt(3);
clickCounter++;//Increment click counter <---
if (x==0) {_b1.setEnabled(true); _b2.setEnabled(false); _b3.setEnabled(false);}
if (x==1) {_b2.setEnabled(true); _b1.setEnabled(false); _b3.setEnabled(false);}
if (x==2) {_b3.setEnabled(true); _b1.setEnabled(false); _b2.setEnabled(false);}
}
/* returns the number of clicks */
public int getClickTimes(){
return clickCounter;
}
}
My program is supposed to have the basic code examples in java and to do that I need help to have the dialogues where I can write have the code preloaded but I can't add spaces in the dialogues and resize them. Please help!
Main Class:
public class JavaHelperTester{
public static void main(String[] args){
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
}
Method Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaHelper extends JPanel implements ActionListener{
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper(){
setPreferredSize(new Dimension(500,350));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == print){
JOptionPane.showMessageDialog (null, "System.out.println(); and System.out.print();", "Print Statements", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == classes){
JOptionPane.showMessageDialog (null, "Main class : public class ClassNameTester{ // public static void main(String[] args){, Other Classes : public class ClassName", "Classes", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == quit){
System.exit(0);
}
}
private void dialogSize(){
}
}
JavaWindow:
import java.awt.*;
import javax.swing.*;
public class JavaWindow extends JFrame{
private Container c;
public JavaWindow(){
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p){
c.add(p);
}
public void showFrame(){
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I made changes to clean up the Java Helper GUI and to allow you to format the information on the JOptionPane dialogs.
Here's the Java Helper GUI.
And here's the Classes JOptionPane.
I modified your JavaHelperTester class to include a call to the SwingUtilities invokeLater method. This method puts the creation and use of your Swing components on the Event Dispatch thread (EDT). A Swing GUI must start with a call to the SwingUtilities invokeLater method.
I also formatted all of your code and resolved the imports.
package com.ggl.java.helper;
import javax.swing.SwingUtilities;
public class JavaHelperTester {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
};
SwingUtilities.invokeLater(runnable);
}
}
Here's your JavaWindow class.
package com.ggl.java.helper;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaWindow extends JFrame {
private static final long serialVersionUID = 6535974227396542181L;
private Container c;
public JavaWindow() {
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here's your JavaHelper class. I made the changes to your action listener to allow you to define the text as an HTML string. You may only use HTML 3.2 commands.
I also changed your button panel to use the GridLayout. The grid layout makes your buttons look neater and makes it easier for the user to select a JButton.
package com.ggl.java.helper;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaHelper extends JPanel implements ActionListener {
private static final long serialVersionUID = -3150356430465932424L;
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper() {
this.setLayout(new GridLayout(0, 2));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == print) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createPrintText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == classes) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createClassesText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == quit) {
System.exit(0);
}
}
private String createPrintText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("System.out.print()");
builder.append("<br>");
builder.append("System.out.println()");
builder.append("</code></pre>");
return builder.toString();
}
private String createClassesText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("Main class : public class ClassNameTester { <br>");
builder.append(" public static void main(String[] args) { <br>");
builder.append(" } <br>");
builder.append("} <br><br>");
builder.append("Other Classes : public class ClassName { <br>");
builder.append("}");
builder.append("</code></pre>");
return builder.toString();
}
}
I have a grid of JTextFields for my sudoku gui but im confused as to how to place for example a 3 in the top left box, in the top left corner of that box so it looks something like this
http://tinypic.com/r/t7io28/8
and that number becomes un editable to the user?
Here's my class for setting the cells:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class Squares extends JPanel {
public final int CELL_COUNT = 9;
public Cell [] cells = new Cell[CELL_COUNT];
public Squares(){
this.setLayout(new GridLayout(3,3));
this.setBorder(new LineBorder(Color.BLACK,2));
for(int i = 0; i<CELL_COUNT; i++){
cells[i] = new Cell();
cells[i].setDocument(new NumericalDocument());
this.add(cells[i]);
}
}
public class Cell extends JTextField{
private int number;
public Cell(){
}
public void setNumber(int number){
this.number = number;
this.setText("5");
}
public int getNumber(){
return number;
}
}
public static class NumericalDocument extends PlainDocument{
String numbers = "0123456789";
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (getLength() == 0 && str.length() == 1 && numbers.contains(str)) {
super.insertString(offs, str, a);
}
else {
Toolkit.getDefaultToolkit().beep();
}
}
}
}
and here's the class that sets the 3x3 cells into a 3x3 grid
import java.awt.BorderLayout;
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.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class SudokuPanel extends JFrame {
public final int SQUARE_COUNT = 9;
public Squares [] squares = new Squares[SQUARE_COUNT];
public SudokuPanel(){
super("Sudoku");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3,3));
for(int i=0; i<SQUARE_COUNT; i++){
squares[i] = new Squares();
panel.add(squares[i]);
}
JPanel panel2 = new JPanel();
JButton startTime = new JButton();
JButton stop = new JButton();
JButton submit = new JButton();
MyTimer timer = new MyTimer();
startTime = new JButton("Start Timer");
stop = new JButton("Stop Timer");
final JLabel timerLabel = new JLabel(" ...Waiting... ");
submit = new JButton("Done");
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem newDifficulty = new JMenuItem("Select New Difficulty");
menu.add(newDifficulty);
JMenuItem reset = new JMenuItem("Reset Puzzle");
menu.add(reset);
JMenuItem exit = new JMenuItem("Exit");
menu.add(exit);
exitaction e = new exitaction();
newDifficultyaction d = new newDifficultyaction();
resetaction f = new resetaction();
reset.addActionListener(f);
exit.addActionListener(e);
newDifficulty.addActionListener(d);
panel2.add(timer);
add(panel, BorderLayout.CENTER);
add(panel2, BorderLayout.PAGE_END);
setVisible(true);
setLocationRelativeTo(null);
}
public class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
public class newDifficultyaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
Level select = new Level();
}
}
public class resetaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
SudokuPanel Squares = new SudokuPanel();
}
}
}
A JTextField can be set uneditable using setEditable(false). You could also use JLabels.
Hi i am creating a java desktop application where i want to show image and i want that all image should change in every 5 sec automatically i do not know how to do this
here is my code
public class ImageGallery extends JFrame
{
private ImageIcon myImage1 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\yellow.png");
private ImageIcon myImage2 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\d.jpg");
private ImageIcon myImage3 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\e.jpg");
private ImageIcon myImage4 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\f.jpg");
JPanel ImageGallery = new JPanel();
private ImageIcon[] myImages = new ImageIcon[4];
private int curImageIndex=0;
public ImageGallery ()
{
ImageGallery.add(new JLabel (myImage1));
myImages[0]=myImage1;
myImages[1]=myImage2;
myImages[2]=myImage3;
myImages[3]=myImage4;
add(ImageGallery, BorderLayout.NORTH);
JButton PREVIOUS = new JButton ("Previous");
JButton NEXT = new JButton ("Next");
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,4));
Menu.add(PREVIOUS);
Menu.add(NEXT);
add(Menu, BorderLayout.SOUTH);
}
How can i achieve this?
Thanks in advance
In this example, a List<JLabel> holds each image selected from a List<Icon>. At each step of a javax.swing.Timer, the list of images is shuffled, and each image is assigned to a label.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
/**
* #see http://stackoverflow.com/a/22423511/230513
* #see http://stackoverflow.com/a/12228640/230513
*/
public class ImageShuffle extends JPanel {
private List<Icon> list = new ArrayList<Icon>();
private List<JLabel> labels = new ArrayList<JLabel>();
private Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
public ImageShuffle() {
this.setLayout(new GridLayout(1, 0));
list.add(UIManager.getIcon("OptionPane.errorIcon"));
list.add(UIManager.getIcon("OptionPane.informationIcon"));
list.add(UIManager.getIcon("OptionPane.warningIcon"));
list.add(UIManager.getIcon("OptionPane.questionIcon"));
for (Icon icon : list) {
JLabel label = new JLabel(icon);
labels.add(label);
this.add(label);
}
timer.start();
}
private void update() {
Collections.shuffle(list);
int index = 0;
for (JLabel label : labels) {
label.setIcon(list.get(index++));
}
}
private void display() {
JFrame f = new JFrame("ImageShuffle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ImageShuffle().display();
}
});
}
}
one way of achieving your goal is setting a swing.Timer to notify its action listeners every 5 seconds, set your class to be the listener for the timer and implement the actionListener interface by having an actionPerformed method which will change all images using their setImage method. the code should look like this:
public class ImageGallery extends JFrame implements ActionListener {
Timer timer;
public ImageGallery() {
timer = new Timer(5000, this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == timer) {
for (int i=0; i<vectorOfImages.size(); i++) {
vectorOfImages.get(i).setImage(AnotherImage);
}
}
}
}