Related
I need to divide java swing window into many fields, something similar to the table or chess board. Color of each cell should be dependent on the object which this cell represents (each object has coordinates, which are changing during the game, so the color of each cell is not constant).
Additionally, if the user clicks on the empty field (white color), then a new random object is created and this object is assigned to these field (and field color is changing).
Which of java swing controls will be the best for these functionalities?
If I were you I would make 2 panel classes(white and black), the white one with a MouseAdapter, so that when one of the panels is clicked you can pull a random JLabel from an array. Here's an example that might help (roughly 120 lines):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class ScratchPaper extends JFrame {
private static final long serialVersionUID = 1L;
private static final int GRIDSIZE = 8;
private JPanel[][] whitePanel = new WhitePanel[GRIDSIZE][GRIDSIZE];
private JPanel[][] blackPanel = new BlackPanel[GRIDSIZE][GRIDSIZE];
private Random rand = new Random();
JButton b1 = new JButton("Btn1");
JButton b2 = new JButton("Btn2");
JButton b3 = new JButton("Btn3");
JLabel l1 = new JLabel("Lbl1");
JLabel l2 = new JLabel("Lbl2");
JLabel l3 = new JLabel("Lbl3");
JPanel panel = new JPanel();
private JComponent[][] randObjects = {{b1, b2, b3}, {l1, l2, l3}, {panel, panel, panel}};
private Color[] randColors = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA};
public ScratchPaper() {
initGUI();
setTitle("EXAMPLE");
pack();
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void initGUI() {
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(GRIDSIZE, GRIDSIZE)); // makes 8*8 grid
add(centerPanel, BorderLayout.CENTER);
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Component clickedComp = findComponentAt(e.getPoint());
JPanel target = (JPanel) clickedComp;
panel.setBackground(randColors[rand.nextInt(randColors.length)]);
if (target instanceof WhitePanel){
target.add(randObjects[rand.nextInt(randObjects.length)][rand.nextInt(randObjects[0].length)]);
target.updateUI();
}
}
};
addMouseListener(ma);
for (int row=0; row<GRIDSIZE; row++) {
for (int col=0; col<GRIDSIZE; col++) {
whitePanel[row][col] = new WhitePanel(row, col);
blackPanel[row][col] = new BlackPanel(row, col);
if ((row%2 == 0 && col%2 == 0) || ((row+1)%2 == 0 && (col+1)%2 == 0)) {
centerPanel.add(whitePanel[row][col]);
}
else {
centerPanel.add(blackPanel[row][col]);
}
}
}
}
public static void main(String args[]) {
try {
String className = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(className);
} catch (Exception ex) {
System.out.println(ex);
}
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
new ScratchPaper();
}
});
}
class WhitePanel extends JPanel {
private static final int SIZE = 50;
public WhitePanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.WHITE);
}
}
class BlackPanel extends JPanel {
private static final int SIZE = 50;
public BlackPanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.BLACK);
}
}
}
Try running it! It's actually pretty fun!
After clicking on the JComboBox, JComboBox covers up some parts of the painting with grey rectangular shaped thing, is there something wrong with the code and how do I fix it? Thanks!
Here's the image.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.Box;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MouseButtonTester extends JFrame implements MouseMotionListener{
int x,y,r;
JComboBox colorChooser;
Color color;
JTextField red = new JTextField();
JTextField green = new JTextField();
JTextField blue = new JTextField();
JPanel topPanel = new JPanel();
JComboBox pen;
int fillKind;
Object[] chooseRGB = {
"Red: ", red,
"Green: ", green,
"Blue: ", blue
};
public MouseButtonTester(){
super();
this.addMouseMotionListener(this);
setResizable(true);
setLayout(new BorderLayout());
add(topPanel,BorderLayout.NORTH);
topPanel.setLayout(new GridLayout(1,2));
colorChooser = new JComboBox();
pen = new JComboBox();
topPanel.add(pen);
topPanel.add(colorChooser);
colorChooser.setBackground(Color.WHITE);
pen.setBackground(Color.WHITE);
pen.addItem("Pen");
pen.addItem("Marker");
pen.addItem("Highlighter");
pen.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(pen.getSelectedItem().toString().equals("Pen")){
fillKind = 0;
r = 8;
}else if(pen.getSelectedItem().toString().equals("Marker")){
fillKind = 0;
r = 15;
}else if(pen.getSelectedItem().toString().equals("Highlighter")){
fillKind = 1;
}
}
});
colorChooser.setFont(new Font("Serif",Font.PLAIN,14));
colorChooser.addItem("Red");
colorChooser.addItem("Orange");
colorChooser.addItem("Yellow");
colorChooser.addItem("Green");
colorChooser.addItem("Blue");
colorChooser.addItem("Violet");
colorChooser.addItem("Purple");
colorChooser.addItem("Choose RGB");
colorChooser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if("Red" == colorChooser.getSelectedItem().toString()){
color = Color.RED;
}else if("Orange" == colorChooser.getSelectedItem().toString()){
color = Color.ORANGE;
}else if("Yellow" == colorChooser.getSelectedItem().toString()){
color = Color.YELLOW;
}
else if("Green" == colorChooser.getSelectedItem().toString()){
color = Color.GREEN;
}
else if("Blue" == colorChooser.getSelectedItem().toString()){
color = Color.BLUE;
}
else if("Violet" == colorChooser.getSelectedItem().toString()){
color = new Color(180,0,200);
}
else if("Purple" == colorChooser.getSelectedItem().toString()){
color = new Color(150,0,200);
}
else if("Purple" == colorChooser.getSelectedItem().toString()){
}
else if("Choose RGB" == colorChooser.getSelectedItem().toString()){
int option = JOptionPane.showConfirmDialog(null, chooseRGB, "Choose RGB", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION){
int redValue = Integer.parseInt(red.getText());
int greenValue = Integer.parseInt(green.getText());
int blueValue = Integer.parseInt(blue.getText());
color = new Color(redValue,greenValue,blueValue);
}
}
}
});
}
Graphics graphics;
public void paint(Graphics g){
graphics = g.create();
}
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
graphics.setColor(color);
if(fillKind == 0){
graphics.fillOval(x, y, r, r);
}else if(fillKind == 1){
graphics.fillRect(x, y, 10, 25);
}
repaint();
}
public void mouseMoved(MouseEvent arg0) {
//No actions
}
}
If you look at your code carefully, the JComboBox drawn on JPanel it means drawn on drawing area.Simple way to fix this issue create two panel ; first one for tools (combobox)and add your other tools on, and another panel to drawing area.
Another way is after item choosed repaint your panel.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class BattleShip {
private static ImageIcon image1 = new ImageIcon("cols.png");
private static ImageIcon image2 = new ImageIcon("rows.png");
private static JMenuBar menubar = new JMenuBar();
private static JPanel container = new JPanel();
private static JButton[][] button = new JButton[10][10];
private static JFrame frame = new JFrame("BattleShip");
private static JButton open;
public static void fileMenu() {
JMenu fileMenu = new JMenu("File");
JMenuItem open = new JMenuItem("Open");
open.setMnemonic(KeyEvent.VK_O);
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_MASK));
JMenuItem restartGame = new JMenuItem("Restart Game");
restartGame.setMnemonic(KeyEvent.VK_R);
restartGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_MASK));
JMenuItem exit = new JMenuItem("Exit");
exit.setMnemonic(KeyEvent.VK_E);
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.CTRL_MASK));
open.addActionListener(new OpenMenu());
exit.addActionListener(new ExitMenu());
fileMenu.add(open);
fileMenu.add(restartGame);
fileMenu.add(exit);
menubar.add(fileMenu);
}
public static void layout() {
JPanel panelOne = new JPanel();
JPanel panelTwo = new JPanel();
JPanel playerPanel = new JPanel();
JPanel cpuPanel = new JPanel();
panelOne.add(playerPanel, BorderLayout.CENTER);
panelOne.setLayout(new BorderLayout());
panelTwo.setLayout(new BorderLayout());
panelOne.add(new JLabel(image1), BorderLayout.NORTH);
panelTwo.add(new JLabel(image1), BorderLayout.NORTH);
panelOne.add(new JLabel(image2), BorderLayout.WEST);
panelTwo.add(new JLabel(image2), BorderLayout.WEST);
panelOne.add(playerPanel, BorderLayout.CENTER);
container.setLayout(new GridLayout(1,2));
container.add(panelOne);
container.add(panelTwo);
}
public static void FlowLayout() {
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
JPanel playerSide = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
JLabel cols = new JLabel();
cols.setIcon(image1);
JLabel rows = new JLabel();
rows.setIcon(image2);
panel.add(cols);
}
public static void main(String[] args) {
fileMenu();
layout();
frame.add(container);
frame.setJMenuBar(menubar);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class ExitMenu implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private static class OpenMenu implements ActionListener {
public void actionPerformed(ActionEvent e) {
}
}
private static class SelectFile implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == open) {
}
}
}
}
How can I do this layout with the rows and cols as a picture?
For the cols how would i do the white space and combine the two together and make a grid? None of the other questions shows me how to do this layout?
[![enter image description here][1]][1]
Shoot, I made something just like that that I'll try to dig out....
Made a long while ago and used two jpg images to create a GUI like so:
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class BattleShipMainProg {
private static void createAndShowGui() {
BattleShipMainPanel mainPanel;
try {
mainPanel = new BattleShipMainPanel();
JFrame frame = new JFrame("Battleship");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class BattleShipMainPanel extends JPanel {
private static final int TA_ROWS = 10;
private static final int TA_COLS = 30;
private static final int CELL_SIDE_LENGTH = 36;
private static final String WEST_IMG_PATH = "battleship/images/Wallpaper-Picture-Under-Water Crp.jpg";
private static final String EAST_IMG_PATH = "battleship/images/Maldives_Sml.jpg";
private BattleShipGridPanel playerGrid;
private BattleShipGridPanel opponentGrid;
private ShipImageMaker imageMaker = new ShipImageMaker(CELL_SIDE_LENGTH);
private JTextArea textarea = new JTextArea(TA_ROWS, TA_COLS);
public BattleShipMainPanel() throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
System.out.println(classLoader.getResource("").getFile());
String westImgString = WEST_IMG_PATH;
String eastImgString = EAST_IMG_PATH;
BufferedImage westImg = ImageIO.read(getClass().getClassLoader()
.getResource(westImgString));
BufferedImage eastImg = ImageIO.read(getClass().getClassLoader()
.getResource(eastImgString));
playerGrid = new BattleShipGridPanel(westImg, CELL_SIDE_LENGTH);
opponentGrid = new BattleShipGridPanel(eastImg, CELL_SIDE_LENGTH);
// !! to delete
playerGrid.getLabel("A 1").setIcon(imageMaker.getSternLeftIcon()[0]);
playerGrid.getLabel("A 2").setIcon(imageMaker.getMidshipHorizIcon()[0]);
playerGrid.getLabel("A 3").setIcon(imageMaker.getMidshipHorizIcon()[0]);
playerGrid.getLabel("A 4").setIcon(imageMaker.getMidshipHorizIcon()[0]);
playerGrid.getLabel("A 5").setIcon(imageMaker.getBowRightIcon()[0]);
playerGrid.getLabel("C 2").setIcon(imageMaker.getBowUpIcon()[1]);
playerGrid.getLabel("D 2").setIcon(imageMaker.getMidshipVertIcon()[1]);
playerGrid.getLabel("E 2").setIcon(imageMaker.getSternDownIcon()[1]);
// !! to delete
playerGrid.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pChngEvt) {
if (pChngEvt.getPropertyName().equals(
BattleShipGridPanel.MOUSE_PRESSED)) {
textarea.append("Player: " + pChngEvt.getNewValue() + "\n");
System.out.printf("[%c, %d]%n", playerGrid.getSelectedRow(), playerGrid.getSelectedCol());
playerGrid.resetSelections();
}
}
});
opponentGrid.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pChngEvt) {
if (pChngEvt.getPropertyName().equals(
BattleShipGridPanel.MOUSE_PRESSED)) {
textarea.append("Opponent: " + pChngEvt.getNewValue() + "\n");
opponentGrid.resetSelections();
}
}
});
textarea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
textarea.setEditable(false);
textarea.setFocusable(false);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
JPanel centerTopPanel = new JPanel(new BorderLayout());
centerTopPanel.add(new JLabel("GridCell Pressed", SwingConstants.LEFT),
BorderLayout.NORTH);
centerTopPanel.add(new JScrollPane(textarea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
centerPanel.add(centerTopPanel);
centerPanel.add(Box.createVerticalGlue());
JPanel playerPanel = new JPanel(new BorderLayout());
playerPanel.add(new JLabel("Player", JLabel.LEFT),
BorderLayout.PAGE_START);
playerPanel.add(playerGrid.getMainPanel(), BorderLayout.CENTER);
JPanel opponentPanel = new JPanel(new BorderLayout());
opponentPanel.add(new JLabel("Opponent", JLabel.LEFT),
BorderLayout.PAGE_START);
opponentPanel.add(opponentGrid.getMainPanel(), BorderLayout.CENTER);
int eb = 10;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new BorderLayout(eb, eb));
add(playerPanel, BorderLayout.WEST);
add(opponentPanel, BorderLayout.EAST);
add(centerPanel, BorderLayout.CENTER);
}
}
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
#SuppressWarnings("serial")
public class BattleShipGridPanel {
public static final String MOUSE_PRESSED = "Mouse Pressed";
// public static final String MOUSE_DRAGGED = "Mouse Dragged";
private static final int ROW_COUNT = 11;
private static final int COL_COUNT = 11;
// the main JPanel for this part of my program
private JPanel mainPanel = new JPanel(){
// it draws an image if available
protected void paintComponent(Graphics g) {
super.paintComponent(g);
myPaint(g);
};
};
private Image img = null;
private String selectedCellName = "";
private JLabel selectedLabel = null;
private Map<String, JLabel> labelMap = new HashMap<String, JLabel>();
private SwingPropertyChangeSupport propChangeSupport = new SwingPropertyChangeSupport(this);
public BattleShipGridPanel(Image img, int cellSideLength) {
this.img = img;
mainPanel.setLayout(new GridLayout(11, 11));
mainPanel.setBorder(BorderFactory.createLineBorder(Color.black));
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
mainPanel.addMouseListener(myMouseAdapter);
for (int row = 0; row < ROW_COUNT; row++) {
for (int col = 0; col < COL_COUNT; col++) {
String rowStr = String.valueOf((char) ('A' + row - 1));
String colStr = String.valueOf(col);
String name = ""; // name for component
String text = ""; // text to display
// create JLabel to add to grid
JLabel label = new JLabel("", SwingConstants.CENTER);
// text to display if label is a row header at col 0
if (col == 0 && row != 0) {
text = "" + rowStr;
} else
// text to display if label is a col header at row 0
if (row == 0 && col != 0) {
text = "" + colStr;
} else
// name to give to label if label is on the grid and not a
// row or col header
if (row != 0 && col != 0) {
name = rowStr + " " + colStr;
labelMap.put(name, label);
}
label.setText(text);
label.setName(name);
label.setPreferredSize(new Dimension(cellSideLength, cellSideLength));
label.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(label);
}
}
}
private void myPaint(Graphics g) {
if (img != null) {
int w0 = mainPanel.getWidth();
int h0 = mainPanel.getHeight();
int x = w0 / 11;
int y = h0 / 11;
int iW = img.getWidth(null);
int iH = img.getHeight(null);
g.drawImage(img, x, y, w0, h0, 0, 0, iW, iH, null);
}
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propChangeSupport.addPropertyChangeListener(listener);
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent mEvt) {
if (mEvt.getButton() == MouseEvent.BUTTON1) {
Component comp = mainPanel.getComponentAt(mEvt.getPoint());
if (comp instanceof JLabel) {
String name = comp.getName();
if (!name.trim().isEmpty()) {
String oldValue = selectedCellName;
String newValue = name;
selectedCellName = name;
selectedLabel = (JLabel) comp;
propChangeSupport.firePropertyChange(MOUSE_PRESSED, oldValue, newValue);
}
}
}
}
}
public JPanel getMainPanel() {
return mainPanel;
}
public String getSelectedCellName() {
return selectedCellName;
}
public char getSelectedRow() {
if (selectedCellName.isEmpty()) {
return (char)0;
} else {
return selectedCellName.split(" ")[0].charAt(0);
}
}
public int getSelectedCol() {
if (selectedCellName.isEmpty()) {
return 0;
} else {
return Integer.parseInt(selectedCellName.split(" ")[1]);
}
}
public JLabel getSelectedLabel() {
return selectedLabel;
}
public void resetSelections() {
selectedCellName = "";
selectedLabel = null;
}
public JLabel getLabel(String key) {
return labelMap.get(key);
}
public void resetAll() {
resetSelections();
for (String key : labelMap.keySet()) {
labelMap.get(key).setIcon(null);
}
}
// for testing purposes only
private static void createAndShowGui() {
// path to some undersea image
String imgPath = "http://upload.wikimedia.org/wikipedia/"
+ "commons/3/31/Great_white_shark_south_africa.jpg";
BufferedImage img = null;
try {
img = ImageIO.read(new URL(imgPath));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
int cellSideLength = 36;
BattleShipGridPanel gridPanel = new BattleShipGridPanel(img, cellSideLength);
gridPanel.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
// print out where the mouse pressed:
System.out.println(evt.getNewValue());
}
});
JFrame frame = new JFrame("BattleShipGridPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(gridPanel.getMainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Path2D.Double;
import java.awt.geom.QuadCurve2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ShipImageMaker {
public static final double GAP = 1.0 / 10.0;
public static final Color LINE_COLOR = Color.black;
public static final Color[] SHIP_FILL_COLOR = { // Color.LIGHT_GRAY,
new Color(200, 200, 200, 180),
new Color(255, 100, 100, 180) };
public static final Color SHIP_BACKGROUND_COLOR = new Color(0, 0, 0, 0);
private AffineTransform rotateUp;
private ImageIcon[] bowRightIcon = new ImageIcon[2];
private ImageIcon[] bowUpIcon = new ImageIcon[2];
private ImageIcon[] sternLeftIcon = new ImageIcon[2];
private ImageIcon[] sternDownIcon = new ImageIcon[2];
private ImageIcon[] midshipHorizIcon = new ImageIcon[2];
private ImageIcon[] midshipVertIcon = new ImageIcon[2];
public ShipImageMaker(int side) {
rotateUp = AffineTransform.getQuadrantRotateInstance(3, side / 2,
side / 2);
Path2D turretPath = new Path2D.Double();
double tpX = side / 2.0 - 3 * GAP * side;
double tpY = side / 2.0 - 1.5 * GAP * side;
double tpW = 3 * GAP * side;
double tpH = tpW;
double lx1 = tpX + tpW;
double ly1 = side / 2.0 - 0.5 * GAP * side;
double lx2 = lx1 + 1.5 * GAP * side;
double ly2 = ly1;
turretPath.append(new Ellipse2D.Double(tpX, tpY, tpW, tpH), false);
turretPath.append(new Line2D.Double(lx1, ly1, lx2, ly2), false);
turretPath.append(new Line2D.Double(lx1, side - ly1, lx2, side - ly2),
false);
double y1 = GAP * side;
double ctrlx = side / 2.0;
double ctrly = y1;
double x2 = side - y1;
double y2 = side / 2.0;
QuadCurve2D topQC = new QuadCurve2D.Double(0, y1, ctrlx, ctrly, x2, y2);
QuadCurve2D botQC = new QuadCurve2D.Double(x2, y2, ctrlx, side - ctrly,
0, side - y1);
Path2D bowFillPath = new Path2D.Double();
bowFillPath.moveTo(0, y1);
bowFillPath.append(topQC, false);
bowFillPath.append(botQC, false);
bowFillPath.lineTo(0, y1);
Path2D bowDrawPath = new Path2D.Double();
bowDrawPath.append(topQC, false);
bowDrawPath.append(botQC, false);
bowDrawPath.append(turretPath, false);
Line2D midShipTopLine = new Line2D.Double(0, y1, side, y1);
Line2D midShipBotLine = new Line2D.Double(side, side - y1, 0, side - y1);
Path2D midShipFillPath = new Path2D.Double();
midShipFillPath.moveTo(0, y1);
midShipFillPath.append(midShipTopLine, false);
midShipFillPath.lineTo(side, side - y1);
midShipFillPath.append(midShipBotLine, false);
midShipFillPath.lineTo(0, y1);
Path2D midShipDrawPath = new Path2D.Double();
midShipDrawPath.append(midShipTopLine, false);
midShipDrawPath.append(midShipBotLine, false);
midShipDrawPath.append(turretPath, false);
Path2D sternDrawPath = new Path2D.Double();
sternDrawPath.moveTo(side, y1);
sternDrawPath.lineTo(side / 2, y1);
sternDrawPath.append(new CubicCurve2D.Double(side / 2, y1, y1, y1, y1,
side - y1, side / 2, side - y1), false);
sternDrawPath.lineTo(side, side - y1);
Path2D sternFillPath = new Path2D.Double(sternDrawPath);
sternFillPath.lineTo(side, y1);
sternDrawPath.append(turretPath.createTransformedShape(AffineTransform
.getQuadrantRotateInstance(2, side / 2, side / 2)), false);
for (int i = 0; i < bowRightIcon.length; i++) {
BufferedImage img = createImage(side, bowFillPath, bowDrawPath,
SHIP_FILL_COLOR[i]);
bowRightIcon[i] = new ImageIcon(img);
bowUpIcon[i] = rotateUp(side, img);
img = createImage(side, midShipFillPath, midShipDrawPath,
SHIP_FILL_COLOR[i]);
midshipHorizIcon[i] = new ImageIcon(img);
midshipVertIcon[i] = rotateUp(side, img);
img = createImage(side, sternFillPath, sternDrawPath,
SHIP_FILL_COLOR[i]);
sternLeftIcon[i] = new ImageIcon(img);
sternDownIcon[i] = rotateUp(side, img);
}
}
private BufferedImage createImage(int side, Path2D fillPath,
Path2D drawPath, Color shipFillColor) {
BufferedImage img = new BufferedImage(side, side,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(shipFillColor);
g2.setBackground(SHIP_BACKGROUND_COLOR);
g2.fill(fillPath);
g2.setColor(LINE_COLOR);
g2.setStroke(new BasicStroke(2f));
g2.draw(drawPath);
g2.dispose();
return img;
}
private ImageIcon rotateUp(int side, BufferedImage src) {
BufferedImage img = new BufferedImage(side, side,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setTransform(rotateUp);
g2.drawImage(src, 0, 0, null);
g2.dispose();
return new ImageIcon(img);
}
public ImageIcon[] getBowRightIcon() {
return bowRightIcon;
}
public ImageIcon[] getBowUpIcon() {
return bowUpIcon;
}
public ImageIcon[] getSternLeftIcon() {
return sternLeftIcon;
}
public ImageIcon[] getSternDownIcon() {
return sternDownIcon;
}
public ImageIcon[] getMidshipHorizIcon() {
return midshipHorizIcon;
}
public ImageIcon[] getMidshipVertIcon() {
return midshipVertIcon;
}
public static void main(String[] args) {
List<Icon> icons = new ArrayList<Icon>();
ShipImageMaker imgMaker = new ShipImageMaker(40);
icons.add(imgMaker.getBowRightIcon()[0]);
icons.add(imgMaker.getBowRightIcon()[1]);
icons.add(imgMaker.getBowUpIcon()[0]);
icons.add(imgMaker.getBowUpIcon()[1]);
icons.add(imgMaker.getMidshipHorizIcon()[0]);
icons.add(imgMaker.getMidshipHorizIcon()[1]);
icons.add(imgMaker.getMidshipVertIcon()[0]);
icons.add(imgMaker.getMidshipVertIcon()[1]);
icons.add(imgMaker.getSternDownIcon()[0]);
icons.add(imgMaker.getSternDownIcon()[1]);
icons.add(imgMaker.getSternLeftIcon()[0]);
icons.add(imgMaker.getSternLeftIcon()[1]);
for (Icon icon : icons) {
JOptionPane.showMessageDialog(null, new JLabel(icon));
}
}
}
Used BorderLayout, GridLayout and BoxLayout.
A lot will come down to what it is you want to achieve, for example you could use a GridLayout, GridBagLayout or a combination of layout managers or you could use custom painting or you could use a JTable for example...
Now, this is pretty basic and is only intended to provide a proof of concept
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
public MainPane() {
setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel(10, 10);
JTable table = new JTable(model);
table.setRowHeight(40);
table.setShowGrid(true);
table.setGridColor(Color.BLACK);
JScrollPane sp = new JScrollPane(table);
sp.setRowHeaderView(new RowHeader(table));
add(sp);
}
}
public class RowHeader extends JPanel {
private JTable table;
public RowHeader(JTable table) {
setOpaque(false);
this.table = table;
table.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
prepareLayout();
}
});
setLayout(new GridBagLayout());
prepareLayout();
}
protected void prepareLayout() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.CENTER;
Border border = new MatteBorder(0, 1, 1, 1, Color.BLACK);
for (int row = 0; row < 10; row++) {
char value = (char) ('A' + row);
JLabel label = makeLabel(Character.toString(value));
label.setBorder(border);
add(label, gbc);
}
gbc.weighty = 1;
JLabel filler = makeLabel("");
filler.setBorder(new MatteBorder(1, 0, 0, 0, Color.BLACK));
add(filler, gbc);
}
protected JLabel makeLabel(String text) {
JLabel label = new JLabel(text) {
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.height = table.getRowHeight();
size.width += 10;
return size;
}
};
label.setHorizontalAlignment(JLabel.CENTER);
return label;
}
}
}
Use BorderLayout, take 3 panel and set them in NORTH, CENTER and SOUTH. IN CENTER use JTable. to diaplay your table and if you want to add the alphabet also between two tables you can split your center panel by adding sub panels in the center panel.
like center_panel.add(subpanel1, and your desire location), or simply go through flow layout.
I'm trying to create a GUI where I can create custom colors. I have a feature that lets the user preview the color before submitting the color. I can't get the Icon to display at all. The actual problem is in my ColorFrame class. The color Icon(a JLabel, color) is created in the actionperformed() method.
The code that creates the Icon(The ButtonListener class):
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ColorFrame extends JFrame implements ActionListener {
private JPanel colorPanel;
private JPanel labelPanel;
private JPanel buttonPanel;
private JLabel labelRed;
private JLabel labelGreen;
private JLabel labelBlue;
private JLabel color;
private JTextField redField;
private JTextField greenField;
private JTextField blueField;
private JButton preview;
private JButton submit;
private int redInt;
private int blueInt;
private int greenInt;
private int width = 30;
private int height = 30;
public ColorFrame(int x, int y)
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //closes all frames for some reason
this.pack();
this.setLocation(x, y);
buttonPanel = new JPanel();
this.getContentPane().add(buttonPanel,BorderLayout.SOUTH);
preview = new JButton("Preview Color");
preview.addActionListener(new ButtonListener());
buttonPanel.add(preview);
createColorPanel();
createLabelPanel();
this.setVisible(true);
}
class ButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
//in the gui, there are three jtextfieilds that represent color values. the first is red, the second is green, and the last is blue.
redInt = Integer.parseInt(redField.getText());
greenInt = Integer.parseInt(greenField.getText());
blueInt = Integer.parseInt(blueField.getText());
color = new JLabel(new ColorIcon(redInt,greenInt,blueInt));
buttonPanel.add(color,BorderLayout.SOUTH);
print(redInt,greenInt, blueInt);
}
}
private void createColorPanel()
{
colorPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//creates the three textfields to input rgb values.
//the first is r, second, b third g
redField = new JTextField(2);
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(10,0,0,10);
colorPanel.add(redField,c);
greenField = new JTextField(2);
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 1;
colorPanel.add(greenField,c);
blueField = new JTextField(2);
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 2;
colorPanel.add(blueField,c);
redField.addActionListener(this);
greenField.addActionListener(this);
blueField.addActionListener(this);
this.add(colorPanel, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent arg0) {
redInt = Integer.parseInt(redField.getText());
greenInt = Integer.parseInt(greenField.getText());
blueInt = Integer.parseInt(blueField.getText());
// creates the color icon. It works sometimes, but not every time.
color = new JLabel(new ColorIcon(redInt,greenInt,blueInt));
buttonPanel.add(color);
print(redInt,greenInt, blueInt);
}
private void print(int a, int b, int c)
{
// just to see if the actionperformed() method works.
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
public Dimension getPreferredSize() {
return new Dimension(300,300);
}
public static void main(String[] args)
{
ColorFrame frame = new ColorFrame(200,200);
}
}
Color Icon class:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.Icon;
public class ColorIcon implements Icon{
private final int size = 30;
private int red;
private int green;
private int blue;
public ColorIcon(int r, int g, int b)
{
this.red = r;
this.green = g;
this.blue = b;
}
#Override
public int getIconHeight() {
// TODO Auto-generated method stub
return size;
}
#Override
public int getIconWidth() {
// TODO Auto-generated method stub
return size;
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
// TODO Auto-generated method stub
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double square = new Rectangle2D.Double(50, 50, size, size);
g2.setColor(new Color(red,green,blue));
g2.fill(square);
}
}
There are a number of possible ways you can handle this. One is to create a panel where you can set the color and paint the entire panel. Something like
private class ColorPanel extends JPanel {
private Color color = Color.BLUE;
public void setColor(Color color) {
this.color = color;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
}
You can just set the color. Another thing I noticed is that you are trying to add the new label to the button panel, but the button panel is in the south of the frame. I think you want the label in the center of the frame. So you would add the new label to the CENTER by itself, and not to the button panel.
Here's a refactor of your code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class ColorFrame extends JFrame implements ActionListener {
private JPanel colorPanel;
private JPanel buttonPanel;
private JLabel color;
private JTextField redField;
private JTextField greenField;
private JTextField blueField;
private JButton preview;
private int redInt;
private int blueInt;
private int greenInt;
private ColorPanel cPanel = new ColorPanel();
public ColorFrame(int x, int y) {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
JPanel preferredSizeWrapper = new JPanel(new GridBagLayout());
preferredSizeWrapper.add(cPanel);
this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
preview = new JButton("Preview Color");
preview.addActionListener(new ButtonListener());
buttonPanel.add(preview);
createColorPanel();
this.add(preferredSizeWrapper);
this.pack();
this.setLocation(x, y);
this.setVisible(true);
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
// in the gui, there are three jtextfieilds that represent color
// values. the first is red, the second is green, and the last is
// blue.
redInt = Integer.parseInt(redField.getText());
greenInt = Integer.parseInt(greenField.getText());
blueInt = Integer.parseInt(blueField.getText());
// new ColorIcon(redInt, greenInt, blueInt)
cPanel.setColor(new Color(redInt, greenInt, blueInt));
}
}
private class ColorPanel extends JPanel {
private Color color = Color.BLUE;
public void setColor(Color color) {
this.color = color;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
}
private void createColorPanel() {
colorPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// creates the three textfields to input rgb values.
// the first is r, second, b third g
redField = new JTextField(2);
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(10, 0, 0, 10);
colorPanel.add(redField, c);
greenField = new JTextField(2);
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 1;
colorPanel.add(greenField, c);
blueField = new JTextField(2);
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 2;
colorPanel.add(blueField, c);
redField.addActionListener(this);
greenField.addActionListener(this);
blueField.addActionListener(this);
this.add(colorPanel, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent arg0) {
redInt = Integer.parseInt(redField.getText());
greenInt = Integer.parseInt(greenField.getText());
blueInt = Integer.parseInt(blueField.getText());
colorPanel.add(color);
}
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorFrame frame = new ColorFrame(200, 200);
}
});
}
}
Another Option is just use a regular JPanel
private JPanel createCPanel() {
return new JPanel() {
{
setBackground(Color.BLUE);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(150, 150);
}
};
}
and just call setBackground(Color) on the panel. You need to keep in mind the above changes also though.
Instead of creating the color icon try using setting the background color to what you want and then set the size of the label.
I have a program which should has splash screen on JPanel, after button click should show another JPanel (object of the class) and draw shapes. I tried remove splash JPanel and after that add JPanel for drawing but it doeesn't work. How can I fix it? Two JLabel should be in the center of screen and it should be on 2 lines.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JComponent;
/**
*
* #author Taras
*/
public class MyComponent extends JComponent {
int i;
Color randColor;
public MyComponent()
{
this.i = i;
addMouseListener(new MouseHandler());
}
private ArrayList<Rectangle2D> arrOfRect=new ArrayList<>();
private ArrayList<Ellipse2D> arrOfEllipse=new ArrayList<>();
// private ArrayList<Color> randColor = new ArrayList<>();
Random rand = new Random();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle2D r : arrOfRect) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(r);
}
for (Ellipse2D e : arrOfEllipse) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(e);
}
}
public void add(Point2D p)
{
double x=p.getX();
double y=p.getY();
if (Pole.i == 1){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,100);
//randColor = new Color(randRed(), randGreen(), randBlue());
arrOfEllipse.add(ellipse);
}
if (Pole.i == 2){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 100, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 3){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 150, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 4){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,50);
arrOfEllipse.add(ellipse);
}
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent event)
{
add(event.getPoint());
//Color rColor = new Color(randRed(), randGreen(), randBlue());
//randColor.add(rColor);
repaint();
}
}
private int randRed() {
int red;
Random randomNumber = new Random();
red = randomNumber.nextInt(255);
return red;
}
private int randGreen() {
int green;
Random randomNumber = new Random();
green = randomNumber.nextInt(255);
return green;
}
private int randBlue() {
int blue;
Random randomNumber = new Random();
blue = randomNumber.nextInt(255);
return blue;
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import org.omg.CosNaming.NameComponent;
public class Pole extends JFrame {
public static int i;
public static JPanel nameContainer = new JPanel(new GridLayout(2, 1));
public static JFrame frame= new JFrame("Shape Stamper!");
public static void main(String[] args) {
JPanel container;
JButton circle = new JButton("Circle");
JButton square = new JButton("Square");
JButton rectangle = new JButton("Rectangle");
JButton oval = new JButton("Oval");
JLabel programName = new JLabel("Shape Stamper!");
JLabel programmerName = new JLabel("Progrramed by: ");
Font font = new Font("Serif", Font.BOLD, 32);
programName.setFont(font);
font = new Font("Serif", Font.ITALIC, 16);
programmerName.setFont(font);
programName.setHorizontalAlignment(JLabel.CENTER);
programmerName.setHorizontalAlignment(JLabel.CENTER);
//programmerName.setVerticalAlignment(JLabel.CENTER);
// nameContainer.setLayout(new BorderLayout());
nameContainer.add(programName);
nameContainer.add(programmerName);
//nameContainer.setLayout(new BoxLayout(nameContainer, BoxLayout.X_AXIS));
container = new JPanel(new GridLayout(1, 4));
container.add(circle);
container.add(square);
container.add(rectangle);
container.add(oval);
circle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 1;
frame.remove(nameContainer);
frame.repaint();
System.out.println(i);
}
});
square.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 2;
}
});
rectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 3;
}
});
oval.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 4;
}
});
MyComponent shape = new MyComponent();
frame.setSize(500, 500);
frame.add(shape, BorderLayout.CENTER);
frame.add(container, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here's an example of making a splash screen using an image.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
public class CircleSplashScreen {
public CircleSplashScreen() {
JFrame frame = new JFrame();
frame.getContentPane().add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleSplashScreen();
}
});
}
#SuppressWarnings("serial")
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setOpaque(false);
setLayout(new GridBagLayout());
try {
img = ImageIO.read(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
} catch (IOException ex) {
Logger.getLogger(CircleSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}