JPane inside JFrame - java

I'm trying to make simple app in Java but I have problem with inserting JPane (pasy) inside JFrame(frame). For now my output is two windows, one with resisor and second with combo boxes. Can you please explain me what am I doing wrong? I also tried frame.getContentPane().add(pasy); but it didn't work.
import java.awt.* ;
import java.awt.Color;
import java.awt.event.* ;
import java.awt.Frame ;
import java.awt.Graphics;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Map;
public class rezystorGUI extends JFrame implements ActionListener {
String kod="",kolor="",pasek1="BLACK",pasek2="WHITE",pasek3="VIOLET",pasek4="WHITE",pasek5="BLACK";
JComboBox p1, p2, p3, p4, p5;
JTextField wynik;
ResistorColorCode rcc;
WpiszWartosc wwart;
/** * Constructor for objects of class REZYSTORGUI */
rezystorGUI(){
setTitle("Odczytywanie paskow rezystora");
setSize(375,300);
setVisible(true);
addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
});
rcc = new ResistorColorCode();
makeGUI() ;
}
/** method */
void makeGUI() {
JFrame frame = new JFrame();
frame.setSize(375,300);
JPanel pasy = new JPanel();
pasy.setLayout(new GridLayout(3,3));
pasy.setSize(200,200);
String[]pasek = {"BLACK","BROWN","RED","ORANGE","YELLOW","GREEN","BLUE","VIOLET","GRAY","WHITE"};
String[]multi = {"BLACK","BROWN","RED","ORANGE","YELLOW","GREEN","BLUE","VIOLET"};
String[]tol = {"BROWN","RED","GREEN","BLUE","VIOLET","GRAY","GOLD","SILVER"};
pasy.add(p1 = new JComboBox<String>(pasek));
p1.addActionListener(this);
pasy.add(p2 = new JComboBox<String>(pasek));
p2.addActionListener(this);
pasy.add(p3 = new JComboBox<String>(pasek));
p3.addActionListener(this);
pasy.add(p4 = new JComboBox<String>(multi));
p4.addActionListener(this);
pasy.add(p5 = new JComboBox<String>(tol));
p5.addActionListener(this);
wynik= new JTextField(30);
pasy.add(wynik);
frame.add(pasy);
frame.pack();
frame.setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Map<String, Color> colors = new HashMap<String, Color>();
colors.put("BLUE", Color.BLUE);
colors.put("RED", Color.RED);
colors.put("GREEN", Color.GREEN);
colors.put("WHITE", Color.WHITE);
colors.put("YELLOW", Color.YELLOW);
colors.put("BLACK", Color.BLACK);
colors.put("ORANGE", Color.ORANGE);
colors.put("GRAY", Color.GRAY);
colors.put("VIOLET", new Color(127,0,255));
colors.put("BROWN", new Color(150,75,0));
colors.put("GOLD", new Color(255,215,0));
colors.put("SILVER", new Color(192,192,192));
colors.put("LIGHT-BLUE", new Color(153,204,255));
int x=100;
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 60, 10);
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 10, 50);
g.setColor(colors.get("LIGHT-BLUE"));
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get(pasek1));
x=x+20;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+10;
g.fillRect(x, 50, 95, 100);
g.setColor(colors.get(pasek2));
x=x+5;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek3));
x=x+30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek4));
x=x+30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+30;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get(pasek5));
x=x+10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x=x+10;
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get("GRAY"));
x=x+20;
g.fillRect(x, 95, 60, 10);
x=x+50;
g.setColor(colors.get("GRAY"));
g.fillRect(x, 95, 10, 50);
}
public void actionPerformed(ActionEvent e){
Object eventSource = e.getSource();
if (eventSource == p1){
pasek1 = (String)p1.getSelectedItem();
kod+=pasek1;
repaint();
}
if (eventSource == p2){
pasek2 = (String)p2.getSelectedItem();
kod+="-";
kod+=pasek2;
repaint();
}
if (eventSource == p3){
pasek3 = (String)p3.getSelectedItem();
kod+="-";
kod+=pasek3;
repaint();
}
if (eventSource == p4){
pasek4 = (String)p4.getSelectedItem();
kod+="-";
kod+=pasek4;
repaint();
}
if (eventSource == p5){
pasek5 = (String)p5.getSelectedItem();
String tempkod;
tempkod=kod;
kod+="-";
kod+=pasek5;
repaint();
rcc.inputColorCode(kod);
kod=tempkod;
wynik.setText(rcc.convertToValues()+" Ohm(s)\n"+rcc.tolerancja+" tolerancji");
}
}
public static void main(String[] args)
{
new rezystorGUI() ;
}
}

Your output is two JFrames because you're creating two JFrames. One is the class which extends JFrame:
public class rezystorGUI extends JFrame
and the other is the frame variable:
void makeGUI() {
JFrame frame = new JFrame();
Solution: don't do this, simple as that. Myself, I avoid extending JFrame, since for one it helps prevent me from doing bad things, like painting directly in the JFrame (like you're doing!).
Instead have your class extend JPanel, draw within its paintComponent method, just as the Swing painting tutorials recommend that you do, add all your components to it, and then when you need to display it in a stand alone GUI, create a JFrame, add your class to its contentPane, pack, and display the JFrame.
e.g.,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;
public class Resistor extends JPanel {
private String kod = "";
private String kolor = "";
private String pasek1 = "BLACK";
private String pasek2 = "WHITE";
private String pasek3 = "VIOLET";
private String pasek4 = "WHITE";
private String pasek5 = "BLACK";
private String[] paseks = {pasek1, pasek2, pasek3, pasek4, pasek5};
private JLabel imageLabel = new JLabel();
private List<JComboBox<String>> combos = new ArrayList<>();
private JTextField textField = new JTextField(10);
public Resistor() {
imageLabel.setIcon(createIcon());
String[] pasek = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET",
"GRAY", "WHITE" };
String[] multi = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET" };
String[] tol = { "BROWN", "RED", "GREEN", "BLUE", "VIOLET", "GRAY", "GOLD", "SILVER" };
String[][] comboModels = {pasek, pasek, pasek, multi, tol};
JPanel comboPanel = new JPanel(new GridLayout(2, 3));
for (int i = 0; i < comboModels.length; i++) {
JComboBox<String> combo = new JComboBox<>(comboModels[i]);
combo.addActionListener(new ComboListener());
comboPanel.add(combo);
combos.add(combo);
}
comboPanel.add(textField);
setLayout(new BorderLayout());
add(imageLabel, BorderLayout.CENTER);
add(comboPanel, BorderLayout.PAGE_END);
}
private Icon createIcon() {
String[] pasek = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET",
"GRAY", "WHITE" };
String[] multi = { "BLACK", "BROWN", "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "VIOLET" };
String[] tol = { "BROWN", "RED", "GREEN", "BLUE", "VIOLET", "GRAY", "GOLD", "SILVER" };
Map<String, Color> colors = new HashMap<String, Color>();
colors.put("BLUE", Color.BLUE);
colors.put("RED", Color.RED);
colors.put("GREEN", Color.GREEN);
colors.put("WHITE", Color.WHITE);
colors.put("YELLOW", Color.YELLOW);
colors.put("BLACK", Color.BLACK);
colors.put("ORANGE", Color.ORANGE);
colors.put("GRAY", Color.GRAY);
colors.put("VIOLET", new Color(127, 0, 255));
colors.put("BROWN", new Color(150, 75, 0));
colors.put("GOLD", new Color(255, 215, 0));
colors.put("SILVER", new Color(192, 192, 192));
colors.put("LIGHT-BLUE", new Color(153, 204, 255));
int w = 375;
int h = 200;
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
int x = 100;
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 60, 10);
g.setColor(colors.get("GRAY"));
g.fillRect(40, 95, 10, 50);
g.setColor(colors.get("LIGHT-BLUE"));
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get(pasek1));
x = x + 20;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 10;
g.fillRect(x, 50, 95, 100);
g.setColor(colors.get(pasek2));
x = x + 5;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek3));
x = x + 30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get(pasek4));
x = x + 30;
g.fillRect(x, 50, 10, 100);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 30;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get(pasek5));
x = x + 10;
g.fillRect(x, 40, 10, 120);
g.setColor(colors.get("LIGHT-BLUE"));
x = x + 10;
g.fillRect(x, 40, 20, 120);
g.setColor(colors.get("GRAY"));
x = x + 20;
g.fillRect(x, 95, 60, 10);
x = x + 50;
g.setColor(colors.get("GRAY"));
g.fillRect(x, 95, 10, 50);
g.dispose();
return new ImageIcon(img);
}
private class ComboListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO finish!
}
}
private static void createAndShowGui() {
Resistor mainPanel = new Resistor();
JFrame frame = new JFrame("Resistor");
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();
}
});
}
}
I also recommend that you spend some time on the non-GUI "model" side of things, for instance, that create a ColorCode class, or better, an enum, one that holds a Color field, a String text field, an int multiplier field (that holds multiples of 10), and perhaps a double tolerance field. Doing this would simplify much of your code and make debugging easier.

Related

Shapes are not drawn in real time

So, if I try to move the shape, it actually moves, but there is no motion animation. In order for the moved shape to be drawn, the application window must be minimized or maximized.
Here is the PentaminoShape class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class PentominoShape extends JFrame implements MouseListener, MouseMotionListener {
JPanel shapePane;
Container contentPane;
private Polygon currPolygon;
private int x, y;
ArrayList<Polygon> polygons = new ArrayList<Polygon>();
JFrame frame;
public PentominoShape(JFrame frame){
this.frame = frame;
initShape();
}
private void initShape() {
Polygon fig1 = new Polygon(new int[]{10, 50, 50, 10}, new int[]{10, 10, 200, 200}, 4);
Polygon fig2 = new Polygon(new int[]{130, 210, 210, 170, 170, 130, 130, 90, 90, 130}, new int[]{80, 80, 120, 120, 200, 200, 160, 160, 120, 120}, 10);
Polygon fig3 = new Polygon(new int[]{290, 330, 330, 250, 250, 290}, new int[]{50, 50, 200, 200, 160, 160}, 6);
Polygon fig4 = new Polygon(new int[]{10, 90, 90, 50, 50, 10}, new int[]{280, 280, 400, 400, 360, 360}, 6);
Polygon fig5 = new Polygon(new int[]{170, 210, 210, 170, 170, 130, 130, 170}, new int[]{240, 240, 360, 360, 400, 400, 320, 320}, 8);
Polygon fig6 = new Polygon(new int[]{250, 370, 370, 330, 330, 290, 290, 250}, new int[]{280, 280, 320, 320, 400, 400, 320, 320}, 8);
Polygon fig7 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 10}, new int[]{480, 480, 520, 520, 480, 480, 560, 560}, 8);
Polygon fig8 = new Polygon(new int[]{170, 250, 250, 290, 290, 170}, new int[]{520, 520, 440, 440, 560, 560}, 6);
Polygon fig9 = new Polygon(new int[]{330, 370, 370, 410, 410, 450, 450, 410, 410, 330}, new int[]{520, 520, 480, 480, 440, 440, 520, 520, 560, 560}, 10);
Polygon fig10 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 90, 90, 50, 50, 10}, new int[]{680, 680, 640, 640, 680, 680, 720, 720, 760, 760, 720, 720}, 12);
Polygon fig11 = new Polygon(new int[]{170, 210, 210, 250, 250, 210, 210, 170}, new int[]{640, 640, 600, 600, 760, 760, 680, 680}, 8);
Polygon fig12 = new Polygon(new int[]{330, 410, 410, 370, 370, 290, 290, 330}, new int[]{640, 640, 680, 680, 760, 760, 720, 720}, 8);
polygons.add(fig1);
polygons.add(fig2);
polygons.add(fig3);
polygons.add(fig4);
polygons.add(fig5);
polygons.add(fig6);
polygons.add(fig7);
polygons.add(fig8);
polygons.add(fig9);
polygons.add(fig10);
polygons.add(fig11);
polygons.add(fig12);
Color[] c = new Color[12];
c[0] = new Color(25, 165, 25);
c[1] = new Color(255, 165, 25);
c[2] = new Color(255, 50, 50);
c[3] = new Color(150, 45, 90);
c[4] = new Color(25, 165, 150);
c[5] = new Color(25, 165, 255);
c[6] = new Color(255, 40, 190);
c[7] = new Color(180, 90, 60);
c[8] = new Color(90, 80, 70);
c[9] = new Color(70, 80, 90);
c[10] = new Color(150, 30, 20);
c[11] = new Color(80, 80, 80);
shapePane = new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(c[0]); g2.fill(fig1);
g2.setColor(c[1]); g2.fill(fig2);
g2.setColor(c[2]); g2.fill(fig3);
g2.setColor(c[3]); g2.fill(fig4);
g2.setColor(c[4]); g2.fill(fig5);
g2.setColor(c[5]); g2.fill(fig6);
g2.setColor(c[6]); g2.fill(fig7);
g2.setColor(c[7]); g2.fill(fig8);
g2.setColor(c[8]); g2.fill(fig9);
g2.setColor(c[9]); g2.fill(fig10);
g2.setColor(c[10]); g2.fill(fig11);
g2.setColor(c[11]); g2.fill(fig12);
}
};
/*contentPane = this.getContentPane();
contentPane.add(shapePane);
this.pack();*/
frame.add(shapePane);
shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);
/*shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);*/
}
public void mousePressed(MouseEvent e) {
for(Polygon polygon: polygons) {
if (polygon.contains(e.getPoint())) {
System.out.println("Pressed");
currPolygon = polygon;
x = e.getX();
y = e.getY();
}
}
}
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint();
}
}catch (NullPointerException ex){
}
}
public void mouseReleased(MouseEvent e){
currPolygon = null;
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
}
And the main Pentamino class:
import javax.swing.*;
public class Pentomino extends JFrame {
JFrame frame;
PentominoShape shape;
PentominoPanel panel;
public Pentomino(){
initUI();
}
private void initUI(){
frame = new JFrame("Пентамино");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1500, 900);
setResizable(false);
shape = new PentominoShape(frame);
panel = new PentominoPanel(frame);
/*frame.add(shape);
frame.add(panel);*/
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
Pentomino game = new Pentomino();
}
}
I'm new to Java and I don't understand how to solve this problem. Tried searching the internet for a similar problem but couldn't find anything.
Your bug is here:
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint(); // ***** here ****
}
}catch (NullPointerException ex){
}
}
You're calling repaint() on the enclosing class, a JFrame, one that is never displayed, and this will have not have the effect desired.
In fact, ask yourself, why this...
public class PentominoShape extends JFrame // ...
Why is PentominoShape extending JFrame at all, when it isn't behaving as a JFrame, when it shouldn't be behaving as a JFrame?
Instead, call repaint on the JPanel that holds the shapes, the shapePane JPanel, and yes, get rid of catching the NullPointerException. That should never be in your code:
public void mouseDragged(MouseEvent e) {
if (currPolygon == null) {
return;
}
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
shapePane.repaint(); // now we're repainting the correct JPanel!
}
}
Side note: I'd clean things up a bit including
Not having any class extend JFrame if possible
Create my own polygon type of class:
public class PentominoShape2 {
private Polygon polygon;
private Color color;
public PentominoShape2(Polygon polygon, Color color) {
this.polygon = polygon;
this.color = color;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(color);
g2.fill(polygon);
}
public Polygon getPolygon() {
return polygon;
}
public Color getColor() {
return color;
}
public boolean contains(Point p) {
return polygon.contains(p);
}
}
and then in the drawing JPanel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (PentominoShape2 poly : polys) {
poly.draw(g);
}
}
same for the mouse listener

Objects disappear on resize and when the window is minimized

i need some help with this code.
I already have the functions of paint the objects and clear the objects from the window but how i can make that when i make a resize or when i minimize the windows the objects doesn't disappear?
This is the code i have at the moment:
public class miClass implements ActionListener{
JFrame ventana;
JPanel panel;
JButton p,c;
Graphics g;
Image img;
Font font1,font2,font3;
public miClass(){
ventana = new JFrame("Aplicacion.");
p = new JButton("P");
c = new JButton("C");
panel = new JPanel();
ventana.setLayout(null);
ventana.setBounds(100,100,600,600);
ventana.getContentPane().add(panel);
ventana.add(p);
p.addActionListener(this);
c.addActionListener(this);
p.setBounds(20,20,120,45);
ventana.add(c);
c.setBounds(200,20,120,45);
ventana.setFocusable(true);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
g = ventana.getGraphics();
Toolkit tool = Toolkit.getDefaultToolkit();
img = tool.getImage("prueba.png");
g.drawImage(img,0,100,null);
font1 = new Font("Helvetica",Font.PLAIN,22);
g.setFont(font1);
g.drawString("Hola", 100, 300);
font2 = new Font("TimesRoman",Font.BOLD,20);
g.setFont(font2);
g.drawString("Mundo", 100, 340);
font3 = new Font("Courier",Font.BOLD+Font.ITALIC,25);
g.setFont(font3);
g.drawString("WASAAAA!", 100, 400);
g.setColor(Color.green);
g.drawOval(300, 200, 150, 100);
g.setColor(Color.red);
g.drawArc(200, 400, 250, 64, 135, 46);
g.setColor(Color.blue);
g.drawLine(400, 200, 150, 100);
g.setColor(Color.magenta);
g.drawRect(300, 250, 160, 50);
g.setColor(Color.cyan);
g.fillRect(100,400,20,240);
g.setColor(Color.lightGray);
g.fillOval(100,340,14,30);
if(e.getSource() == c){ //Clean all objects on the window//
g.clearRect(0,100,900,800);
}
}
public static void main(String args[]){
miClass GUI = new miClass();
}
}
Your frame is reset to its initial state when it is resized, and your code only redraws it when a button is clicked, not when it is resized. The paintComponent method on any subclass of Component is called after the parent frame is resized, so you can fix this issue by overriding that method.
package SO;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class miClass implements ActionListener {
JFrame ventana;
JPanel panel;
JButton p, c;
Graphics g;
Image img;
Font font1, font2, font3;
public miClass() {
ventana = new JFrame("Aplicacion.");
p = new JButton("P");
c = new JButton("C");
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
// your stuff
font1 = new Font("Helvetica", Font.PLAIN, 22);
g.setFont(font1);
g.drawString("THIS GETS REDRAWN", 100, 300);
}
};
panel.setSize(400, 400);
ventana.setLayout(null);
ventana.setBounds(100, 100, 600, 600);
ventana.getContentPane().add(panel);
ventana.add(p);
p.addActionListener(this);
c.addActionListener(this);
p.setBounds(20, 20, 120, 45);
ventana.add(c);
c.setBounds(200, 20, 120, 45);
ventana.setFocusable(true);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
g = panel.getGraphics();
Toolkit tool = Toolkit.getDefaultToolkit();
img = tool.getImage("prueba.png");
g.drawImage(img, 0, 100, null);
font1 = new Font("Helvetica", Font.PLAIN, 22);
g.setFont(font1);
g.drawString("Hola", 100, 300);
font2 = new Font("TimesRoman", Font.BOLD, 20);
g.setFont(font2);
g.drawString("Mundo", 100, 340);
font3 = new Font("Courier", Font.BOLD + Font.ITALIC, 25);
g.setFont(font3);
g.drawString("WASAAAA!", 100, 400);
g.setColor(Color.green);
g.drawOval(300, 200, 150, 100);
g.setColor(Color.red);
g.drawArc(200, 400, 250, 64, 135, 46);
g.setColor(Color.blue);
g.drawLine(400, 200, 150, 100);
g.setColor(Color.magenta);
g.drawRect(300, 250, 160, 50);
g.setColor(Color.cyan);
g.fillRect(100, 400, 20, 240);
g.setColor(Color.lightGray);
g.fillOval(100, 340, 14, 30);
if (e.getSource() == c) { // Clean all objects on the window//
g.clearRect(0, 100, 900, 800);
}
}
public static void main(String args[]) {
miClass GUI = new miClass();
}
}

How to add a mouse hover listener to a rectangle in Java

I am trying to make a button using the Rectangle object and am also trying to make the color change on hover, and it will not change.
I have made my code have more generic names for variables that way it would not confuse, here it is:
public class MouseHandler extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if(mx > button.x && mx < button.x+button.width &&
my > button.y && my < button.y+button.height) {
buttonHover = true;
} else {
buttonHover = false;
}
}
}
And I tried calling these lines of code also, but it wouldn't work:
if(buttonHover)
g.setColor(hoverColor);
g.drawRect(button.x, button.y, button.width, button.height);
I will put my full code at the bottom, with the actual variable names. Thanks for the help!
package trivia;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Main extends JFrame{
boolean mainMenu = true;
boolean startHover;
static Color tan = Color.decode("#F4EBC3");
static Color darkGreen = Color.decode("#668284");
static Color buttonColor = Color.decode("#A2896B");
static Color borderColor = Color.decode("#333333");
static Color buttonHover = Color.decode("#F5B66E");
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle body = new Rectangle(0, 100, 500, 400);
Rectangle start = new Rectangle(150, 150, 200, 40);
Rectangle howToPlay = new Rectangle(150, 225, 200, 40);
Rectangle quit = new Rectangle(150, 300, 200, 40);
public Main() {
setTitle("Trivia Game!");
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
#Override
public void paint(Graphics g) {
Dimension d = this.getSize();
if(mainMenu = true){
g.setColor(darkGreen);
g.fillRect(header.x, header.y, header.width, header.height);
g.setFont(new Font("Courier", Font.BOLD, 24));
g.setColor(Color.BLACK);
drawCenteredString("Trivia Game!", d.width, 125, g);
g.setColor(tan);
g.fillRect(body.x, body.y, body.width, body.height);
g.setColor(buttonColor);
g.fillRect(start.x, start.y, start.width, start.height);
g.setColor(borderColor);
g.drawRect(start.x, start.y, start.width, start.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("Start", d.width, 340, g);
g.setColor(buttonColor);
g.fillRect(howToPlay.x, howToPlay.y, howToPlay.width, howToPlay.height);
g.setColor(borderColor);
g.drawRect(howToPlay.x, howToPlay.y, howToPlay.width, howToPlay.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("How To Play", d.width, 490, g);
g.setColor(buttonColor);
g.fillRect(quit.x, quit.y, quit.width, quit.height);
g.setColor(borderColor);
g.drawRect(quit.x, quit.y, quit.width, quit.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("Quit?", d.width, 640, g);
g.setColor(buttonColor);
g.fillRect(start.x, start.y, start.width, start.height);
g.setColor(borderColor);
g.drawRect(start.x, start.y, start.width, start.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("Start", d.width, 340, g);
if(startHover)
g.setColor(buttonHover);
g.drawRect(start.x, start.y, start.width, start.height);
}
}
public void drawCenteredString(String s, int w, int h, Graphics g) {
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(s)) / 2;
int y = (fm.getAscent() + (h- (fm.getAscent() + fm.getDescent())) / 2);
g.drawString(s, x, y);
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Main m = new Main();
}
public class MouseHandler extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if(mx > start.x && mx < start.x+start.width &&
my > start.y && my < start.y+start.height) {
startHover = true;
System.out.println("yes");
} else {
startHover = false;
System.out.println("no");
}
}
}
}
I'll start with...
1) If it truly just a rectangle you want to deal with. Please use https://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html , Java has been kind enough to make your life simple please don't throw it away. (ignore this keeping here for reference)
2) You should implement MouseMotionListener... I did it for you.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class test extends JFrame implements MouseMotionListener {
boolean mainMenu = true;
boolean startHover;
static Color tan = Color.decode("#F4EBC3");
static Color darkGreen = Color.decode("#668284");
static Color buttonColor = Color.decode("#A2896B");
static Color borderColor = Color.decode("#333333");
static Color buttonHover = Color.decode("#F5B66E");
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle body = new Rectangle(0, 100, 500, 400);
Rectangle start = new Rectangle(150, 150, 200, 40);
Rectangle howToPlay = new Rectangle(150, 225, 200, 40);
Rectangle quit = new Rectangle(150, 300, 200, 40);
public test() {
setTitle("Trivia Game!");
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
this.addMouseMotionListener(this);
}
#Override
public void paint(Graphics g) {
Dimension d = this.getSize();
if (mainMenu = true) {
g.setColor(darkGreen);
g.fillRect(header.x, header.y, header.width, header.height);
g.setFont(new Font("Courier", Font.BOLD, 24));
g.setColor(Color.BLACK);
drawCenteredString("Trivia Game!", d.width, 125, g);
g.setColor(tan);
g.fillRect(body.x, body.y, body.width, body.height);
g.setColor(buttonColor);
g.fillRect(start.x, start.y, start.width, start.height);
g.setColor(borderColor);
g.drawRect(start.x, start.y, start.width, start.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("Start", d.width, 340, g);
g.setColor(buttonColor);
g.fillRect(howToPlay.x, howToPlay.y, howToPlay.width,
howToPlay.height);
g.setColor(borderColor);
g.drawRect(howToPlay.x, howToPlay.y, howToPlay.width,
howToPlay.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("How To Play", d.width, 490, g);
g.setColor(buttonColor);
g.fillRect(quit.x, quit.y, quit.width, quit.height);
g.setColor(borderColor);
g.drawRect(quit.x, quit.y, quit.width, quit.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("Quit?", d.width, 640, g);
g.setColor(buttonColor);
g.fillRect(start.x, start.y, start.width, start.height);
g.setColor(borderColor);
g.drawRect(start.x, start.y, start.width, start.height);
g.setFont(new Font("Courier", Font.BOLD, 20));
g.setColor(Color.black);
drawCenteredString("Start", d.width, 340, g);
if (startHover)
g.setColor(buttonHover);
g.drawRect(start.x, start.y, start.width, start.height);
}
}
public void drawCenteredString(String s, int w, int h, Graphics g) {
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(s)) / 2;
int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2);
g.drawString(s, x, y);
}
public static void main(String[] args) {
#SuppressWarnings("unused")
test m = new test();
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("lol");
int mx = e.getX();
int my = e.getY();
if (mx > start.x && mx < start.x + start.width && my > start.y
&& my < start.y + start.height) {
startHover = true;
System.out.println("yes");
} else {
startHover = false;
System.out.println("no");
}
}
}
If you read below you can see there are a lot of things wrong with your code. Don't let that scare you from learning. Do it step by step and you will be fine.
You've several issues going on here:
You're doing drawing directly within a JFrame, a dangerous thing to do, since JFrames hold many components, several I'm sure that you're not familiar with, including borders, rootpane, glasspane, and contentpane, and if you mess up painting, it can mess up the drawing of these critical components.
Also by painting inside of a paint method, you loose all the advantages of Swing graphics.
Also you appear to have most of your program design and logic within a painting method, something that you should never do since you don't have full control over when or even if that method gets called.
Instead, you should create your button component in its own class, separate from the JFrame
Give your class ability to be placed in a JPanel
And give it a rollover capability.
For my money though, I'd just extend a JButton or better, just use a JButton, and make it look the way I want rather than trying to re-invent the wheel.
e.g.,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
#SuppressWarnings("serial")
public class Main2 extends JPanel {
private static final Color TAN = Color.decode("#F4EBC3");
private static final Color DARK_GREEN = Color.decode("#668284");
private static final Color BUTTON_COLOR = Color.decode("#A2896B");
private static final Color BORDER_COLOR = Color.decode("#333333");
private static final Color BUTTON_ROLLOVER_COLOR = Color.decode("#F5B66E");
private static final String TITLE = "Trivia Game!";
private static final Font TITLE_FONT = new Font("Courier", Font.BOLD, 24);
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W - 30;
private JButton startButton;
private JButton howToPlayButton;
private JButton quitButton;
public Main2() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(TITLE_FONT);
int blGap = 15;
titleLabel.setBorder(BorderFactory.createEmptyBorder(blGap, blGap, blGap, blGap));
JPanel titlePanel = new JPanel(new GridBagLayout());
titlePanel.setBackground(DARK_GREEN);
titlePanel.add(titleLabel);
JPanel centerInnerPanel = new JPanel(new GridLayout(0, 1, blGap, 2 * blGap));
centerInnerPanel.setOpaque(false);
centerInnerPanel.setBorder(BorderFactory.createEmptyBorder(blGap, blGap, blGap, blGap));
centerInnerPanel.add(startButton = createButton("Start"));
centerInnerPanel.add(howToPlayButton = createButton("How To Play"));
centerInnerPanel.add(quitButton = createButton("Quit?"));
JPanel centerOuterPanel = new JPanel(new GridBagLayout());
centerOuterPanel.setBackground(TAN);
centerOuterPanel.add(centerInnerPanel);
setLayout(new BorderLayout());
add(titlePanel, BorderLayout.PAGE_START);
add(centerOuterPanel, BorderLayout.CENTER);
}
private JButton createButton(String name) {
final JButton button = new JButton(name);
button.setFont(TITLE_FONT.deriveFont(20F));
button.setBackground(BUTTON_COLOR);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 25, 5, 25);
Border lineBorder = BorderFactory.createLineBorder(BORDER_COLOR);
Border nestedBorder = BorderFactory.createCompoundBorder(lineBorder, emptyBorder);
button.setBorder(nestedBorder);
button.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel)e.getSource();
if (model.isRollover()) {
button.setBackground(BUTTON_ROLLOVER_COLOR);
} else {
button.setBackground(BUTTON_COLOR);
}
}
});
return button;
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
int w = Math.max(super.getPreferredSize().width, PREF_W);
int h = Math.max(super.getPreferredSize().height, PREF_H);
return new Dimension(w, h);
}
private static void createAndShowGui() {
Main2 mainPanel = new Main2();
JFrame frame = new JFrame("Main2");
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();
}
});
}
}

How do you add graphics to a different panel in Java

import java.awt.event.ActionEvent; //this is my button class
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.Dimension;
public class Buttons extends JFrame{
private JPanel panel1, panel2;
private JButton button1, button2, button3;
private JMenuBar menuBar;
public Buttons()
{
createPanel();
addPanel();
}
private void createPanel()
{
setLocationRelativeTo(null);
panel1 = new JPanel();
panel1.setBackground(Color.cyan);
button1 = new JButton("Start");
button1.addActionListener(new addButtonListener());
button1.setBounds(50, 90, 190, 30);
button2 = new JButton("Instructions");
button2.setBounds(70, 130, 160, 30);
panel2 = new JPanel();
//button3 = new JButton("Test");
//panel2.setBackground(Color.orange);
//button3.setBounds(50, 50, 90, 30);
}
private void addPanel()
{
panel1.add(button1);
panel1.add(button2);
panel2.add(button3);
add(panel1);
}
class addButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
getContentPane().removeAll();
getContentPane().add(panel2);
repaint();
printAll(getGraphics());
}
}
public static void main(String[]args)
{
JMenuItem exitAction = new JMenuItem("Exit");
JMenuBar menuBar = new JMenuBar();
JMenu save = new JMenu("Save");
JMenu file = new JMenu("File");
JMenu credit = new JMenu("Credit");
file.add(exitAction);
menuBar.add(file);
menuBar.add(save);
menuBar.add(credit);
exitAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
Buttons frame = new Buttons();
frame.setTitle("Bikini Bottom Marathon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,500);
frame.setVisible(true);
frame.setJMenuBar(menuBar);
}
}
import javax.swing.*;
//this is my graphics class to create a board. the images are imported from saved
pictures in my class file. I'm trying to add the output from this code (the board)
onto the buttons class
import java.applet.*;
import java.awt.*;
import javax.imageio.*;
import java.net.*;
import java.io.*;
import java.awt.image.*;
import java.applet.*;
public class compscigame extends Applet
{
public void paint (Graphics page)
{
Image pineapple = getImage(getCodeBase(), "pineapple.jpg");
page.drawImage (pineapple, 50, 500, 50, 50, this);
Image raygun = getImage(getCodeBase(), "Raygun.jpg");
page.drawImage (raygun, 300, 350, 50, 50, this);
Image karen = getImage(getCodeBase(), "Karen.jpg");
page.drawImage(karen, 100, 50, 50, 50, this);
Image karensmad = getImage(getCodeBase(), "karensmad.jpg");
page.drawImage(karensmad, 150, 400, 50, 50, this);
Image rocketboots = getImage(getCodeBase(), "rocketboots.jpg");
page.drawImage(rocketboots, 200, 300, 50, 50, this);
Image emptybeaker = getImage(getCodeBase(), "emptybeaker.jpg");
page.drawImage(emptybeaker, 350, 150, 50, 50, this);
Image happykaren = getImage(getCodeBase(), "happykaren.jpg");
page.drawImage(happykaren, 100, 50, 50, 50, this);
Image raygunnotshooting = getImage(getCodeBase(), "raygunnotshooting.jpg");
page.drawImage (raygunnotshooting, 450, 200, 50, 50, this);
Image notfirerocket = getImage(getCodeBase(), "notfirerocket.jpg");
page.drawImage (notfirerocket, 450, 450, 50, 50, this);
Image firerocket = getImage(getCodeBase(), "firerocket.jpg");
page.drawImage (firerocket, 500, 200, 50, 50, this);
Image fullbeaker = getImage(getCodeBase(), "fullbeaker.jpg");
page.drawImage (fullbeaker, 250, 250, 50, 50, this);
Image boots = getImage(getCodeBase(), "boots.jpg");
page.drawImage (boots, 300, 500, 50, 50, this);
Image krustykrab = getImage(getCodeBase(), "krustykrab.jpg");
page.drawImage(krustykrab, 50, 50, 50, 50, this);
Board board = new Board(page, new Color (255,0,100));
setBackground(Color.YELLOW);
}
class Board
{
private Graphics g;
private Color col;
private Square [][] squares;
public Board (Graphics g, Color col)
{
this.col = col;
this.g = g;
Color temp;
squares = new Square[10][10];
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
int num;
if (i + j % 2 == 0)
temp = col;
else
temp = new Color(255, 0 , 255);
Square t;
t = new Square (g, temp, i, j);
if (j % 2 != 0)
{
num = 10 - i + 1 + 10 * (j - 1);
}
else
{
num = i + 10 * (j - 1);
}
t.setVal(num);
t.drawSquare();
squares[i - 1][j - 1] = t;
}
}
}
}
class Square
{
private Color col;
private int x;
private int y;
private Graphics g;
private int val;
public Square (Graphics g, Color col, int x, int y)
{
this.col = col;
this.g = g;
this.x = x;
this.y = y;
val = 0;
}
public void setVal(int num)
{
val = num;
}
public void drawSquare()
{
g.setColor(col);
g.drawRect(50 + (10 - x) * 50, 50 + (10 - y) * 50, 50, 50);
String str = "" + val;
g.drawString(str, 50 + (10 - x) * 50 + 5, 50 + (10 - y) * 50 + 10);
}
}
I just want the board to be in another panel. As you can see I used ActionListener to create the action my buttons will do. When you click Start it takes you to the button that says "test." I want the graphic from the Board to show on this second panel, (panel2)
}
Make a custom inner class that extends JPanel and then override the onPaintComponent method. Draw the Board there. Create a new BoardPanel instead of a JPanel.
Put your paint code in a seperate class (JPanel)
public void paint (Graphics page)
{
...
}
There is no need for the applet to have a dependency on any of this code.

Java battleship game starting point trouble

Im making a fully graphical battleship game that will eventually allow 2 players to play over a network, but im having trouble figuring out how to assign coordinates to each square on the grid, and how to let the players select where they want to place a ship. Ive made ships as .PNG's all being the corresponding length in pixels to match the 100x100 squares. (ie) carrier would take 5 squares. Lastly, can i make a small popup window that asks where the want to place a ship for each turn? The code i have is pretty small for now, Its just starting but i need a bit of help getting it going. Any help is appreciated.
package Battleshiponline;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
private Timer timer;
public Board() {
//addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLUE);
setDoubleBuffered(true);
timer = new Timer(5, this);
timer.start();
String[] rowA = new String[] {"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"};
String[] rowB = new String[] {"B1","B2","B3","B4","B5","B6","B7","B8","B9","B10"};
String[] rowC = new String[] {"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10"};
String[] rowD = new String[] {"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10"};
String[] rowE = new String[] {"E1","E2","E3","E4","E5","E6","E7","E8","E9","E10"};
String[] rowF = new String[] {"F1","F2","F3","F4","F5","F6","F7","F8","F9","F10"};
String[] rowG = new String[] {"G1","G2","G3","G4","G5","G6","G7","G8","G9","G10"};
String[] rowH = new String[] {"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10"};
String[] rowI = new String[] {"I1","I2","I3","I4","I5","I6","I7","I8","I9","I10"};
String[] rowJ = new String[] {"J1","J2","J3","J4","J5","J6","J7","J8","J9","J10"};
}
boolean inGame;
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
//vert lines(1-10)
g2d.drawLine(100, 1000, 100, 0);
g2d.drawLine(200, 1000, 200, 0);
g2d.drawLine(300, 1000, 300, 0);
g2d.drawLine(400, 1000, 400, 0);
g2d.drawLine(500, 1000, 500, 0);
g2d.drawLine(600, 1000, 600, 0);
g2d.drawLine(700, 1000, 700, 0);
g2d.drawLine(800, 1000, 800, 0);
g2d.drawLine(900, 1000, 900, 0);
g2d.drawLine(1000, 1000, 1000, 0);
// horizontal lines(A-J)
g2d.drawLine(0, 100, 1100,100);
g2d.drawLine(0, 200, 1100, 200);
g2d.drawLine(0, 300, 1100, 300);
g2d.drawLine(0, 400, 1100, 400);
g2d.drawLine(0, 500, 1100, 500);
g2d.drawLine(0, 600, 1100, 600);
g2d.drawLine(0, 700, 1100, 700);
g2d.drawLine(0, 800, 1100, 800);
g2d.drawLine(0, 900, 1100, 900);
Toolkit.getDefaultToolkit().sync();
}
public void actionPerformed(ActionEvent e) {
repaint();
}
/* private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
.keyPressed(e);
}
*/
Firstly, I would advise against making your grid squares 100x100 pixels, as that would result in a grid that is 1000 x 1000, which is too tall for many screens. For your gid, consider using a GridLayout which each cell a JButton. Here is a demo to see how it may look:
public class GridTest extends JPanel implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame("Grid Test");
frame.add(new GridTest());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void init() {
GridLayout layout = new GridLayout(10, 10);
setLayout(layout);
for (char row = 'A'; row <= 'J'; row++) {
for (int col = 1; col <= 10; col++) {
JButton button = new JButton("" + row + col);
button.setMargin(new Insets(0, 0, 0, 0));
button.setPreferredSize(new Dimension(50, 50));
button.addActionListener(this);
add(button);
}
}
}
public GridTest() {
init();
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, String.format("You pressed %s!", e.getActionCommand()),
"You Pressed a Button", JOptionPane.INFORMATION_MESSAGE);
((JButton) e.getSource()).setEnabled(false);
}
}
I would recommend looking up Swing and looking to all the components to get an understanding of what each can do. Oracle's Tutorial is a good place to start

Categories

Resources