I am trying to make a program that paints 16 rectangles in a windows. When you click on a rectangle with the mouse, it should disappear. The instructions tell me to create a class named Rektangel
with the variables x, y, b, h (length and width in Swedish). Then I should create 16 objects of the type Rectangel
and store them in a list.
I made three classes, named Panel14_1
, Frame14_1
and Rektangel
. I tried to pull the Panel into the frame but it doesn't work. When I run the program, it only opens a window and there are no red rectangles in it...
Frame
package ovning14__1;
public class Frame14__1 extends javax.swing.JFrame {
/**
* Creates new form Frame14__1
*/
public Frame14__1() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame14__1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new Frame14__1().setVisible(true);
});
}
// Variables declaration - do not modify
// End of variables declaration
}
Rektangel
package ovning14__1;
import java.awt.Color;
import java.awt.Graphics;
public class Rektangel {
private int x = 0;
private int y = 0;
private int b = 10;
private int h = 10;
public Rektangel(int x, int y, int h, int b) {
this.x = x;
this.y = y;
this.b = b;
this.h = h;
}
public void Rita(Graphics g){
g.setColor(Color.RED);
g.fillRect(x, y, b, h);
}
public boolean ärTräffad(int musX, int musY){
boolean träffad = false;
if (musX > x && musX < (x+h) && musY > y && musY < (y+b)) {
träffad = true;
}
return träffad;
}
}
Panel
package ovning14__1;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.ArrayList;
public class Panel14_1 extends javax.swing.JPanel {
private final ArrayList<Rektangel> rektanglar = new ArrayList<>();
private boolean speletÄrSlut = false;
public Panel14_1() {
initComponents();
for (int rad = 0; rad < 4; rad++){
for (int kolumn = 0; kolumn < 6; kolumn++){
int x = 10 + 50 * kolumn;
int y = 10 + 30 * rad;
int h = 30;
int b = 20;
Rektangel rektangel = new Rektangel(x, y, h, b);
rektanglar.add(rektangel);
}
}
}
@Override
protected void printComponent(Graphics g) {
super.printComponent(g);
for (int i = 0; i < rektanglar.size(); i++){
Rektangel rektangel = rektanglar.get(i);
rektangel.Rita(g);
}
if (speletÄrSlut) {
String text = "Grattis";
Font font = new Font (Font.SANS_SERIF, Font.PLAIN, 30);
g.setFont(font);
g.setColor(Color.BLUE);
int x = 25;
int y = 30;
g.drawString(text, x, y);
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
formMousePressed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
private void formMousePressed(java.awt.event.MouseEvent evt) {
boolean träff = false;
for (int i =0; i < rektanglar.size() && !träff; i++){
Rektangel rektangel = rektanglar.get(i);
if (rektangel.ärTräffad(evt.getX(), evt.getY())){
rektanglar.remove(i);
träff= true;
}
}
if(rektanglar.isEmpty()){
speletÄrSlut = true;
}
repaint();
}
}
// Variables declaration - do not modify
// End of variables declaration
Hello and welcome to stackoverflow:! :D
To paint a rectangle use Graphics.fillRect(x,y,w,h)
or for just the outline use Graphics.drawRect(x,y,w,h
.
If you want them to disappear, then you have to paint your JFrame if you click on a rectangle with the mouse. I would create a JButton and add an ActionListener.
Edit: Overwrite the paintComponent
method and not printComponent
The first thing you need to do is to add the JPanel
to the JFrame
by: add(new Panel14_1())
. There is no need to set a GroupLayout
to the JFrame
. The default ( BorderLayout
) will do the job. So
public class Frame14__1 extends javax.swing.JFrame {
public Frame14__1() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
add(new Panel14_1()); //add a panel to frame
pack();
}
public static void main(String args[]) {
..no change is needed
}
}
After implementing those changes you'll see the rectangles.
In Panel14_1
although overriding printComponent
should work you should override paintComponent
:
protected void paintComponent(Graphics g) { //not printComponent
super.paintComponent(g);
..no change in the following code
}
Rita(Graphics g)
should be rita(Graphics g)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.