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.
Related
I have a JSlider but it does not appear when I run the code. I also created a button, but that one shows. Also, do you know how to change the location of the two to the bottom left and right? Thanks!
Here is my code
public class Board extends JPanel implements ActionListener,
KeyListener
{
private CurlingStone[] stones;
private int stonenumber;
private Timer timer;
private int delay = 15;
private Button button;
private JSlider slider;
public Board()
{
stones = new CurlingStone[8];
for(int i = 0; i < 8; i++)
{
if(i%2 == 0)
stones[i] = new CurlingStone(Color.yellow);
else
stones[i] = new CurlingStone(Color.red);
}
stonenumber = 0;
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
this button appears
button = new Button("Launch");
add(button);
button.addActionListener(this);
but the slider does not, so over here I'm not sure what's wrong
slider = new JSlider(1, 10, 1);
slider.setMinorTickSpacing(1);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
add(slider);
timer = new Timer(delay, this);
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0, 0, 400, 725);
g.setColor(Color.gray);
g.fillRect(0, 0, 400, 50);
g.setColor(Color.blue);
g.fillOval(95, 95, 210, 210);
g.setColor(Color.white);
g.fillOval(125, 125, 150, 150);
g.setColor(Color.red);
g.fillOval(155, 155, 90, 90);
g.setColor(Color.white);
g.fillOval(185, 185, 30, 30);
for(int i = 0; i <= stonenumber; i++)
{
stones[i].draw((Graphics2D) g);
}
if(stones[stonenumber].stoneX == 185 &&
stones[stonenumber].stoneY == 600)
{
g.setColor(Color.green);
((Graphics2D)g).setStroke(new BasicStroke(4));
g.drawLine(200, 600, 200 + stones[stonenumber].dirX*10, 530);
}
this.requestFocus();
g.dispose();
}
I am making a GUI that has Graphics2D objects drawn on a JPanel within a JFrame. When I resize the window the Graphics2D objects reduce into a tiny rectangle. How can I set the drawing to resize with the JFrame when the user resizes the window?
I have tried using gridlayout, flowlayout, borderlayout, and settled on gridbaglayout. This helps with the resizing of btnPanel and the JButton but not for the Graphics2D objects.
Here is my self contained example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DrawPanelMain extends JPanel {
/*
* Variables used to set the value of preferred height and width
*/
public static final double version = 0.0;
JPanel btnPanel = new JPanel();
JPanel switchPanel = new JPanel();
DrawEllipses drawEllipses = new DrawEllipses(POINT_LIST);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initializePointList();
createAndShowGui();
}
});
}
public static java.util.List<Point> POINT_LIST = new ArrayList<>();
/*
* This loop will initialize POINT_LIST with the set of points for drawing the ellipses.
* The for each loop initializes points for the top row and the second for loop draws the
* right triangle.
*/
public static void initializePointList() {
int ellipsePointsYCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620};
int ellipsePointsXCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620, 680};
int xx = 80;
for (int aXt : ellipsePointsXCoordinate) {
POINT_LIST.add(new Point(aXt, xx));
}
for (int i = 0; i < ellipsePointsYCoordinate.length; i++) {
for (int j = i; j < ellipsePointsYCoordinate.length; j++) {
POINT_LIST.add(new Point(ellipsePointsXCoordinate[i], ellipsePointsYCoordinate[j]));
}
}
}
public DrawPanelMain() {
switchPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
switchPanel.setBackground(Color.DARK_GRAY);
switchPanel.add(drawEllipses);
switchPanel.revalidate();
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// first column
c.gridx = 0;
add(switchPanel, c);
// second column
c.gridx = 1;
add(switchPanel, c);
// first row
c.gridy = 0;
// second row
c. gridy = 1;
add(btnPanel, c);
btnPanel.add(new JButton(new AddSwitchAction("Add Switch Panel")));
}
public static void createAndShowGui() {
JFrame frame = new JFrame("RF Connection Panel " + version);
frame.setLayout(new BorderLayout());
frame.add(new DrawPanelMain());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(false);
//frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
/*
* AddSwitchAction will add a new pane to the tabbedPane when the add switch button is clicked
*/
private class AddSwitchAction extends AbstractAction {
public AddSwitchAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String title = "Switch ";
DrawEllipses tabComponent = new DrawEllipses(POINT_LIST);
switchPanel.add(title, tabComponent);
}
}
}
#SuppressWarnings("serial")
class DrawEllipses extends JPanel {
private final int PREF_W = 750; //Window width
private final int PREF_H = 750; //Window height
private final int OVAL_WIDTH = 30;
private static final Color INACTIVE_COLOR = Color.RED;
private static final Color ACTIVE_COLOR = Color.green;
private java.util.List<Point> points;
private java.util.List<Ellipse2D> ellipses = new ArrayList<>();
private Map<Ellipse2D, Color> ellipseColorMap = new HashMap<>();
/*
* This method is used to populate "ellipses" with the initialized ellipse2D dimensions
*/
public DrawEllipses(java.util.List<Point> points) {
this.points = points;
for (Point p : points) {
int x = p.x - OVAL_WIDTH / 2;
int y = p.y - OVAL_WIDTH / 2;
int w = OVAL_WIDTH;
int h = OVAL_WIDTH;
Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h);
ellipses.add(ellipse);
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
MyMouseAdapter mListener = new MyMouseAdapter();
addMouseListener(mListener);
addMouseMotionListener(mListener);
}
/*
* paintComponent is used to paint the ellipses
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ellipse2D ellipse : ellipses) {
g2.setColor(ellipseColorMap.get(ellipse));
g2.fill(ellipse);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(2));
g2.draw(ellipse);
}
/*
* Set the font characteristics, color, and draw the row labels.
*/
g.setFont(new Font("TimesRoman", Font.BOLD, 18));
g.setColor(Color.BLACK);
//Along the top row
g.drawString("External Port", 10, 50);
g.drawString("1", 135, 50);
g.drawString("2", 195, 50);
g.drawString("3", 255, 50);
g.drawString("4", 315, 50);
g.drawString("5", 375, 50);
g.drawString("6", 435, 50);
g.drawString("7", 495, 50);
g.drawString("8", 555, 50);
g.drawString("9", 615, 50);
g.drawString("10", 672, 50);
//Along the Y-axis
g.drawString("Radio 2", 40, 145);
g.drawString("3", 90, 205);
g.drawString("4", 90, 265);
g.drawString("5", 90, 325);
g.drawString("6", 90, 385);
g.drawString("7", 90, 445);
g.drawString("8", 90, 505);
g.drawString("9", 90, 565);
g.drawString("10", 90, 625);
//Along the X-Axis
g.drawString("1", 135, 670);
g.drawString("2", 195, 670);
g.drawString("3", 255, 670);
g.drawString("4", 315, 670);
g.drawString("5", 375, 670);
g.drawString("6", 435, 670);
g.drawString("7", 495, 670);
g.drawString("8", 555, 670);
g.drawString("9", 615, 670);
//Draws a 3DRect around the top row of ellipse2D objects
g2.setColor(Color.lightGray);
g2.draw3DRect(120, 60, 580, 40, true);
g2.draw3DRect(121, 61, 578, 38, true);
g2.draw3DRect(122, 62, 576, 36, true);
}
/*
* MouseAdapter is extended for mousePressed Event that detects if the x, y coordinates
* of a drawn ellipse are clicked. If the color is INACTIVE it is changed to ACTIVE and
* vice versa.
*/
private class MyMouseAdapter extends MouseAdapter {
#Override
/*
* When mousePressed event occurs, the color is toggled between ACTIVE and INACTIVE
*/
public void mousePressed(MouseEvent e) {
Color c;
for (Ellipse2D ellipse : ellipses) {
if (ellipse.contains(e.getPoint())) {
c = (ellipseColorMap.get(ellipse) == INACTIVE_COLOR) ? ACTIVE_COLOR : INACTIVE_COLOR;
ellipseColorMap.put(ellipse, c);
}
}
repaint();
}
}
/*
* This method will set the dimensions of the JFrame equal to the preferred H x W
*/
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
/*
* Used for button click action to change all ellipses to ACTIVE_COLOR
*/
public void activateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, ACTIVE_COLOR);
}
repaint();
}
/*
* Used for button click action to change all ellipses to INACTIVE_COLOR
*/
public void deactivateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
repaint();
}
}
This method will set the dimensions of the JFrame equal to the preferred H x W
No it set the preferred size of the panel. The size of the frame will be the preferred size of all the components added to it plus the frame decorations (title bar, borders).
When I resize the window the Graphics2D objects reduce into a tiny rectangle.
The GridBagLayout respects the preferred size of the component. When there is not enough space to display the component it will shrink to its "minimum size".
You probably need to override the getMinimumSize() method to equal the preferred size. Then in this case the component should just be truncated if space is not available.
If you want you actually painting to shrink then you need to build the logic into your painting code so that the painting is done relative to the space available on the panel.
Try adding your 2D object to a JLabel as BufferedImage of ImageIcon. You can do this by:
JLabel label2 = new JLabel(new ImageIcon(//Location of your Image);
Or I think you can also add Graphics2D objects directly creating them inside label bu I'm not sure about that
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();
}
});
}
}
I am using the following code to test the bound values of a JFrame of mine:
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1 = this.getBounds();
this.setExtendedState(JFrame.MAXIMIZED_BOTH); //this == JFrame
r2 = this.getBounds();
At first, I thought that the values of r2 (regarding x, y, width and height) would be different, since the frame is automatically resized. However, the variables r1 and r2 seems to be (almost) equal, according to the Debugger.
Why does this happen? What should I do in order to get the new values of the maximized JFrame?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class NewGUI extends JFrame {
private JPanel contentPane;
private List list;
private JButton btnSelectAgent;
private JTextField textField;
private JButton btnBrowse;
private JButton btnPreviousStep2;
private JButton btnLoad;
private JButton btnPreviousStep3;
private JButton btnStart;
private File file = null;
ImageIcon icon = new ImageIcon("image.gif");
Border blackline = BorderFactory.createLineBorder(Color.black);
private JPanel firstStepPanel;
private JPanel secondStepPanel;
private JPanel thirdStepPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NewGUI frame = new NewGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public NewGUI() {
super("GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 681, 422);
contentPane = new JPanel();
contentPane.setForeground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null); //centered location
contentPane.setLayout(null);
//test codes begin
Insets insets = this.getInsets();
Rectangle r = new Rectangle();
Dimension d = new Dimension();
r.x = 0;
r.y = 0;
r.width = 1280;
r.height = 1024;
r = this.getMaximizedBounds();
d = this.getMaximumSize();
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
Dimension d1 = new Dimension();
Dimension d2 = new Dimension();
d1 = this.getSize();
r1 = this.getBounds();
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
r = this.getMaximizedBounds();
r2 = r1;
this.setMaximizedBounds(r);
r2.width = this.getWidth();
r2.height = this.getHeight();
d2 = this.getSize();
//test codes end
/* pane.setLayout(null);
JButton b1 = new JButton("one");
JButton b2 = new JButton("two");
JButton b3 = new JButton("three");
pane.add(b1);
pane.add(b2);
pane.add(b3);
JPanel pane = new JPanel();
Insets insets = this.getInsets();
Rectangle r = new Rectangle();
r.x = insets.left;
r.y = insets.top;
JFrame frame = new JFrame();
frame.getInsets();
Dimension size = b1.getPreferredSize();
b1.setBounds(25 + insets.left, 5 + insets.top, size.width, size.height);
Rectangle r = new Rectangle();
r.x = 1;
r.y = 2;
b1.setBounds
size = b2.getPreferredSize();
b2.setBounds(55 + insets.left, 40 + insets.top, size.width, size.height);
size = b3.getPreferredSize();
b3.setBounds(150 + insets.left, 15 + insets.top, size.width + 50, size.height + 20);
...//In the main method:
Insets insets = frame.getInsets();
frame.setSize(300 + insets.left + insets.right, 125 + insets.top + insets.bottom);
*/
firstStepPanel = new JPanel();
firstStepPanel.setBounds(10, 10, 194, 363);
contentPane.add(firstStepPanel);
//this.add(firstStepPanel, BorderLayout.WEST);
firstStepPanel.setLayout(null);
firstStepPanel.setBorder(
BorderFactory.createTitledBorder(blackline, "Agent selection"));
//makeFrameFullSize(contentPane); //aparentemente nao funcionando
list = new List();
list.setBounds(10, 31, 169, 203);
firstStepPanel.add(list);
list.setMultipleSelections(true);
btnSelectAgent = new JButton("Select Agent");
btnSelectAgent.setBounds(10, 274, 169, 34);
firstStepPanel.add(btnSelectAgent);
secondStepPanel = new JPanel();
secondStepPanel.setBorder(
BorderFactory.createTitledBorder(blackline, "file selection"));
secondStepPanel.setBounds(214, 11, 266, 362);
contentPane.add(secondStepPanel);
//this.add(secondStepPanel, BorderLayout.CENTER);
secondStepPanel.setLayout(null);
btnLoad = new JButton("Load");
btnLoad.setBounds(78, 317, 118, 34);
secondStepPanel.add(btnLoad);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (file == null) {
showMessage("Please, select a file on the upper options");
} else {
disableSecondStep();
enableThirdStep();
}
}
});
btnLoad.setEnabled(false);
textField = new JTextField();
textField.setBounds(10, 29, 157, 34);
secondStepPanel.add(textField);
textField.setEnabled(false);
textField.setColumns(10);
textField.setText("P:\\\\");
btnBrowse = new JButton("Browse");
btnBrowse.setBounds(167, 29, 89, 35);
secondStepPanel.add(btnBrowse);
btnBrowse.setEnabled(false);
btnPreviousStep2 = new JButton("<< Previous");
btnPreviousStep2.setBounds(78, 272, 118, 34);
secondStepPanel.add(btnPreviousStep2);
btnPreviousStep2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enableFirstStep();
disableSecondStep();
}
});
btnPreviousStep2.setEnabled(false);
thirdStepPanel = new JPanel();
thirdStepPanel.setBorder(
BorderFactory.createTitledBorder(blackline, "Process initialization"));
thirdStepPanel.setBounds(490, 10, 165, 362);
contentPane.add(thirdStepPanel);
//this.add(thirdStepPanel, BorderLayout.EAST);
thirdStepPanel.setLayout(null);
//thirdStepPanel.setSize(100, r.height);
//r.x += 100;
//thirdStepPanel.setBounds(r);
//thirdStepPanel.setBounds(r.x,r.y, r.width, r.height);
//thirdStepPanel.setAlignmentX(r.x);
//thirdStepPanel.setAlignmentY(r.y);
btnPreviousStep3 = new JButton("<< Previous");
btnPreviousStep3.setBounds(7, 56, 151, 34);
thirdStepPanel.add(btnPreviousStep3);
btnPreviousStep3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enableSecondStep();
disableThirdStep();
}
});
btnPreviousStep3.setEnabled(false);
btnStart = new JButton(icon);
btnStart.setBounds(7, 101, 151, 159);
thirdStepPanel.add(btnStart);
btnStart.setEnabled(false);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMessage("Process started!");
}
});
//btnStart.setBackground(Color.RED);
btnStart.setForeground(Color.BLACK);
btnStart.setOpaque(false);
btnStart.setBorderPainted(false);
btnStart.setContentAreaFilled(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser("some folder blablabla");
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
//System.out.println(file.getPath());
textField.setText(file.getPath());
} else if (returnVal == JFileChooser.CANCEL_OPTION) {
//System.out.println("File dialog cancelled");
} else if (returnVal == JFileChooser.ERROR_OPTION) {
showMessage("Error in the file dialog!");
}
}
});
btnSelectAgent.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (list.getSelectedItems().length == 0) {
showMessage("Please, select an Agent in the Agent's list");
} else {
disableFirstStep();
enableSecondStep();
}
}
});
list.add("Zemax");
list.add("Roundspot");
list.add("CCDCamera");
list.add("HexapodXYTable");
/* this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.add(firstStepPanel, BorderLayout.WEST);
this.add(secondStepPanel, BorderLayout.CENTER);
this.add(thirdStepPanel, BorderLayout.EAST);*/
}
private void showMessage(String msg) {
JOptionPane.showMessageDialog(this, msg);
}
private void enableFirstStep() {
list.setEnabled(true);
btnSelectAgent.setEnabled(true);
}
private void enableSecondStep() {
textField.setEnabled(true);
btnBrowse.setEnabled(true);
btnPreviousStep2.setEnabled(true);
btnLoad.setEnabled(true);
}
private void enableThirdStep() {
btnPreviousStep3.setEnabled(true);
btnStart.setEnabled(true);
}
private void disableFirstStep() {
list.setEnabled(false);
btnSelectAgent.setEnabled(false);
}
private void disableSecondStep() {
textField.setEnabled(false);
btnBrowse.setEnabled(false);
btnPreviousStep2.setEnabled(false);
btnLoad.setEnabled(false);
}
private void disableThirdStep() {
btnPreviousStep3.setEnabled(false);
btnStart.setEnabled(false);
}
private void makeFrameFullSize(JPanel panel) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
panel.setSize(screenSize.width, screenSize.height);
}
BufferedImage image;
public void nextButton() {
try {
image = ImageIO.read(new File("C:\\Users\\BAYGONCALVE\\Desktop\\red_button.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawImage(image, 0, 0, null);
}
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
}
The main problem is, the frame isn't actually visible.
For example, after I cleaned up your code a little I get...
r1 = java.awt.Rectangle[x=1280,y=820,width=0,height=0]
r2 = java.awt.Rectangle[x=1280,y=820,width=0,height=0]
d1 = java.awt.Dimension[width=0,height=0]
d2 = java.awt.Dimension[width=0,height=0]
(took out the call to setBounds and few other things). Based on the fact that the window hasn't been realised yet (not shown), it's not surprising to me that the sizes don't actually change, because until you show the window, it has no context of which GraphicsDevice it will be shown on, therefore no means by which it can determine what the maximum size actually would be...
If you call setVisible(true) in the constructor, before calling setExtendedState(JFrame.MAXIMIZED_BOTH) I get...
r1 = java.awt.Rectangle[x=1214,y=801,width=132,height=38]
r2 = java.awt.Rectangle[x=-8,y=32,width=2576,height=1576]
d1 = java.awt.Dimension[width=132,height=38]
d2 = java.awt.Dimension[width=2576,height=1576]
Side notes...
Don't use null layouts. Pixel perfect layouts are an illusion in modern UI design, you have no control over fonts, DPI, rendering pipelines or other factors that will change the way that you components will be rendered on the screen. Swing was designed to work with layout managers to overcome these issues. If you insist on ignoring these features and work against the API design, be prepared for a lot of headaches and never ending hard work...
Don't mix heavy and light weight components, AWT and Swing components don't play well together, instead of using java.awt.List try using javax.swing.JList instead
Try this
frame.getWidth() and frame.getHeight()
To get size of JFrame without the title and other borders
frame.getContentPane().getSize();
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