JPanel drawn with extra width - java

I have a Stratego board being drawn on a JPanel, being used to set up the player's pieces. After two different instances of these panels are correctly arranged by the players, the main board (that has the same format and layout, just will have different piece appearance and logical behavior) will show.
My issue is that the second input panel and the main board (which currently has no functionality or pieces on it) are SOMETIMES set up with extra width on the bottom and the right, causing the 10x10 grid to not take up the entire board space like it should.
The initial input panel for player 1 seems to be working fine, never having this problem. The second panel and the main panel only SOMETIMES have this issue, so I'm not entirely sure where this is stemming from.
Here is the main method which sets up the panels and stuff.
public class Core {
public static void main(String[] args) {
LogicInterpreter logic = new LogicInterpreter();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
InputFrame inputPlayer1 = new InputFrame(logic, 1, "red", 600, 600);
inputPlayer1.setLocation(dim.width / 2 - inputPlayer1.getSize().width/2,
dim.height / 2 - inputPlayer1.getSize().height / 2);
while(!logic.isSetUp1()){
//Just to make it work
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Now bring up board 2
InputFrame inputPlayer2 = new InputFrame(logic, 2, "blue", 600, 600);
inputPlayer2.setLocation(dim.width / 2 - inputPlayer2.getSize().width/2,
dim.height / 2 - inputPlayer2.getSize().height / 2);
while(!logic.isSetUp2()){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
openBoards(logic);
}
public static void openBoards(LogicInterpreter logic) {
try {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
MainBoard board = new MainBoard(logic);
board.setLocation(dim.width / 2 - board.getSize().width / 2, dim.height / 2 - board.getSize().height / 2);
} catch (Exception e) {
System.exit(1);
}
}
}
Also, here is the code inside the input panels. I'm not sure what is relevant, so I can't take stuff out. Sorry. I will withhold the main board setup code because it is really the same.
public class InputFrame extends JFrame {
private static final long serialVersionUID = 1L;
private LogicInterpreter holder;
private Panel2 jp;
private int height, width;
private Map<Integer, ArrayList<Integer>> lakeCoords = new HashMap<>();
private List<Piece> pieces = new ArrayList<>();
private int playernumber;
private String playerColor;
Piece selectedPiece;
Piece secondSelectedPiece;
boolean hidePieces = false;
JButton submit = new JButton("SUBMIT");
public void addCoords() {
lakeCoords.put(3, new ArrayList<Integer>(Arrays.asList(6, 5)));
lakeCoords.put(4, new ArrayList<Integer>(Arrays.asList(6, 5)));
lakeCoords.put(7, new ArrayList<Integer>(Arrays.asList(6, 5)));
lakeCoords.put(8, new ArrayList<Integer>(Arrays.asList(6, 5)));
}
public void createPieces() {
int y = 1;
if (playernumber == 2) {
y = 7;
}
List<Integer> openValues = new ArrayList<>();
openValues.add(1);
openValues.add(2);
openValues.add(11);
openValues.add(12);
for (int x = 0; x < 2; x++) {
openValues.add(3);
}
for (int x = 0; x < 3; x++) {
openValues.add(4);
}
for (int x = 0; x < 4; x++) {
openValues.add(5);
openValues.add(6);
openValues.add(7);
}
for (int x = 0; x < 5; x++) {
openValues.add(8);
}
for (int x = 0; x < 8; x++) {
openValues.add(9);
}
for (int x = 0; x < 6; x++) {
openValues.add(10);
}
Collections.sort(openValues);
System.out.println(openValues.size());
System.out.println(pieces.size());
for (int x = 1; x <= 10; x++) {
for (int z = y; z <= y + 3; z++) {
// 1x1 Marshal
// 2x1 General
// 3x2 Colonel
// 4x3 Major
// 5x4 Captain
// 6x4 Lieutenant
// 7x4 Sergeant
// 8x5 Miner
// 9x8 Scout
// 10x6 Bomb
// 11x1 Flag
// 12x1 Spy
Piece piece = new Piece(new Coords(x, z), openValues.get(0), playerColor);
openValues.remove(0);
pieces.add(piece);
}
}
}
public InputFrame(LogicInterpreter holder, int playerNumber, String playerColor, int height, int width) {
this.height = height;
this.width = width;
playernumber = playerNumber;
this.playerColor = playerColor;
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
addCoords();
this.holder = holder;
createPieces();
jp = new Panel2(height, width);
setResizable(false);
jp.setBackground(new Color(235, 202, 158));
setTitle("Player " + playerNumber + " Arrangement GUI || Click Submit When Ready");
jp.setPreferredSize(new Dimension(600, 600));
jp.setLayout(null);
jp.addMouseListener(new HandleMouse());
if(playernumber == 1)
submit.setBounds(width / 10 * 4, height / 10 * 7, width / 10 * 2, height / 10 * 2);
else
submit.setBounds(width / 10 * 4, height / 10, width / 10 * 2, height / 10 * 2);
submit.setFont(new Font("Arial", Font.BOLD, width * 20 / 600));
submit.setBackground(Color.LIGHT_GRAY);
submit.addActionListener(new CloseListener(this));
jp.add(submit);
getContentPane().add(jp);
pack();
setVisible(true);
}
class CloseListener implements ActionListener {
private InputFrame frame;
public CloseListener(InputFrame frame) {
this.frame = frame;
}
public void actionPerformed(ActionEvent event) {
// Do the stuff here before closing
hidePieces = true;
repaint();
if (playernumber == 1) {
holder.setP1Pieces(pieces);
JOptionPane.showMessageDialog(null, "Press When Ready for Next Player");
holder.setSetUp1(true);
} else {
holder.setP2Pieces(pieces);
JOptionPane.showMessageDialog(null, "Press When Player 1 is Ready");
holder.setSetUp2(true);
}
frame.dispose();
}
}
public class Panel2 extends JPanel {
private static final long serialVersionUID = 1L;
int height = 0;
int width = 0;
public Panel2(int height, int width) {
this.height = height;
this.width = width;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int x = 0; x < width; x += width / 10) {
for (int y = 0; y < height; y += height / 10) {
boolean fill = false;
for (Entry<Integer, ArrayList<Integer>> coords : lakeCoords.entrySet()) {
if ((coords.getKey() - 1 == x / 60 && coords.getValue().get(0) - 1 == y / 60)
|| (coords.getKey() - 1 == x / 60 && coords.getValue().get(1) - 1 == y / 60)) {
fill = true;
break;
}
}
if (fill) {
g.setColor(Color.BLUE);
g.fillRect(x, y, width / 10, height / 10);
g.setColor(Color.BLACK);
g.drawRect(x, y, width / 10, height / 10);
} else {
g.setColor(Color.BLACK);
g.drawRect(x, y, width / 10, height / 10);
}
}
}
if(hidePieces){
for (Piece piece : pieces) {
try {
g.drawImage(ImageIO.read(new File(playerColor + "_pieces/" + (playerColor.equals("blue") ? "Blue" : "Red") + "_Strat_Piece"
+ ".png")), piece.getX() * width / 10 - width / 10,
piece.getY() * height / 10 - height / 10, width / 10, height / 10, null);
} catch(Exception e){}
}
} else {
for (Piece piece : pieces) {
g.drawImage(piece.getImage(), piece.getX() * width / 10 - width / 10,
piece.getY() * height / 10 - height / 10, width / 10, height / 10, null);
}
if (selectedPiece != null) {
g.setColor(Color.BLUE);
g.drawImage(selectedPiece.getImage(), selectedPiece.getX() * width / 10 - width / 10,
selectedPiece.getY() * height / 10 - height / 10, width / 10, height / 10, null);
g.drawRect(selectedPiece.getX() * width / 10 - width / 10,
selectedPiece.getY() * height / 10 - height / 10, width / 10, height / 10);
}
}
}
}
private class HandleMouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Coords coordinates = holder.getClickedBox(x, y, width, height);
boolean found = false;
boolean move = false;
for (Piece piece : pieces) {
if (piece.getX() == coordinates.getX() && piece.getY() == coordinates.getY()) {
found = true;
if (selectedPiece == null) {
selectedPiece = piece;
} else {
move = true;
secondSelectedPiece = piece;
}
}
}
if (move) {
pieces.remove(selectedPiece);
pieces.remove(secondSelectedPiece);
Coords storage = selectedPiece.getCoords();
selectedPiece.setCoords(secondSelectedPiece.getCoords());
secondSelectedPiece.setCoords(storage);
pieces.add(selectedPiece);
pieces.add(secondSelectedPiece);
selectedPiece = null;
secondSelectedPiece = null;
} else if (!found) {
if (selectedPiece != null) {
selectedPiece = null;
}
}
repaint();
}
}
}

Did you check how many pixels are "sometimes" added?
When i call setResizable(true) on my jframe, i notice that "sometimes" there are 10 pixels more, both in width and height, than i expect.
If this is your case, i answered a similar question here.
I was able to solve the problem using a 'trick', calling pack more than one time.
In the answer i also linked another similar question (this one), where i wasn't able to find another solution, but there some users described the bug.

Related

How to get multiple rectangles in one larger one

Im trying to display the maximum number of smaller rectangles that will fit into a larger one. I can get the horizontal rectangles to show up, but the vertical rectangles will not show up. I need help on figuring out how to get the vertical rectangles to display in the JFrame.
Here is the class with the main:
import javax.swing.*;
public class MyPanel extends JComponent {
public static void main(String[] arguments) {
LargeRec large = new LargeRec();
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Rectangle");
frame.setResizable(false);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(large);
}
}
This is the class for creating the rectangle's:
import javax.swing.*;
import java.awt.*;
public class LargeRec extends JComponent {
static int larX;
static int larY;
static int smaX;
static int smaY;
public static int getRandomIntRange(int min, int max) {
int x = (int) (Math.random() * ((max + 1 - min))) + min;
if (x > (max + 1))
x = max;
return x;
}
public void paint(Graphics g) {
larX = getRandomIntRange(100, 300);
larY = getRandomIntRange(100, 300);
while (larX == larY) {
larX = getRandomIntRange(100, 300);
larY = getRandomIntRange(100, 300);
}
while (larY > larX) {
larX = getRandomIntRange(100, 300);
larY = getRandomIntRange(100, 300);
}
smaX = getRandomIntRange(10, 50);
smaY = getRandomIntRange(10, 50);
while (smaX == smaY) {
smaX = getRandomIntRange(10, 50);
smaY = getRandomIntRange(10, 50);
}
while (smaY > smaX) {
smaX = getRandomIntRange(10, 50);
smaY = getRandomIntRange(10, 50);
}
g.drawRect(0, 0, larX, larY);
g.setColor(Color.black);
g.fillRect(0, 0, larX, larY);
int LX = larX;
int LY = larY;
int SX = smaX;
int SY = smaY;
for (int nx = 0; nx <= larX; nx = nx + smaX) {
while (LY >= SY) {
LY = LY - SY;
if(LX>=SX) {
g.setColor(Color.red);
g.drawRect(nx, LY, smaX, smaY);
}
}
LX = LX - SX;
LY = larY;
}
Graphics2D g2 = (Graphics2D) g;
for (int ny =LX; ny+smaY <=LX ; ny = ny + smaY) {
while (LY >= SX) {
g2.setColor(Color.blue);
g2.drawRect(ny, LY, smaY, smaX);
LY = LY - SX;
}
LY=larY;
}
}
}
It should output a black rectangle with smaller horizontal rectangles and vertical rectangles. It displays the horizontal (red) rectangles, but not the vertical(blue) rectangles.
Here is an example of a bad output:

There is some space at the end of the bar chart I've created using Graphics

I am trying to make a bar chart. Everything goes fine; the code compiles and runs successfully. But the frame (window) is not packed perfectly. There is some space at the end of the bar chart. I just want this space removed.
public class BarChart extends JPanel{
int[] percentage;
Color color;
double barOffset;
public BarChart(int[] percentage, Color color) {
this.color = color;
this.percentage = percentage;
}
public BarChart(int[] percentage) {
this.color = Color.black;
this.percentage = percentage;
}
public BarChart() {
this.color = Color.black;
}
int w = 1,h = 1;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
w = getWidth();
h = getHeight();
g.setColor(color);
barOffset = w*0.05;
int barWidth = (int)(w*0.1);
for(int i = 0; i<percentage.length; i++) {
g.fillRect((int)(barOffset),(int)(h*0.95-2*percentage[i]), barWidth, 2*percentage[i]);
if(i < percentage.length-1)
barOffset = (i+2)*w*0.05 + (i+1)*(barWidth);
}
}
}
This was not a packing error, but rather you were drawing off the edge of the component. To check for packing errors, set a background color for the container that is distinct from the component color.
For the set int[] p = new int[]{100, 5, 6, 9, 1, 0, 5, 100};, your bars are being drawn as follows:
component dimensions: width=104 height=10
bar[0]: xLeft=5 yTop=-190 barWidth=10 barHeight=200
bar[1]: xLeft=20 yTop=0 barWidth=10 barHeight=10
bar[2]: xLeft=35 yTop=-2 barWidth=10 barHeight=12
bar[3]: xLeft=50 yTop=-8 barWidth=10 barHeight=18
bar[4]: xLeft=66 yTop=7 barWidth=10 barHeight=2
bar[5]: xLeft=81 yTop=9 barWidth=10 barHeight=0
bar[6]: xLeft=96 yTop=0 barWidth=10 barHeight=10
bar[7]: xLeft=111 yTop=-190 barWidth=10 barHeight=200
I think this produces what you're looking for. Drawing components can be tricky, and the way I mitigate the complexity is to keep track of my screen locations semantically.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BarChart extends JPanel
{
public static void main(String[] args)
{
int[] p = new int[]{100, 5, 6, 9, 1, 0, 5, 100};
JFrame f = new JFrame();
f.setBackground(Color.BLUE);
BarChart chart = new BarChart(p);
chart.setBackground(Color.RED);
f.add(chart);
f.pack();
f.show();
}
private int[] percentage;
private Color color;
private boolean padEnds = true;
public BarChart(int[] percentage, Color color)
{
this.percentage = percentage;
this.color = color;
return;
}
public BarChart(int[] percentage)
{
this(percentage, Color.BLACK);
return;
}
public BarChart()
{
this(new int[0]);
return;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(this.color);
int width = super.getWidth();
int height = super.getHeight();
int topPadding = Math.round(height * 0.05f);
int barCount = this.percentage.length;
int barOffset = Math.round(width * 0.025f); // 2.5% (in pixels) reserved space on both sides of each bar == 5% between bars
int totalOffsetWidth = (barOffset * 2) * barCount;
if (!this.padEnds)
{
totalOffsetWidth -= (barOffset * 2);
}
int availableWidth = width - totalOffsetWidth;
int availableHeight = height - topPadding;
int barWidth = (int) Math.floor((float) availableWidth / (float) barCount);
int xLeft = 0;
for (int i = 0; i < barCount; i++)
{
int percent = this.percentage[i];
if (this.padEnds || (i != 0))
{
xLeft += barOffset; // Add offset here to pad left side of each bar.
}
int barHeight = Math.round(((float) availableHeight) * ((float) percent / 100f));
int yTop = topPadding + (availableHeight - barHeight);
g.fillRect(xLeft, yTop, barWidth, barHeight);
xLeft += barWidth; // advance the next drawing position
if (this.padEnds || (i != (barCount - 1)))
{
xLeft += barOffset; // Add offset here to pad right side of each bar.
}
}
return;
}
}

Image with all colors

I'm trying to write an algorithm to satisfy this challenge. I've double, triple, and quadruple checked my logic, but I think I'm missing something obvious. This program should group each color next to similar colors, but it produces something more akin to noise.
This is sort of what I expect (taken from a similar answer):
And this is what I'm actually getting:
public class AllColors extends JFrame {
private static final int WIDTH = 256;
private static final int HEIGHT = 128;
private static long TOTAL_ITERATIONS = (WIDTH * HEIGHT) * 185000;
private static int VALUES_PER_CHANNEL =32;
private static int CHANNEL_DELTA = 256/VALUES_PER_CHANNEL;
static BufferedImage image;
private static final int SCALE = 5;
static int[][] kernel = { { 0, 0, 1, 0, 0 },
{ 0, 2, 3, 2, 0 },
{ 1, 3, 0, 3, 1 },
{ 0, 2, 3, 2, 0 },
{ 0, 0, 1, 0, 0 } };
public static void main(String[] args) {
AllColors f = new AllColors();
f.setTitle("All Colors");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
image = new BufferedImage(WIDTH * SCALE, HEIGHT * SCALE, BufferedImage.TYPE_3BYTE_BGR);
init();
//gui stuff
JPanel p = new JPanel(){
#Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.scale(SCALE, SCALE);
g2.drawImage(image, 0, 0, null);
}
};
p.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
f.add(p);
f.pack();
f.setVisible(true);
group(p);
}
//makes an image of all colors
private static void init() {
int x = 0;
int y = 0;
for(int r = 0; r < VALUES_PER_CHANNEL; r+= 1){
for(int g = 0; g < VALUES_PER_CHANNEL; g+= 1){
for(int b = 0; b < VALUES_PER_CHANNEL; b+= 1){
x++;
if(x % WIDTH == 0){
y++;
x = 0;
}
if(y >= HEIGHT)
return;
image.setRGB(x, y, new Color(r*CHANNEL_DELTA,g*CHANNEL_DELTA,b*CHANNEL_DELTA).getRGB());
}
}
}
}
//group together similar pixels
private static void group(JPanel panel){
Random rand = new Random();
for(long i = 0; i < TOTAL_ITERATIONS; i++){
Point first = new Point(rand.nextInt(WIDTH), rand.nextInt(HEIGHT));
Point second = new Point(rand.nextInt(WIDTH), rand.nextInt(HEIGHT));
trySwitch(first, second);
if(i % (WIDTH * HEIGHT) == 0){
System.out.println(i / (WIDTH * HEIGHT));
panel.repaint();
}
}
}
private static void swap(Point first, Point second){
int temp = image.getRGB(second.x, second.y);
image.setRGB(second.x, second.y, image.getRGB(first.x, first.y));
image.setRGB(first.x, first.y, temp);
}
//get how similar the neighbors are
private static int getNeighborDelta(int imageX, int imageY){
Color center = new Color(image.getRGB(imageX, imageY));
int sum = 0;
for (int x = 0; x < kernel[0].length; x++)
{
for (int y = 0; y < kernel.length; y++)
{
int weight = kernel[x][y];
if (weight <= 0)
{
continue;
}
int xOffset = x - (kernel[0].length / 2);
int yOffset = y - (kernel.length / 2);
try{
sum += getDistance(new Color(image.getRGB(imageX + xOffset, imageY + yOffset)), center) * weight;
}catch(ArrayIndexOutOfBoundsException e){
//if out of image
}
}
}
return sum;
}
//switches if the neighbors will be more similar
private static void trySwitch(Point first, Point second){
double firstDistance = getNeighborDelta(first.x, first.y);
swap(first, second);
double secondDistance = getNeighborDelta(first.x, first.y);
if(secondDistance > firstDistance)
swap(first, second);
}
//get similarity between colors
private static double getDistance(Color one, Color two){
int r = Math.abs(two.getRed() - one.getRed());
int g = Math.abs(two.getGreen() - one.getGreen());
int b = Math.abs(two.getBlue() - one.getBlue());
return r + g + b;
}
}

How can I let JToolBars wrap to the next line (FlowLayout) without them being hidden ty the JPanel below them?

I am in the process of making a GUI which shows three JToolBars above a big JPanel. These toolbars are collectively very large, so I'm using a FlowLayout to make them wrap to the next line if they reach the JFrame border. The problem is that when they wrap to the next line, they become hidden by the JPanel below.. I wish I could force the JPanel containing the toolbars to grow enough to show all toolbars..
Is there a way to do this? Or is there another way to make these toolbars visible?
I have run into this problem before. I found the best solution is to use a modified version of FlowLayout that takes into account vertical changes and wraps them to the next line. Here is the code for such a layout.
import java.awt.*;
/**
* A modified version of FlowLayout that allows containers using this
* Layout to behave in a reasonable manner when placed inside a
* JScrollPane
* #author Babu Kalakrishnan
* Modifications by greearb and jzd
*/
public class ModifiedFlowLayout extends FlowLayout {
public ModifiedFlowLayout() {
super();
}
public ModifiedFlowLayout(int align) {
super(align);
}
public ModifiedFlowLayout(int align, int hgap, int vgap) {
super(align, hgap, vgap);
}
public Dimension minimumLayoutSize(Container target) {
// Size of largest component, so we can resize it in
// either direction with something like a split-pane.
return computeMinSize(target);
}
public Dimension preferredLayoutSize(Container target) {
return computeSize(target);
}
private Dimension computeSize(Container target) {
synchronized (target.getTreeLock()) {
int hgap = getHgap();
int vgap = getVgap();
int w = target.getWidth();
// Let this behave like a regular FlowLayout (single row)
// if the container hasn't been assigned any size yet
if (w == 0) {
w = Integer.MAX_VALUE;
}
Insets insets = target.getInsets();
if (insets == null){
insets = new Insets(0, 0, 0, 0);
}
int reqdWidth = 0;
int maxwidth = w - (insets.left + insets.right + hgap * 2);
int n = target.getComponentCount();
int x = 0;
int y = insets.top + vgap; // FlowLayout starts by adding vgap, so do that here too.
int rowHeight = 0;
for (int i = 0; i < n; i++) {
Component c = target.getComponent(i);
if (c.isVisible()) {
Dimension d = c.getPreferredSize();
if ((x == 0) || ((x + d.width) <= maxwidth)) {
// fits in current row.
if (x > 0) {
x += hgap;
}
x += d.width;
rowHeight = Math.max(rowHeight, d.height);
}
else {
// Start of new row
x = d.width;
y += vgap + rowHeight;
rowHeight = d.height;
}
reqdWidth = Math.max(reqdWidth, x);
}
}
y += rowHeight;
y += insets.bottom;
return new Dimension(reqdWidth+insets.left+insets.right, y);
}
}
private Dimension computeMinSize(Container target) {
synchronized (target.getTreeLock()) {
int minx = Integer.MAX_VALUE;
int miny = Integer.MIN_VALUE;
boolean found_one = false;
int n = target.getComponentCount();
for (int i = 0; i < n; i++) {
Component c = target.getComponent(i);
if (c.isVisible()) {
found_one = true;
Dimension d = c.getPreferredSize();
minx = Math.min(minx, d.width);
miny = Math.min(miny, d.height);
}
}
if (found_one) {
return new Dimension(minx, miny);
}
return new Dimension(0, 0);
}
}
}
Take a look at WrapLayout. It worked for me. Here is the code.

How to delete object with a mouse click?

I made a simple FlowChat Editor that creates rectangles and triangles and connects them to each other and shows the way from up to down. I can move this elements on screen too.
I am now trying to create a button to delete the element which I clicked. There is problem that I can delete MyTriangle objects, but I can't delete MyRectangle objects. It deletes but not object which I clicked. I delete from first object to last.
Here is my code:
if (deleteObj) {
if (rectsList.size() != 0) {
for (int i = 0; i < rectsList.size(); i++) {
MyRect rect = (MyRect) rectsList.get(i);
if (e.getX() <= rect.c.x + 50 && e.getX() >= rect.c.x - 50
&& e.getY() <= rect.c.y + 15 && e.getY() >= rect.c.y - 15) {
rectsList.remove(rect);
System.out.println("This is REctangle DELETED\n");
}
}
}
if (triangleList.size() != 0) {
for (int j = 0; j < triangleList.size(); j++) {
MyTriangle trian = (MyTriangle) triangleList.get(j);
if (e.getX() <= trian.c.x + 20 && e.getX() >= trian.c.x - 20
&& e.getY() <= trian.c.y + 20 && e.getY() >= trian.c.y - 20) {
triangleList.remove(trian);
System.out.println("This is Triangle Deleted\n");
}
}
}
Edit Here MyRectangle and MyTriangle classes
public class MyRect extends Ellipse2D.Double {
Point c;
Point in;
Point out;
int posX;
int posY;
int width = 100;
int height = 30;
int count;
public MyRect(Point center, Point input, Point output,int counter) {
c = center;
in = input;
out = output;
count=counter;
}
void drawMe(Graphics g) {
// in.x=c.x+20;
int posX = c.x;
int posY = c.y;
int posInX = in.x;
int posInY = in.y;
int posOutX = out.x;
int posOutY = out.y;
g.setColor(Color.MAGENTA);
g.drawString(" S "+count ,posX-5, posY+5);
g.setColor(Color.black);
g.drawRect(posX-50, posY-15, width, height);
g.setColor(Color.green);
g.drawRect(posInX-3, posInY-9, 6, 6);
g.setColor(Color.blue);
g.drawRect(posOutX-3, posOutY+3, 6, 6);
}
}
public class MyTriangle {
Point c;
Point in ;
Point outYES ;
Point outNO ;
int posX;
int posY;
int count;
public MyTriangle(Point center,Point input,Point outputYES,Point outputNO,int counter) {
c = center;
in = input;
outYES = outputYES;
outNO = outputNO;
count=counter;
}
void drawMe(Graphics g) {
int posX = c.x;
int posY = c.y;
int posInX=in.x;
int posInY=in.y;
int posOutYESX=outYES.x;
int posOutYESY=outYES.y;
int posOutNOX=outNO.x;
int posOutNOY=outNO.y;
int[] xPoints = {posX - 50, posX, posX + 50, posX};
int[] yPoints = {posY, posY - 30, posY, posY + 30};
g.setColor(Color.MAGENTA);
g.drawString(" T "+count,posX-5, posY+5);
g.setColor(Color.black);
g.drawPolygon(xPoints, yPoints, 4);
// draw input
g.setColor(Color.green);
g.drawRect(posInX-3,posInY-9, 6, 6);
g.setColor(Color.blue);
g.drawRect(posOutYESX-9,posOutYESY-3 , 6, 6);
g.setColor(Color.red);
g.drawRect(posOutNOX-3,posOutNOY+3 , 6, 6);
}
}
Edit 2
Here my funcs to add object to list.Is there could be ant mistake?Because I am her ceratıng new object of that calss and I am addıng that object to rectlist or trianglelist..
public void initRect(Point c, Point in, Point out) {
sCounter++;
MyRect myrects = new MyRect(c, in, out, sCounter);
rectsList.add(myrects);
s_And_t_List.add(myrects);
objectCounter.add("S " + sCounter);
selectablePanel.repaint();
}
public void initTriangle(Point c, Point in, Point outYES, Point outNO) {
tCounter++;
MyTriangle mytriangles = new MyTriangle(c, in, outYES, outNO, tCounter);
triangleList.add(mytriangles);
s_And_t_List.add(mytriangles);
objectCounter.add("T " + tCounter);
selectablePanel.repaint();
}
It seems like your logic is wrong. In your Rectangle class why not make a method returning a boolean that tests if a given set of coordinates is contained in your object. For example:
public boolean contains(int x, int y){
if(x_starting_point <= x && x <= x_starting_point+width
&& y_starting_point <= y && y <= y_starting_point+height)
return true;
return false;
}

Categories

Resources