Search Results

Search found 82 results on 4 pages for 'paintcomponent'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Adding a JPanel to another JPanel having TableLayout

    - by user253530
    I am trying to develop a map editor in java. My map window receives as a constructor a Map object. From that map object i am able to retrieve the Grid and every item in the grid along with other getters and setters. The problem is that even though the Mapping extends JComponent, when I place it in a panel it is not painted. I have overridden the paint method to satisfy my needs. Here is the code, maybe you could help me. public class MapTest extends JFrame implements ActionListener { private JPanel mainPanel; private JPanel mapPanel; private JPanel minimapPanel; private JPanel relationPanel; private TableLayout tableLayout; private JPanel tile; MapTest(Map map) { mainPanel = (JPanel) getContentPane(); mapPanel = new JPanel(); populateMapPanel(map); mainPanel.add(mapPanel); this.setPreferredSize(new Dimension(800, 600)); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } private double[][] generateTableLayoutSize(int x, int y, int size) { double panelSize[][] = new double[x][y]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { panelSize[i][j] = size; } } return panelSize; } private void populateMapPanel(Map map) { double[][] layoutSize = generateTableLayoutSize(map.getMapGrid().getRows(), map.getMapGrid().getColumns(), 50); tableLayout = new TableLayout(layoutSize); for(int i = 0; i < map.getMapGrid().getRows(); i++) { for(int j = 0; j < map.getMapGrid().getColumns(); j++) { tile = new JPanel(); tile.setName(String.valueOf(((Mapping)map.getMapGrid().getItem(i, j)).getCharacter())); tile.add(map.getMapItem(i, j)); String constraint = i + "," + j; mapPanel.add(tile, constraint); } } mapPanel.validate(); mapPanel.repaint(); } public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } } My Mapping Class public class Mapping extends JComponent implements Serializable{ private BufferedImage image; private Character character; //default public Mapping() { super(); this.image = null; this.character = '\u0000'; } //Mapping from image and char public Mapping(BufferedImage image, char character) { super(); this.image = image; this.character = character; } //Mapping from file and char public Mapping(File file, char character) { try { this.image = ImageIO.read(file); this.character = character; } catch (IOException ex) { System.out.println(ex); } } public char getCharacter() { return character; } public void setCharacter(char character) { this.character = character; } public BufferedImage getImage() { return image; } public void setImage(BufferedImage image) { this.image = image; repaint(); } @Override /*Two mappings are consider the same if -they have the same image OR -they have the same character OR -both of the above*/ public boolean equals(Object mapping) { if (this == mapping) { return true; } if (mapping instanceof Mapping) { return true; } //WARNING! equals might not work for images return (this.getImage()).equals(((Mapping) mapping).getImage()) || (this.getCharacter()) == (((Mapping) mapping).getCharacter()); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); //g.drawImage(image, 0, 0, null); g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null); } // @Override // public Dimension getPreferredSize() { // if (image == null) { // return new Dimension(10, 10); //instead of 100,100 set any prefered dimentions // } else { // return new Dimension(100, 100);//(image.getWidth(null), image.getHeight(null)); // } // } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { character = (Character) in.readObject(); image = ImageIO.read(ImageIO.createImageInputStream(in)); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeObject(character); ImageWriter writer = (ImageWriter) ImageIO.getImageWritersBySuffix("jpg").next(); writer.setOutput(ImageIO.createImageOutputStream(out)); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(0.85f); writer.write(null, new IIOImage(image, null, null), param); } }

    Read the article

  • JAVA: How to use paint() method to update the previously drawn object?

    - by GamDroid
    How to use paint() such that when repaint() is called the previously drawn object should not get deleted when drawing the new object. That is the drawing area must get UPDATED only and not REDRAWN. In my code when one of many button is clicked, some aplhabet get displayed. I want to have functionality such that when other buttons are clicked the previously drawn alhabets must be present.Take is as if a string of alphabets getting created as the buttons are clicked. Im using Java Swing for coding. Some piece of my code: if(source == btnAlpha[i] ) bollyDraw.repaint(); //bollydraw is an object of a JPanel extended class having implemented the paintComponent(Graphics g) method In the paint() method: if (word[i] == key) { g.drawChars(word, i, 1, x, y); }

    Read the article

  • Why cant i draw an elipse in with code?

    - by bvivek88
    package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import javax.swing.*; public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; Color color; Point start=new Point(); Point end =new Point(); JButton elipse=new JButton("Elipse"); JButton rectangle=new JButton("Rectangle"); JButton line=new JButton("Line"); String selected; public test_bmp() { color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { //super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } if(selected=="line") g2.drawLine(start.x,start.y,end.x,end.y); } //Draw on Buffered image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); System.out.println("draw"); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } repaint(); g2.dispose(); } public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setBackground(color.lightGray); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener(this); buttonpanel.add(elipse); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(rectangle); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(line); return buttonpanel; } public static void main(String args[]) { test_bmp application=new test_bmp(); //Main window JFrame frame=new JFrame("Whiteboard"); frame.setLayout(new BorderLayout()); frame.add(application.addButtons(),BorderLayout.WEST); frame.add(application); //size of the window frame.setSize(600,400); frame.setLocation(0,0); frame.setVisible(true); int w = frame.getWidth(); int h = frame.getHeight(); image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent event) { start = event.getPoint(); } @Override public void mouseReleased(MouseEvent event) { end = event.getPoint(); draw(); } @Override public void mouseDragged(MouseEvent e) { end=e.getPoint(); repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; draw(); } } I need to create a paint application, when i draw elipse by dragging mouse from left to right it displays nothing, why?? should i use any other function here?

    Read the article

  • How to center align background image in JPanel

    - by Jaguar
    I wanted to add background image to my JFrame. Background image means I can later add Components on the JFrame or JPanel Although I coudn't find how to add background image to a JFrame, I found out how to add background image to a JPanel from here: How to set background image in Java? This solved my problem, but now since my JFrame is resizable I want to keep the image in center. The code I found uses this method public void paintComponent(Graphics g) { //Draw the previously loaded image to Component. g.drawImage(img, 0, 0, null); //Draw image } Can anyone say how to align the image to center of the JPanel. As g.drawImage(img, 0, 0, null); provides x=0 and y=0 Also if there is a method to add background image to a JFrame then I would like to know. Thanks.

    Read the article

  • Why do I get a nullpointerexception at line ds.getPort in class L1?

    - by Fred
    import java.awt.; import java.awt.event.; import javax.swing.; import java.io.; import java.net.; import java.util.; public class Draw extends JFrame { /* * Socket stuff */ static String host; static int port; static int localport; DatagramSocket ds; Socket socket; Draw d; Paper p = new Paper(ds); public Draw(int localport, String host, int port) { d = this; this.localport = localport; this.host = host; this.port = port; try { ds = new DatagramSocket(localport); InetAddress ia = InetAddress.getByName(host); System.out.println("Attempting to connect DatagramSocket. Local port " + localport + " , foreign host " + host + ", foreign port " + port + "..."); ds.connect(ia, port); System.out.println("Success, ds.localport: " + ds.getLocalPort() + ", ds.port: " + ds.getPort() + ", address: " + ds.getInetAddress()); Reciever r = new Reciever(ds); r.start(); } catch (Exception e) { e.printStackTrace(); } setDefaultCloseOperation(EXIT_ON_CLOSE); getContentPane().add(p, BorderLayout.CENTER); setSize(640, 480); setVisible(true); } public static void main(String[] args) { int x = 0; for (String s : args){ if (x==0){ localport = Integer.parseInt(s); x++; } else if (x==1){ host = s; x++; } else if (x==2){ port = Integer.parseInt(s); } } Draw d = new Draw(localport, host, port); } } class Paper extends JPanel { DatagramSocket ds; private HashSet hs = new HashSet(); public Paper(DatagramSocket ds) { this.ds=ds; setBackground(Color.white); addMouseListener(new L1(ds)); addMouseMotionListener(new L2()); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); Iterator i = hs.iterator(); while(i.hasNext()) { Point p = (Point)i.next(); g.fillOval(p.x, p.y, 2, 2); } } private void addPoint(Point p) { hs.add(p); repaint(); } class L1 extends MouseAdapter { DatagramSocket ds; public L1(DatagramSocket ds){ this.ds=ds; } public void mousePressed(MouseEvent me) { addPoint(me.getPoint()); Point p = me.getPoint(); String message = Integer.toString(p.x) + " " + Integer.toString(p.y); System.out.println(message); try{ byte[] data = message.getBytes("UTF-8"); //InetAddress ia = InetAddress.getByName(ds.host); String convertedMessage = new String(data, "UTF-8"); System.out.println("The converted string is " + convertedMessage); DatagramPacket dp = new DatagramPacket(data, data.length); System.out.println(ds.getPort()); //System.out.println(message); //System.out.println(ds.toString()); //ds.send(dp); /*System.out.println("2Sending a packet containing data: " +data +" to " + ia + ":" + d.port + "...");*/ } catch (Exception e){ e.printStackTrace(); } } } class L2 extends MouseMotionAdapter { public void mouseDragged(MouseEvent me) { addPoint(me.getPoint()); Point p = me.getPoint(); String message = Integer.toString(p.x) + " " + Integer.toString(p.y); //System.out.println(message); } } } class Reciever extends Thread{ DatagramSocket ds; byte[] buffer; Reciever(DatagramSocket ds){ this.ds = ds; buffer = new byte[65507]; } public void run(){ try { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while(true){ try { ds.receive(packet); String s = new String(packet.getData()); System.out.println(s); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } }

    Read the article

  • Trouble adding Image to a JPanel

    - by user1276078
    I'm making a video game, and I need to add an image to a JPanel and then add that JPanel to a JFrame. All of the tutorials I've seen say to add it to a JLabel, but the image needs to be able to move around. Unless you can move a JLabel around, I can't do that. How would I be able to add an Image directly to a JPanel. This is what I have so far, but it is just like it was on a JApplet class Penguin extends JPanel { public Image image; public void paintComponent( Graphics g ) { image = getImage( getDocumentBase(), "Penguins.jpg" ); g.drawImage( image, 0, 0, this ); } }

    Read the article

  • How can I rotate an image using Java/Swing and then set its origin to 0,0?

    - by JT
    I'm able to rotate an image that has been added to a JLabel. The only problem is that if the height and width are not equal, the rotated image will no longer appear at the JLabel's origin (0,0). Here's what I'm doing. I've also tried using AffineTransform and rotating the image itself, but with the same results. Graphics2D g2d = (Graphics2D)g; g2d.rotate(Math.toRadians(90), image.getWidth()/2, image.getHeight()/2); super.paintComponent(g2d); If I have an image whose width is greater than its height, rotating that image using this method and then painting it will result in the image being painted vertically above the point 0,0, and horizontally to the right of the point 0,0.

    Read the article

  • Drawing multiple lines with Java Swing

    - by rize
    I'm learning drawing lines with Java Swing in order to draw a labyrinth. I can draw one line at a specified position and it shows just fine. But when I want to draw multiple lines, only the last one shows. My code: public class LabyrinthGUI extends JFrame { ... Line line1 = new Line(0, 0, 0, 50); this.getContentPane().add(line1); } public class Line extends JPanel{ private int x1, y1, x2, y2; public Line(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void paintComponent (Graphics g) { g.drawLine(x1, y1, x2, y2); } I probably have to refresh something, to display all the lines drawn with for-loop, but don't know what.

    Read the article

  • Flickering when repainting a JPanel inside a JScrollPAne

    - by pR0Ps
    I'm having a problem with repainting a JPanel inside a JScrollPane. Basically, I'm just trying to 'wrap' my existing EditPanel (it originally extended JPanel) into a JScrollPane. It seems that the JPanel updates too often (mass flickering). How would I stop this from happening? I tried using the setIgnoreRepaint() but it didn't seem to do anything. Will this current implementation work or would I need to create another inner class to fine-tune the JPanel I'm using to display graphics? Skeleton code: public class MyProgram extends JFrame{ public MyProgram(){ super(); add(new EditPanel()); pack(); } private class EditPanel extends JScrollPane{ private JPanel graphicsPanel; public EditPanel(){ graphicsPanel = new JPanel(); } public void paintComponent(Graphics g){ graphicsPanel.revalidate(); //update the scrollpane to current panel size repaint(); Graphics g2 = graphicsPanel.getGraphics(); g2.drawImage(imageToDraw, 0, 0, null); } } }

    Read the article

  • improving drawing pythagoras tree

    - by sasquatch90
    Hello. I have written program for drawing pythagoras tree fractal. Can anybody see any way of improving it ? Now it is 120 LOc. I was hoping to shorten it to ~100... import javax.swing.*; import java.util.Scanner; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JComponent; public class Main extends JFrame {; public Main(int n) { setSize(900, 900); setTitle("Pythagoras tree"); Draw d = new Draw(n); add(d); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private int pow(int n){ int pow = 2; for(int i = 1; i < n; i++){ if(n==0){ pow = 1; } pow = pow*2; } return pow; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Give amount of steps: "); int steps = sc.nextInt(); new Main(steps); } } class Draw extends JComponent { private int height; private int width; private int steps; public Draw(int n) { height = 800; width = 800; steps = n; Dimension d = new Dimension(width, height); setMinimumSize(d); setPreferredSize(new Dimension(d)); setMaximumSize(d); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.white); g.fillRect(0, 0, width, height); g.setColor(Color.black); int w = width; int h = height; int x1, x2, x3, x4, x5, y1, y2, y3, y4, y5; int base = w/7; x1 = (w/2)-(base/2); x2 = x1; x3 = (w/2)+(base/2); x4 = x3; x5 = w/2; y1 = (h-(h/15))-base; y2 = h-(h/15); y3 = y2; y4 = y1; y5 = (h-(h/15))-(base+(base/2)); //paint g.drawLine(x1, y1, x2, y2); g.drawLine(x2, y2, x3, y3); g.drawLine(x3, y3, x4, y4); g.drawLine(x1, y1, x4, y4); int n1 = steps; n1--; if(n1>0){ g.drawLine(x1, y1, x5, y5); g.drawLine(x4, y4, x5, y5); paintMore(n1, g, x1, x5, x4, y1, y5, y4); paintMore(n1, g, x4, x5, x1, y4, y5, y1); } } public void paintMore(int n1, Graphics g, double x1_1, double x2_1, double x3_1, double y1_1, double y2_1, double y3_1){ double x1, x2, x3, x4, x5, y1, y2, y3, y4, y5; //counting x1 = x1_1 + (x2_1-x3_1); x2 = x1_1; x3 = x2_1; x4 = x2_1 + (x2_1-x3_1); x5 = ((x2_1 + (x2_1-x3_1)) + ((x2_1-x3_1)/2)) + ((x1_1-x2_1)/2); y1 = y1_1 + (y2_1-y3_1); y2 = y1_1; y3 = y2_1; y4 = y2_1 + (y2_1-y3_1); y5 = ((y1_1 + (y2_1-y3_1)) + ((y2_1-y1_1)/2)) + ((y2_1-y3_1)/2); //paint g.setColor(Color.green); g.drawLine((int)x1, (int)y1, (int)x2, (int)y2); g.drawLine((int)x3, (int)y3, (int)x4, (int)y4); g.drawLine((int)x1, (int)y1, (int)x4, (int)y4); n1--; if(n1>0){ g.drawLine((int)x1, (int)y1, (int)x5, (int)y5); g.drawLine((int)x4, (int)y4, (int)x5, (int)y5); paintMore(n1, g, x1, x5, x4, y1, y5, y4); paintMore(n1, g, x4, x5, x1, y4, y5, y1); } } }

    Read the article

  • Adding fields to a proxied class in Clojure

    - by mikera
    I'm using "proxy" to extend various Swing classes in a Clojure GUI application, generally with code that looks something like: (def ^JPanel mypanel (proxy [JPanel] [] (paintComponent [#^Graphics g] (.drawImage g background-image 0 0 nil)))) This works well but I can't figure out how to add additional fields to the newly extended class, for example making the background-image a field that could be subsequently updated. This would be pretty easy and common practice in Java. Is there a good way to do this in Clojure? Or is there another preferred method to achieve the same effect?

    Read the article

  • Java MVC project - either I can't update the drawing, or I can't see it

    - by user1881164
    I've got a project based around the Model-View-Controller paradigm, and I've been having a lot of trouble with getting it to work properly. The program has 4 panels, which are supposed to allow me to modify an oval drawn on the screen in various ways. These seem to work fine, and after considerable trouble I was able to get them to display in the JFrame which holds the whole shebang. I've managed to get them to display by breaking away from the provided instructions, but when I do that, I can't seem to get the oval to update. However, if I follow the directions to the letter, I only ever see an empty frame. The project had pretty specific directions, which I followed up to a point, but some of the documentation was unclear. I think what I'm missing must be something simple, since nothing is jumping out at me as not making sense. I have to admit though that my Java experience is limited and my experience with GUI design/paradigms is even more so. Anyway, I've been searching the web and this site extensively trying to figure out what's wrong, but this is a somewhat specific example and honestly I just don't know enough about this to generalize any of the answers I've found online and figure out what's missing. I've been poring over this code for far too long now so I'm really hoping someone can help me out. public class Model { private Controller controller; private View view; private MvcFrame mvcFrame; private int radius = 44; private Color color = Color.BLUE; private boolean solid = true; //bunch of mutators and accessors for the above variables public Model() { controller = new Controller(this); view = new View(this); mvcFrame = new MvcFrame(this); } } Here's the model class. This seems to be fairly simple. I think my understanding of what's going on here is solid, and nothing seems to be wrong. Included mostly for context. public class Controller extends JPanel{ private Model model; public Controller(Model model) { this.model = model; setBorder(BorderFactory.createLineBorder(Color.GREEN)); setLayout(new GridLayout(4,1)); add(new RadiusPanel(model)); add(new ColorPanel(model)); add(new SolidPanel(model)); add(new TitlePanel(model)); } } This is the Controller class. As far as I can tell, the setBorder, setLayout, and series of adds do nothing here. I had them commented out, but this is the way that the instructions told me to do things, so either there's a mistake there or something about my setup is wrong. However, when I did it this way, I would get an empty window (JFrame) but none of the panels would show up in it. What I did to fix this is put those add functions in the mvcFrame class: public class MvcFrame extends JFrame { private Model model; public MvcFrame(Model model){ this.model = model; //setLayout(new GridLayout(4,1)); //add(new RadiusPanel(model)); //add(new ColorPanel(model)); //add(new SolidPanel(model)); //add(new TitlePanel(model)); //add(new View(model)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setSize(800,600); setVisible(true); } } So here's where things kind of started getting weird. The first block of commented out code is the same as what's in the Controller class. The reason I have it commented out is because that was just a lucky guess - it's not supposed to be like that according to the instructions. However, this did work for getting the panels to show up - but at that point I was still tearing my hair out trying to get the oval to display. The other commented line ( add(new View(model)); ) was a different attempt at making things work. In this case, I put those add functions in the View class (see commented out code below). This actually worked to display both the oval and the panels, but that method wouldn't allow me to update the oval. Also, though I just had the oval displaying, I can't seem to figure out what exactly made that happen, and I can't seem to make it come back. public class View extends JPanel{ private Model model; public View(Model model) { this.model = model; //setLayout(new GridLayout(4,1)); //add(new RadiusPanel(model)); //add(new ColorPanel(model)); //add(new SolidPanel(model)); //add(new TitlePanel(model)); repaint(); } @Override protected void paintComponent(Graphics g){ super.paintComponent(g); //center of view panel, in pixels: int xCenter = getWidth()/2; int yCenter = getHeight()/2; int radius = model.getRadius(); int xStart = xCenter - radius; int yStart = yCenter - radius; int xWidth = 2 * radius; int yHeight = 2 * radius; g.setColor(model.getColor()); g.clearRect(0, 0, getWidth(), getHeight()); if (model.isSolid()){ g.fillOval(xStart, yStart, xWidth, yHeight); } else { g.drawOval(xStart, yStart, xWidth, yHeight); } } } Kinda same idea as before - the commented out code is stuff I added to try to get things working, but is not based on the provided directions. In the case where that stuff was uncommented, I had the add(new View(model)); line from the mvcFrame line uncommented as well. The various panel classes (SolidPanel, ColorPanel, etc) simply extend a class called ControlPanel which extends JPanel. These all seem to work as expected, not having much issue with them. There is also a driver which launches the GUI. This also seems to work as expected. The main problem I'm having is that I can't get the oval to show up, and the one time I could make it show up, none of the options for changing it seemed to work. I feel like I'm close but I'm just at a loss for other things to try out at this point. Anyone who can help will have my sincerest gratitude.

    Read the article

  • Java, two JPanel on JFrame - Settings JPanel, StartMenu JPanel [on hold]

    - by Andy Tyurin
    There is my first question and I welcome community! I'm making a simple game and have some problems with Start menu. I have three buttons on my JPanel StartMenu and when I click "Settings" button, new JPanel will be open, but I don't know why buttons from StartMenu JPanel appeared in my Settings JPanel. My "Settings" JPanel has one ugly button "Back" in center and ugly grey background. I made some screens to see a problem. Start Menu JPanel when game launched Settings JPanel when button clicked Settings JPanel when mouse was over settings window There is code of StartMenu class: public class StartMenu extends JPanel { private GameButton startGameButton = new GameButton("Start game"); private GameButton settingsGameButton = new GameButton("Settings"); private GameButton exitGameButton = new GameButton("Exit game"); private Image bgImage = new ImageIcon(getClass().getClassLoader().getResource("ru/andydevs/astraLaserForce/bg.png")).getImage(); private int posX; private int posY; final private int WIDTH=(int)Game.SCREEN_DIMENSION.getWidth()/3; final private int HEIGHT=(int)Game.SCREEN_DIMENSION.getHeight()/2; public StartMenu() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); setSize(new Dimension(WIDTH, HEIGHT)); posX=(int)Game.SCREEN_DIMENSION.getWidth()/2-WIDTH/2; posY=(int)Game.SCREEN_DIMENSION.getHeight()/2-HEIGHT/2; setBounds(posX, posY,WIDTH,HEIGHT); c.ipadx=95; c.ipady=15; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(20,0,0,0); c.gridy=0; add(startGameButton, c); c.gridy=1; c.insets = new Insets(20,0,0,0); System.out.println(settingsGameButton.getWidth()); add(settingsGameButton, c); c.gridy=2; c.insets = new Insets(20,0,0,0); add(exitGameButton, c); settingsGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameOptionsPanel gop = new GameOptionsPanel(); Game.container.add(gop); Game.container.setComponentZOrder(gop, 0); Game.container.revalidate(); Game.container.repaint(); } }); exitGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Main.currentGame.stop(); } }); } public void paintComponent(Graphics g) { g.drawImage(bgImage,0,0,WIDTH,HEIGHT,null); } } There is code of Settings JPanel public class GameOptionsPanel extends GamePanel { private GameButton backButton = new GameButton("Back"); private GameOptionsPanel that; public GameOptionsPanel() { super((int) (Game.SCREEN_DIMENSION.getWidth()/3), (int) (Game.SCREEN_DIMENSION.getHeight()/2), new Color(50,50,50)); that=this; setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill=gbc.HORIZONTAL; add(backButton); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Game.container.remove(that); Game.container.revalidate(); Game.container.repaint(); } }); } } I glad to see some suggestions. Thanks.

    Read the article

  • Why a Swing app stops my Java servlet ?

    - by Frank
    I have a Swing runnable app which updates messages, then I have a Java servlet that gets messages from Paypal IPN (Instant Payment Notification), when the servlet starts up, in the init(), I starts the Swing runnable app which opens a desktop window, but 30 minutes later an error in the Swing caused the servlet to stop, how can that happen ? Because the runnable is running on it's own thread, servlet started that thread, why an error in that thread will cause the servlet to stop ? public class License_Manager extends JPanel implements Runnable { License_Manager() { Do_GUI(); ... start(); } public static void main(String[] args) { // Schedule a job for the event-dispatching thread : creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } }); } } public class PayPal_Servlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); License_Manager.main(null); } protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { } } And besides the error don't even have anything to do with my code, it looks like this : Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 17 = 0 at java.util.Vector.elementAt(Vector.java:427) at javax.swing.DefaultListModel.getElementAt(DefaultListModel.java:70) at javax.swing.plaf.basic.BasicListUI.paintCell(BasicListUI.java:191) at javax.swing.plaf.basic.BasicListUI.paintImpl(BasicListUI.java:304) at javax.swing.plaf.basic.BasicListUI.paint(BasicListUI.java:227) at javax.swing.plaf.ComponentUI.update(ComponentUI.java:143) at javax.swing.JComponent.paintComponent(JComponent.java:763) at javax.swing.JComponent.paint(JComponent.java:1029) at javax.swing.JComponent.paintChildren(JComponent.java:864) at javax.swing.JComponent.paint(JComponent.java:1038) at javax.swing.JViewport.paint(JViewport.java:747) at javax.swing.JComponent.paintChildren(JComponent.java:864) at javax.swing.JComponent.paint(JComponent.java:1038) at javax.swing.JComponent.paintToOffscreen(JComponent.java:5124) at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:278) at javax.swing.RepaintManager.paint(RepaintManager.java:1220) at javax.swing.JComponent._paintImmediately(JComponent.java:5072) at javax.swing.JComponent.paintImmediately(JComponent.java:4882) at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:803) at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714) at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694) at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    Read the article

  • How can I draw on JPanel using another quadrant for the coordinates?

    - by Sanoj
    I would like to draw some shapes on a JPanel by overriding paintComponent. I would like to be able to pan and zoom. Panning and zooming is easy to do with AffineTransform and the setTransform method on the Graphics2D object. After doing that I can easyli draw the shapes with g2.draw(myShape) The shapes are defined with the "world coordinates" so it works fine when panning and I have to translate them to the canvas/JPanel coordinates before drawing. Now I would like to change the quadrant of the coordinates. From the 4th quadrant that JPanel and computer often uses to the 1st quadrant that the users are most familiar with. The X is the same but the Y-axe should increase upwards instead of downwards. It is easy to redefine origo by new Point(origo.x, -origo.y); But How can I draw the shapes in this quadrant? I would like to keep the coordinates of the shapes (defined in the world coordinates) rather than have them in the canvas coordinates. So I need to transform them in some way, or transform the Graphics2D object, and I would like to do it efficiently. Can I do this with AffineTransform too?

    Read the article

  • Modifying and Manipulating a interactive bezier curve

    - by rachel
    This is a homework question and I'm having a lot of trouble with it - I've managed to do some of it but still cant finish it - can i Please get some help. Q1. Bezier Curves The following example allows you to interactively control a bezier curve by dragging the control points Cubic.java Replace the call to draw the cubic shape (big.draw(cubic)), by your own function to draw a bezier by the recursive split method. Finally, add the ability to create a longer Bezier curve by adding more control points to create a second curve. Cubic.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.applet.Applet; import java.awt.geom.*; import java.awt.image.BufferedImage; public class Cubic extends JApplet{ static protected JLabel label; CubicPanel cubicPanel; public void init(){ //Initialize the layout. getContentPane().setLayout(new BorderLayout()); cubicPanel = new CubicPanel(); cubicPanel.setBackground(Color.white); getContentPane().add(cubicPanel); label = new JLabel("Drag the points to adjust the curve."); getContentPane().add("South", label); } public static void main(String s[]) { JFrame f = new JFrame("Cubic"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); JApplet applet = new Cubic(); f.getContentPane().add(applet, BorderLayout.CENTER); applet.init(); f.setSize(new Dimension(350,250)); f.setVisible(true); } } class CubicPanel extends JPanel implements MouseListener, MouseMotionListener{ BufferedImage bi; Graphics2D big; int x, y; Rectangle area, startpt, endpt, onept, twopt, rect; CubicCurve2D.Double cubic = new CubicCurve2D.Double(); Point2D.Double start, end, one, two, point; boolean firstTime = true; boolean pressOut = false; public CubicPanel(){ setBackground(Color.white); addMouseMotionListener(this); addMouseListener(this); start = new Point2D.Double(); one = new Point2D.Double(); two = new Point2D.Double(); end = new Point2D.Double(); cubic.setCurve(start, one, two, end); startpt = new Rectangle(0, 0, 8, 8); endpt = new Rectangle(0, 0, 8, 8); onept = new Rectangle(0, 0, 8, 8); twopt = new Rectangle(0, 0, 8, 8); } public void mousePressed(MouseEvent e){ x = e.getX(); y = e.getY(); if(startpt.contains(x, y)){ rect = startpt; point = start; x = startpt.x - e.getX(); y = startpt.y - e.getY(); updateLocation(e); } else if(endpt.contains(x, y)){ rect = endpt; point = end; x = endpt.x - e.getX(); y = endpt.y - e.getY(); updateLocation(e); } else if(onept.contains(x, y)){ rect = onept; point = one; x = onept.x - e.getX(); y = onept.y - e.getY(); updateLocation(e); } else if(twopt.contains(x, y)){ rect = twopt; point = two; x = twopt.x - e.getX(); y = twopt.y - e.getY(); updateLocation(e); } else { pressOut = true; } } public void mouseDragged(MouseEvent e){ if(!pressOut) { updateLocation(e); } } public void mouseReleased(MouseEvent e){ if(startpt.contains(e.getX(), e.getY())){ rect = startpt; point = start; updateLocation(e); } else if(endpt.contains(e.getX(), e.getY())){ rect = endpt; point = end; updateLocation(e); } else if(onept.contains(e.getX(), e.getY())){ rect = onept; point = one; updateLocation(e); } else if(twopt.contains(e.getX(), e.getY())){ rect = twopt; point = two; updateLocation(e); } else { pressOut = false; } } public void mouseMoved(MouseEvent e){} public void mouseClicked(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void updateLocation(MouseEvent e){ rect.setLocation((x + e.getX())-4, (y + e.getY())-4); point.setLocation(x + e.getX(), y + e.getY()); checkPoint(); cubic.setCurve(start, one, two, end); repaint(); } public void paintComponent(Graphics g){ super.paintComponent(g); update(g); } public void update(Graphics g){ Graphics2D g2 = (Graphics2D)g; Dimension dim = getSize(); int w = dim.width; int h = dim.height; if(firstTime){ // Create the offsecren graphics to render to bi = (BufferedImage)createImage(w, h); big = bi.createGraphics(); // Get some initial positions for the control points start.setLocation(w/2-50, h/2); end.setLocation(w/2+50, h/2); one.setLocation((int)(start.x)+25, (int)(start.y)-25); two.setLocation((int)(end.x)-25, (int)(end.y)+25); // Set the initial positions of the squares that are // drawn at the control points startpt.setLocation((int)((start.x)-4), (int)((start.y)-4)); endpt.setLocation((int)((end.x)-4), (int)((end.y)-4)); onept.setLocation((int)((one.x)-4), (int)((one.y)-4)); twopt.setLocation((int)((two.x)-4), (int)((two.y)-4)); // Initialise the CubicCurve2D cubic.setCurve(start, one, two, end); // Set some defaults for Java2D big.setColor(Color.black); big.setStroke(new BasicStroke(5.0f)); big.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); area = new Rectangle(dim); firstTime = false; } // Clears the rectangle that was previously drawn. big.setColor(Color.white); big.clearRect(0, 0, area.width, area.height); // Set the colour for the bezier big.setPaint(Color.black); // Replace the following line by your own function to // draw the bezier specified by start, one, two, end big.draw(cubic); // Draw the control points big.setPaint(Color.red); big.fill(startpt); big.setPaint(Color.magenta); big.fill(endpt); big.setPaint(Color.blue); big.fill(onept); big.setPaint(new Color(0, 200, 0)); big.fill(twopt); // Draws the buffered image to the screen. g2.drawImage(bi, 0, 0, this); } /* Checks if the rectangle is contained within the applet * window. If the rectangle is not contained withing the * applet window, it is redrawn so that it is adjacent to the * edge of the window and just inside the window. */ void checkPoint(){ if (area == null) { return; } if((area.contains(rect)) && (area.contains(point))){ return; } int new_x = rect.x; int new_y = rect.y; double new_px = point.x; double new_py = point.y; if((rect.x+rect.width)>area.getWidth()){ new_x = (int)area.getWidth()-(rect.width-1); } if(point.x > area.getWidth()){ new_px = (int)area.getWidth()-1; } if(rect.x < 0){ new_x = -1; } if(point.x < 0){ new_px = -1; } if((rect.y+rect.width)>area.getHeight()){ new_y = (int)area.getHeight()-(rect.height-1); } if(point.y > area.getHeight()){ new_py = (int)area.getHeight()-1; } if(rect.y < 0){ new_y = -1; } if(point.y < 0){ new_py = -1; } rect.setLocation(new_x, new_y); point.setLocation(new_px, new_py); } }

    Read the article

  • Why aren't my coordinates matching my JFrame size?

    - by AsLanFromNarnia
    I want to do some drawing in a JPanel but the enclosing JFrame size doesn't seem to match where I've asked the coordinates to be drawn. In my example code, the JFrame size is set to (700, 700) and the last point is drawn at (600, 600). I would expect this point to be drawn 100 pixels away from the right and bottom edges but it isn't (please see screenshot). Here's the code I'm using: import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class Scratch extends JPanel { static int frameWidth = 700; static int frameHeight = 700; public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(frameWidth, frameHeight); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Scratch scratch = new Scratch(); frame.getContentPane().add(scratch); frame.setVisible(true); } @Override public void paintComponent(Graphics g) { g.drawRect(100, 100, 1, 1); g.drawString("100", 100, 100); g.drawRect(200, 200, 1, 1); g.drawString("200", 200, 200); g.drawRect(300, 300, 1, 1); g.drawString("300", 300, 300); g.drawRect(400, 400, 1, 1); g.drawString("400", 400, 400); g.drawRect(500, 500, 1, 1); g.drawString("500", 500, 500); g.drawRect(600, 600, 1, 1); g.drawString("600", 600, 600); } }

    Read the article

  • drawing to a JPanel without inheritance

    - by g.rocket
    Right now I'm working on a program that throws up a bunch of separate (generated at runtime) images, each in their own window. To do this i've tried this approach: public void display(){ JFrame window = new JFrame("NetPart"); JPanel canvas = new JPanel(); window.getContentPane().add(canvas); Graphics g = canvas.getGraphics(); Dimension d = getSize(); System.out.println(d); draw(g,new Point(d.minX*50,d.maxY*50), 50); window.setSize(d.size(50)); window.setResizable(false); window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); window.setVisible(true); } public void draw(Graphics g, Point startLoc, int scale){ // generate and draw the image } public Dimension getSize(){ //returns my own dimensions class } However, this throws a NullPointerException in draw, claiming that the graphics is null. is there any way to externally draw to a JPanel from outside it (not inherit from JPanel and override PaintComponent)? Any help would be appreciated.

    Read the article

  • Drawing graphics on top of a JButton

    - by trinth
    I have a situation wherein I have a bunch of JButtons on a GridLayout. I need each of the JButtons to have: a background image (but retain the ability to keep the default button look if needed) custom graphics drawn on top by other classes I have no trouble with the background image, since I am using setIcon() but I am having problems drawing things on top of the background. At one point I was able to draw on top of the button, but after the button was clicked, the drawings disappeared. How can make the button keep this drawing state? Basically, I need a way for my JButtons to have public methods that would allow another class to draw anything on it such as: public void drawSomething() { Graphics g = this.getGraphics(); g.drawOval(3,2,2,2); repaint(); } or public Graphics getGraphics() { return this.getGraphics(); } then another class could do this: button.getGraphics().drawSomething(); The latter is more what I am looking for but the first is equally useful. Is there any way to go about this? Also, overriding the parent class method paintComponent() doesn't help since I need each button to have different graphics.

    Read the article

  • problem in adding image to JFrame

    - by firestruq
    Hi, I'm having problems in adding a picture into JFrame, something is missing probebly or written wrong. here are the classes: main class: public class Tester { public static void main(String args[]) { BorderLayoutFrame borderLayoutFrame = new BorderLayoutFrame(); borderLayoutFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); borderLayoutFrame.setSize(600,600); borderLayoutFrame.setVisible(true); } } public class BorderLayoutFrame extends JFrame implements ActionListener { private JButton buttons[]; // array of buttons to hide portions private final String names[] = { "North", "South", "East", "West", "Center" }; private BorderLayout layout; // borderlayout object private PicPanel picture = new PicPanel(); // set up GUI and event handling public BorderLayoutFrame() { super( "Philosofic Problem" ); layout = new BorderLayout( 5, 5 ); // 5 pixel gaps setLayout( layout ); // set frame layout buttons = new JButton[ names.length ]; // set size of array // create JButtons and register listeners for them for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); } add( buttons[ 0 ], BorderLayout.NORTH ); // add button to north add( buttons[ 1 ], BorderLayout.SOUTH ); // add button to south add( buttons[ 2 ], BorderLayout.EAST ); // add button to east add( buttons[ 3 ], BorderLayout.WEST ); // add button to west add( picture, BorderLayout.CENTER ); // add button to center } // handle button events public void actionPerformed( ActionEvent event ) { } } I'v tried to add the image into the center of layout. here is the image class: public class PicPanel extends JPanel { Image img; private int width = 0; private int height = 0; public PicPanel() { super(); img = Toolkit.getDefaultToolkit().getImage("table.jpg"); } public void paintComponent(Graphics g) { super.paintComponents(g); if ((width <= 0) || (height <= 0)) { width = img.getWidth(this); height = img.getHeight(this); } g.drawImage(img,0,0,width,height,this); } } Please your help, what is the problem? thanks BTW: i'm using eclipse, which directory the image suppose to be in?

    Read the article

  • Is there any way to add a MouseListener to a Graphic object ?

    - by Fahad
    Hi, Is there any way to add a MouseListener to a Graphic object. I have this simple GUI that draw an oval. What I want is handling the event when the user clicks on the oval import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; public class Gui2 extends JFrame { JFrame frame = new JFrame(); MyDrawPanel drawpanel = new MyDrawPanel(); public static void main(String[] args) { Gui2 gui = new Gui2(); gui.go(); } public void go() { frame.getContentPane().add(drawpanel); // frame.addMouseListener(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } } class MyDrawPanel extends JComponent implements MouseListener { public void paintComponent(Graphics g) { int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); Color startrandomColor = new Color(red, green, blue); red = (int) (Math.random() * 255); green = (int) (Math.random() * 255); blue = (int) (Math.random() * 255); Color endrandomColor = new Color(red, green, blue); Graphics2D g2d = (Graphics2D) g; this.addMouseListener(this); GradientPaint gradient = new GradientPaint(70, 70, startrandomColor, 150, 150, endrandomColor); g2d.setPaint(gradient); g2d.fillOval(70, 70, 100, 100); } @Override public void mouseClicked(MouseEvent e) { if ((e.getButton() == 1) && (e.getX() >= 70 && e.getX() <= 170 && e.getY() >= 70 && e .getY() <= 170)) { this.repaint(); // JOptionPane.showMessageDialog(null,e.getX()+ "\n" + e.getY()); } } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } } This Works Except it fires when the click is within a virtual box around the oval. Could anyone help me to have it fire when the click is EXACTLY on the oval. Thanks in advance.

    Read the article

  • JFrame does not refresh after deleting an image

    - by dajackal
    Hi! I'm working for the first time with images in a JFrame, and I have some problems. I succeeded in putting an image on my JFrame, and now i want after 2 seconds to remove my image from the JFrame. But after 2 seconds, the image does not disappear, unless I resize the frame or i minimize and after that maximize the frame. Help me if you can. Thanks. Here is the code: File f = new File("2.jpg"); System.out.println("Picture " + f.getAbsolutePath()); BufferedImage image = ImageIO.read(f); MyBufferedImage img = new MyBufferedImage(image); img.resize(400, 300); img.setSize(400, 300); img.setLocation(50, 50); getContentPane().add(img); this.setSize(600, 400); this.setLocationRelativeTo(null); this.setVisible(true); Thread.sleep(2000); System.out.println("2 seconds over"); getContentPane().remove(img); Here is the MyBufferedImage class: public class MyBufferedImage extends JComponent{ private BufferedImage image; private int nPaint; private int avgTime; private long previousSecondsTime; public MyBufferedImage(BufferedImage b) { super(); this.image = b; this.nPaint = 0; this.avgTime = 0; this.previousSecondsTime = System.currentTimeMillis(); } @Override public void paintComponent(Graphics g) { Graphics2D g2D = (Graphics2D) g; g2D.setColor(Color.BLACK); g2D.fillRect(0, 0, this.getWidth(), this.getHeight()); long currentTimeA = System.currentTimeMillis(); //g2D.drawImage(this.image, 320, 0, 0, 240, 0, 0, 640, 480, null); g2D.drawImage(image, 0,0, null); long currentTimeB = System.currentTimeMillis(); this.avgTime += currentTimeB - currentTimeA; this.nPaint++; if (currentTimeB - this.previousSecondsTime > 1000) { System.out.format("Drawn FPS: %d\n", nPaint++); System.out.format("Average time of drawings in the last sec.: %.1f ms\n", (double) this.avgTime / this.nPaint++); this.previousSecondsTime = currentTimeB; this.avgTime = 0; this.nPaint = 0; } } }

    Read the article

  • How do I make my custom Swing component visible?

    - by Alex
    I have no idea why it won't show. First I create an instance of the component and then add it to a certain element in a two-dimensional JPanel array. Then I loop through that array and add each JPanel to another JPanel container which is to hold all the JPanels. I then add that final container to my JFrame window and set visibility to true, it should be visible? public class View extends JFrame { Board gameBoard; JFrame gameWindow = new JFrame("Chess"); JPanel gamePanel = new JPanel(); JPanel[][] squarePanel = new JPanel[8][8]; JMenuBar gameMenu = new JMenuBar(); JButton restartGame = new JButton("Restart"); JButton pauseGame = new JButton("Pause"); JButton log = new JButton("Log"); View(Board board){ gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE); gameWindow.setSize(400, 420); gameWindow.getContentPane().add(gamePanel, BorderLayout.CENTER); gameWindow.getContentPane().add(gameMenu, BorderLayout.NORTH); gameMenu.add(restartGame); gameMenu.add(pauseGame); gameMenu.add(log); gameBoard = board; drawBoard(gameBoard); gameWindow.setResizable(false); gameWindow.setVisible(true); } public void drawBoard(Board board){ for(int row = 0; row < 8; row++){ for(int col = 0; col < 8; col++){ Box box = new Box(board.getSquare(col, row).getColour(), col, row); squarePanel[col][row] = new JPanel(); squarePanel[col][row].add(box); } } for(JPanel[] col : squarePanel){ for(JPanel square : col){ gamePanel.add(square); } } } } @SuppressWarnings("serial") class Box extends JComponent{ Color boxColour; int col, row; public Box(Color boxColour, int col, int row){ this.boxColour = boxColour; this.col = col; this.row = row; repaint(); } protected void paintComponent(Graphics drawBox){ drawBox.setColor(boxColour); drawBox.drawRect(50*col, 50*row, 50, 50); drawBox.fillRect(50*col, 50*row, 50, 50); } } A final question as well. Notice how each Box component has a position, what happens to the position when I add the component to a JPanel and add the JPanel to my JFrame? Does it still have the same position in relation to the other Box components?

    Read the article

  • How can I set an image for background of GUI interface?

    - by enriched
    hey everyone, im having some troubles displaying the background image for a GUI interface in java. Here is what i have at the moment, and with current stage of code it shows default(gray) background. import javax.swing.*; import java.awt.event.*; import java.util.Scanner; import java.awt.*; import java.io.File; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; ////////////////////////////////// // 3nriched Games Presents: // // MIPS The Mouse!! // ////////////////////////////////// public class mipsMouseGUI extends JFrame implements ActionListener { private static String ThePDub = ("mouse"); //the password JPasswordField pass; JPanel panel; JButton btnEnter; JLabel lblpdub; public mipsMouseGUI() { BufferedImage image = null; try { //attempts to read picture from the folder image = ImageIO.read(getClass().getResource("/mousepics/mousepic.png")); } catch (IOException e) { //catches exceptions e.printStackTrace(); } ImagePanel panel = new ImagePanel(new ImageIcon("/mousepics/neonglowOnwill.png").getImage()); setIconImage(image); //sets icon picture setTitle("Mips The Mouse Login"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pass = new JPasswordField(5); //sets password length to 5 pass.setEchoChar('@'); //hide characters as @ symbol pass.addActionListener(this); //adds action listener add(panel); //adds panel to frame btnEnter = new JButton("Enter"); //creates a button btnEnter.addActionListener(this);// Register the action listener. lblpdub = new JLabel(" Your Password: "); // label that says enter password panel.add(lblpdub, BorderLayout.CENTER);// adds label and inputbox panel.add(pass, BorderLayout.CENTER); // to panel and sets location panel.add(btnEnter, BorderLayout.CENTER); //adds button to panel pack(); // packs controls and setLocationRelativeTo(null); // Implicit "this" if inside JFrame constructor. setVisible(true);// makes them visible (duh) } public void actionPerformed(ActionEvent a) { Object source = a.getSource(); //char array that holds password char[] passy = pass.getPassword(); //characters array to string String p = new String(passy); //determines if user entered correct password if(p.equals(ThePDub)) { JOptionPane.showMessageDialog(null, "Welcome beta user: USERNAME."); } else JOptionPane.showMessageDialog(null, "You have enter an incorrect password. Please try again."); } public class ImagePanel extends JPanel { private BufferedImage img; public ImagePanel(String img) { this(new ImageIcon(img).getImage()); } public ImagePanel(Image img) { Dimension size = new Dimension(img.getWidth(null), img.getHeight(null)); } public void paintComponent(Graphics g) { g.drawImage(img, 0, 0, null); } } }

    Read the article

  • Help with simple frame, and graphics in Java

    - by Crystal
    For hw, I'm trying to create a "CustomButton" that has a frame and in that frame, I draw two triangles, and a square over it. It's supposed to give the user the effect of a button press once it is depressed. So for starters, I am trying to set up the beginning graphics, drawing two triangles, and a square. The problem I have is although I set my frame to 200, 200, and the triangles I have drawn I think to the correct ends of my frame size, when I run the program, I have to extend my window to make the whole artwork, my "CustomButton," viewable. Is that normal? Thanks. Code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CustomButton { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CustomButtonFrame frame = new CustomButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class CustomButtonFrame extends JFrame { // constructor for CustomButtonFrame public CustomButtonFrame() { setTitle("Custom Button"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); CustomButtonSetup buttonSetup = new CustomButtonSetup(); this.add(buttonSetup); } private static final int DEFAULT_WIDTH = 200; private static final int DEFAULT_HEIGHT = 200; } class CustomButtonSetup extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // first triangle coords int x[] = new int[TRIANGLE_SIDES]; int y[] = new int[TRIANGLE_SIDES]; x[0] = 0; y[0] = 0; x[1] = 200; y[1] = 0; x[2] = 0; y[2] = 200; Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES); // second triangle coords x[0] = 0; y[0] = 200; x[1] = 200; y[1] = 200; x[2] = 200; y[2] = 0; Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES); g2.drawPolygon(firstTriangle); g2.setColor(Color.WHITE); g2.fillPolygon(firstTriangle); g2.drawPolygon(secondTriangle); g2.setColor(Color.GRAY); g2.fillPolygon(secondTriangle); // draw rectangle 10 pixels off border g2.drawRect(10, 10, 180, 180); } public static final int TRIANGLE_SIDES = 3; }

    Read the article

< Previous Page | 1 2 3 4  | Next Page >