Add a button over image - java

How can I add a button over an image created with JLabel?
Even if I put the same coordinates on ".setbounds" the image usually gets behind the buttons.
public class Tatica extends JFrame {
JPanel jl = new JPanel();
JLabel jp = new JLabel();
public Tatica(){
jl.setLayout(null);
jp.setIcon(new ImageIcon("C:\\Users\\LG\\workspace\\Teste\\src\\snippet\\asdiuashd.Jpg"));
jl.add(jp);
add(jl);
jp.setBounds(100, 0, 1000, 1000);
validate();
JButton team2 = new JButton("Gk");
jl.add(team2);
team2.setBounds(400, 0, 100, 20);
team2.setVisible(true);
team2.setLayout(null);
JButton dc = new JButton("Dc");
jl.add(dc);
dc.setBounds(300, 200, 100, 20);
dc.setVisible(true);
JButton dc2 = new JButton("Dc");
jl.add(dc2);
dc2.setBounds(500, 200, 100, 20);
dc2.setVisible(true);
JButton dl = new JButton("Dl");
jl.add(dl);
dl.setBounds(100, 200, 100, 20);
dl.setVisible(true);
JButton dr = new JButton("Dr");
jl.add(dr);
dr.setBounds(700, 200, 100, 20);
dr.setVisible(true);
}
}

I'd instead slice up the image and use the sub-images as icons for either buttons or labels. Then arrange them all in a GridBagLayout.
Here is an example of what I mean (special thanks to #camickr for solving the bug in my layout code!):
(It uses a an icon with a transparent shade of white for mouse hover, black for pressed. The mouse was pointing at the left center forward when the screen shot was taken. It is left as an exercise for the reader to implement the logic needed to alternate between labels and buttons as required, in the GUI formed from 81 sub images.)
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
import javax.imageio.ImageIO;
public class SoccerField {
private JPanel ui = null;
int[] x = {0, 35, 70, 107, 142, 177, 212, 247, 282, 315};
int[] y = {0, 45, 85, 140, 180, 225, 265, 280, 320, 345};
Color brighter = new Color(255,255,255,92);
Color darker = new Color(0,0,0,92);
SoccerField() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new GridBagLayout());
ui.setBackground(Color.RED);
try {
URL url = new URL("http://i.stack.imgur.com/9E5ky.jpg");
BufferedImage img = ImageIO.read(url);
BufferedImage field = img.getSubimage(100, 350, 315, 345);
BufferedImage[] bi = subSampleImageColumns(field);
BufferedImage[][] fieldParts = new BufferedImage[bi.length][];
for (int ii=0; ii<bi.length; ii++) {
fieldParts[ii] = subSampleImageRows(bi[ii]);
}
for (int ii=0; ii<fieldParts[0].length; ii++) {
for (int jj=0; jj<fieldParts.length; jj++) {
addImageToPanel(ui, fieldParts[ii][jj], ii, jj);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void addImageToPanel(
JPanel panel, BufferedImage img, int row, int col) {
Insets insets = new Insets(0,0,0,0);
double weighty = img.getHeight()==40 ? .5 : .1;
GridBagConstraints gbc = new GridBagConstraints(
row, col,
1, 1,
.5, weighty,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
insets, 0, 0);
ImageIcon ii = new ImageIcon(img);
JButton b = new JButton(ii);
b.setRolloverIcon(new ImageIcon(getFadeImage(img, brighter)));
b.setPressedIcon(new ImageIcon(getFadeImage(img, darker)));
b.setBorder(null);
b.setBorder(new EmptyBorder(0, 0, 0, 0));
b.setBorderPainted(false);
b.setContentAreaFilled(false);
b.setFocusPainted(false);
panel.add(b, gbc);
}
private BufferedImage[] subSampleImageColumns(BufferedImage img) {
BufferedImage[] imageRows = new BufferedImage[x.length - 1];
for (int ii = 0; ii < x.length - 1; ii++) {
BufferedImage bi = img.getSubimage(
x[ii], 0, x[ii + 1] - x[ii], img.getHeight());
imageRows[ii] = bi;
}
return imageRows;
}
private BufferedImage[] subSampleImageRows(BufferedImage img) {
BufferedImage[] imageRows = new BufferedImage[y.length - 1];
for (int ii = 0; ii < y.length - 1; ii++) {
BufferedImage bi = img.getSubimage(
0, y[ii], img.getWidth(), y[ii + 1] - y[ii]);
imageRows[ii] = bi;
}
return imageRows;
}
private BufferedImage getFadeImage(BufferedImage img, Color clr) {
BufferedImage bi = new BufferedImage(
img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(img, 0, 0, ui);
g.setColor(clr);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.dispose();
return bi;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
SoccerField o = new SoccerField();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

How can I add a button over an image created with JLabel?
Add the buttons to the label, not the panel.
So the basic code is:
JPanel panel = new JPanel();
JLabel label = new JLabel( new ImageIcon(...) );
label.setLayout( new FlowLayout() );
JButton button1 = new JButton("Button1");
label.add(button1);
JButton button2 = new JButton("Button1");
label.add(button2);
So now the label will be the size of the image. The buttons will be displayed in a FlowLayout on the image. It is your responsibility to make sure the buttons fit on the image or the buttons will not be displayed properly.
The question is do you really need to add the label to the panel or should you just add the label to the frame?

Related

Blink boxes in sequence

I changed a program (see below) I nabbed and have managed to get it to do some of what I want. I need a number of rows/bands/stripes of 3 to blink in sequence. If you could imagine three sets of three vertical bars/bands and each bar numbered 1-3. I want to get each band/bar numbered 1 of each group to blink. So all bands numbered 1 blinks for a finite time, then bands numbered 2, then 3 then repeat. So when looking at it it looks like vertical stripes blinking 1,2,3,1,2,3 etc.
What's set out below and what I have described as boxes below refers to the bands I am talking about
class BelishN {
private Timer timer;
public class Drawing extends JPanel {
private int x = 125;// Not required - it was for the ball!
private int y = 80;
private boolean changeColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(1, 1, 10, 770);
//Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(10, 1, 10, 770);
//Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(20, 1, 10, 770);
// Rectangle box6 = new Rectangle(165, 405, 20, 45);
//drawing the shapes
//Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
//g2.draw(ball);
g2.draw(box1);
//g2.draw(box2);
//g2.draw(box3);
//g2.draw(box4);
//g2.draw(box5);
//g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.ORANGE);
//g2.fill(ball);
changeColors = !changeColors;
if (changeColors) {
g2.setColor(Color.white);
//g2.fill(new Ellipse2D.Double(x, y, 100, 100));
g2.fill(box1 = new Rectangle(1, 1, 10, 770));//3 vertical bands are flashing together
g2.fill(box3 = new Rectangle(10, 1, 10, 770));
g2.fill(box5 = new Rectangle(20, 1, 10, 770));
}
}
public void changeColors() {
changeColors = true;
repaint();
}
}
public BelishN() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(800, 770); //Screen size
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
shapes.repaint();
}
});
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
//Positioning
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// in last line here, start the timer:
timer.start();
}
public static void main(String[] args) {
new BelishN();
}
}

How do you add graphics to a different panel in Java

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.

Getting new bound values from JFrame (Java)

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();

JPanel Inside Of A JPanel

I am trying to get a JPanel to appear inside of another JPanel. Currently, the JPanel is in an external JFrame and loads with my other JFrame. I want the JPanel to be inside the other JPanel so the program does not open two different windows.
Here is a picture:
The small JPanel with the text logs I want inside of the main game frame. I've tried adding the panel to the panel, panel.add(othePanel). I've tried adding it the JFrame, frame.add(otherPanel). It just overwrites everything else and gives it a black background.
How can I add the panel, resize, and move it?
Edits:
That is where I want the chatbox to be.
Class code:
Left out top of class.
public static JPanel panel;
public static JTextArea textArea = new JTextArea(5, 30);
public static JTextField userInputField = new JTextField(30);
public static void write(String message) {
Chatbox.textArea.append("[Game]: " + message + "\n");
Chatbox.textArea.setCaretPosition(Chatbox.textArea.getDocument()
.getLength());
Chatbox.userInputField.setText("");
}
public Chatbox() {
panel = new JPanel();
panel.setPreferredSize(new Dimension(220, 40));
panel.setBackground(Color.BLACK);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(380, 100));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
scrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
userInputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String fromUser = userInputField.getText();
if (fromUser != null) {
textArea.append(Frame.username + ":" + fromUser + "\n");
textArea.setCaretPosition(textArea.getDocument()
.getLength());
userInputField.setText("");
}
}
});
panel.add(userInputField, SwingConstants.CENTER);
panel.add(scrollPane, SwingConstants.CENTER);
//JFrame frame = new JFrame();
//frame.add(panel);
//frame.setSize(400, 170);
//frame.setVisible(true);
}
Main frame class:
public Frame() {
frame.getContentPane().remove(loginPanel);
frame.repaint();
String capName = capitalizeString(Frame.username);
name = new JLabel(capName);
new EnemyHealth("enemyhealth10.png");
new Health("health10.png");
new LoadRedCharacter("goingdown.gif");
new Spellbook();
new LoadMobs();
new LoadItems();
new Background();
new Inventory();
new ChatboxInterface();
frame.setBackground(Color.black);
Frame.redHealthLabel.setFont(new Font("Serif", Font.PLAIN, 20));
ticks.setFont(new Font("Serif", Font.PLAIN, 20));
ticks.setForeground(Color.yellow);
Frame.redHealthLabel.setForeground(Color.black);
// Inventory slots
panel.add(slot1);
panel.add(name);
name.setFont(new Font("Serif", Font.PLAIN, 20));
name.setForeground(Color.white);
panel.add(enemyHealthLabel);
panel.add(redHealthLabel);
panel.add(fireSpellBookLabel);
panel.add(iceSpellBookLabel);
panel.add(spiderLabel);
panel.add(appleLabel);
panel.add(fireMagicLabel);
panel.add(swordLabel);
// Character
panel.add(redCharacterLabel);
// Interface
panel.add(inventoryLabel);
panel.add(chatboxLabel);
// Background
panel.add(backgroundLabel);
frame.setContentPane(panel);
frame.getContentPane().invalidate();
frame.getContentPane().validate();
frame.getContentPane().repaint();
//I WOULD LIKE THE LOADING OF THE PANEL SOMEWHERE IN THIS CONSTRUCTOR.
new ResetEntities();
frame.repaint();
panel.setLayout(null);
Run.loadKeyListener();
Player.px = Connect.x;
Player.py = Connect.y;
new Mouse();
TextualMenu.rect = new Rectangle(Frame.inventoryLabel.getX() + 80,
Frame.inventoryLabel.getY() + 100,
Frame.inventoryLabel.getWidth(),
Frame.inventoryLabel.getHeight());
Player.startMessage();
}
Don't use static variables.
Don't use a null layout.
Use appropriate layout managers. Maybe the main panel uses a BorderLayout. Then you add your main component to the CENTER and a second panel to the EAST. The second panel can also use a BorderLayout. You can then add the two components to the NORTH, CENTER or SOUTH as you require.
For example, using a custom Border:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.RadialGradientPaint;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
#SuppressWarnings("serial")
public class FrameEg extends JPanel {
public static final String FRAME_URL_PATH = "http://th02.deviantart.net/"
+ "fs70/PRE/i/2010/199/1/0/Just_Frames_5_by_ScrapBee.png";
public static final int INSET_GAP = 120;
private BufferedImage frameImg;
private BufferedImage smlFrameImg;
public FrameEg() {
try {
URL frameUrl = new URL(FRAME_URL_PATH);
frameImg = ImageIO.read(frameUrl);
final int smlFrameWidth = frameImg.getWidth() / 2;
final int smlFrameHeight = frameImg.getHeight() / 2;
smlFrameImg = new BufferedImage(smlFrameWidth, smlFrameHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics g = smlFrameImg.getGraphics();
g.drawImage(frameImg, 0, 0, smlFrameWidth, smlFrameHeight, null);
g.dispose();
int top = INSET_GAP;
int left = top;
int bottom = top;
int right = left;
Insets insets = new Insets(top, left, bottom, right);
MyBorder myBorder = new MyBorder(frameImg, insets);
JTextArea textArea = new JTextArea(50, 60);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
for (int i = 0; i < 300; i++) {
textArea.append("Hello world! How is it going? ");
}
setLayout(new BorderLayout(1, 1));
setBackground(Color.black);
Dimension prefSize = new Dimension(frameImg.getWidth(),
frameImg.getHeight());
JPanel centerPanel = new MyPanel(prefSize);
centerPanel.setBorder(myBorder);
centerPanel.setLayout(new BorderLayout(1, 1));
centerPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
MyPanel rightUpperPanel = new MyPanel(new Dimension(smlFrameWidth,
smlFrameHeight));
MyPanel rightLowerPanel = new MyPanel(new Dimension(smlFrameWidth,
smlFrameHeight));
top = top / 2;
left = left / 2;
bottom = bottom / 2;
right = right / 2;
Insets smlInsets = new Insets(top, left, bottom, right);
rightUpperPanel.setBorder(new MyBorder(smlFrameImg, smlInsets));
rightUpperPanel.setLayout(new BorderLayout());
rightLowerPanel.setBorder(new MyBorder(smlFrameImg, smlInsets));
rightLowerPanel.setBackgroundImg(createBackgroundImg(rightLowerPanel
.getPreferredSize()));
JTextArea ruTextArea1 = new JTextArea(textArea.getDocument());
ruTextArea1.setWrapStyleWord(true);
ruTextArea1.setLineWrap(true);
rightUpperPanel.add(new JScrollPane(ruTextArea1), BorderLayout.CENTER);
JPanel rightPanel = new JPanel(new GridLayout(0, 1, 1, 1));
rightPanel.add(rightUpperPanel);
rightPanel.add(rightLowerPanel);
rightPanel.setOpaque(false);
add(centerPanel, BorderLayout.CENTER);
add(rightPanel, BorderLayout.EAST);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private BufferedImage createBackgroundImg(Dimension preferredSize) {
BufferedImage img = new BufferedImage(preferredSize.width,
preferredSize.height, BufferedImage.TYPE_INT_ARGB);
Point2D center = new Point2D.Float(img.getWidth()/2, img.getHeight()/2);
float radius = img.getWidth() / 2;
float[] dist = {0.0f, 1.0f};
Color centerColor = new Color(100, 100, 50);
Color outerColor = new Color(25, 25, 0);
Color[] colors = {centerColor , outerColor };
RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
Graphics2D g2 = img.createGraphics();
g2.setPaint(paint);
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
g2.dispose();
return img;
}
private static void createAndShowGui() {
FrameEg mainPanel = new FrameEg();
JFrame frame = new JFrame("FrameEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class MyPanel extends JPanel {
private Dimension prefSize;
private BufferedImage backgroundImg;
public MyPanel(Dimension prefSize) {
this.prefSize = prefSize;
}
public void setBackgroundImg(BufferedImage background) {
this.backgroundImg = background;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
return prefSize;
}
}
#SuppressWarnings("serial")
class MyBorder extends AbstractBorder {
private BufferedImage borderImg;
private Insets insets;
public MyBorder(BufferedImage borderImg, Insets insets) {
this.borderImg = borderImg;
this.insets = insets;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height) {
g.drawImage(borderImg, 0, 0, c);
}
#Override
public Insets getBorderInsets(Component c) {
return insets;
}
}
Which would look like:

Icon is not set right on GlassPane

I have a class that sets warning icons behind a textField when the input is different from what i expect form the user. For textfield this class works perfect, but when i'm trying to use it with a textArea the warning icons aren't set on the right location .
here is the class that sets and removes the warning icons:
public class GlassValidationPane extends JComponent {
private HashMap<Component, JLabel> warningLabels = new HashMap<>();
private ImageIcon warningIcon;
private final ImageUtilities iU = new ImageUtilities();
public GlassValidationPane() {
setLayout(null);
setOpaque(false);
Icon icon = UIManager.getIcon("OptionPane.warningIcon");
int imgW = icon.getIconWidth();
int imgH = icon.getIconHeight();
BufferedImage img = iU.getBufferedImageOfIcon(icon, imgW, imgH);
warningIcon = new ImageIcon(iU.resize(img, 18, 18));
}
void showWarningIcon(Component c) {
if (warningLabels.containsKey(c)) {
return;
}
JLabel label = new JLabel();
label.setIcon(warningIcon);
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() + c.getX() + label.getIcon().getIconWidth();//this makes it appear outside/next to component);
int y = c.getY();
System.out.println("ïn show warning: " + y);
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
add(label);
label.setVisible(true);
revalidate();
repaint();
warningLabels.put(c, label);
}
public void removeWarningIcon(Component c) {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component component = entry.getKey();
JLabel jLabel = entry.getValue();
if (component == c) {
remove(jLabel);
revalidate();
repaint();
break;
}
}
warningLabels.remove(c);
}
public void refreshLocations() {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component c = entry.getKey();
JLabel label = entry.getValue();
int x = c.getWidth() + c.getX() + label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
revalidate();
repaint();
}
}
public boolean allSet(){
if(!warningLabels.isEmpty()){
JOptionPane.showMessageDialog(null, "Please fill every text field in, or adjust te wrong input", "Empty input/Wrong input", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private class ImageUtilities {
public BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
public BufferedImage getBufferedImageOfIcon(Icon icon, int imgW, int imgH) {
BufferedImage img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return img;
}
}
}
I have found that the getY() function for the textArea always gives 0 back, but i can't find why it always return 0. here is the code who calls the class ClaxxValidationPane:
public class JobInput extends JFrame {
private JPanel contentPane;
private JTextField txtJobId;
private GlassValidationPane gvp;
private JTextArea textAreaDesription;
private boolean INSERT;
/**
* Create the frame.
*/
public JobInput(String titel, boolean INSERT) {
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
}
});
setBounds(100, 100, 296, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblTitel = new JLabel(titel);
lblTitel.setFont(new Font("Arial", Font.BOLD, 15));
GridBagConstraints gbc_lblTitel = new GridBagConstraints();
gbc_lblTitel.gridwidth = 2;
gbc_lblTitel.insets = new Insets(0, 0, 5, 0);
gbc_lblTitel.gridx = 0;
gbc_lblTitel.gridy = 0;
contentPane.add(lblTitel, gbc_lblTitel);
JSeparator separator = new JSeparator();
GridBagConstraints gbc_separator = new GridBagConstraints();
gbc_separator.fill = GridBagConstraints.BOTH;
gbc_separator.gridwidth = 2;
gbc_separator.insets = new Insets(0, 0, 5, 0);
gbc_separator.gridx = 0;
gbc_separator.gridy = 1;
contentPane.add(separator, gbc_separator);
JLabel lblJobid = new JLabel("JobID");
GridBagConstraints gbc_lblJobid = new GridBagConstraints();
gbc_lblJobid.anchor = GridBagConstraints.EAST;
gbc_lblJobid.insets = new Insets(0, 0, 5, 5);
gbc_lblJobid.gridx = 0;
gbc_lblJobid.gridy = 2;
contentPane.add(lblJobid, gbc_lblJobid);
txtJobId = new JTextField();
GridBagConstraints gbc_txtJobId = new GridBagConstraints();
gbc_txtJobId.insets = new Insets(0, 0, 5, 0);
gbc_txtJobId.fill = GridBagConstraints.HORIZONTAL;
gbc_txtJobId.gridx = 1;
gbc_txtJobId.gridy = 2;
contentPane.add(txtJobId, gbc_txtJobId);
txtJobId.setColumns(10);
JLabel lblDescription = new JLabel("Description");
GridBagConstraints gbc_lblDescription = new GridBagConstraints();
gbc_lblDescription.anchor = GridBagConstraints.NORTH;
gbc_lblDescription.insets = new Insets(0, 0, 5, 5);
gbc_lblDescription.gridx = 0;
gbc_lblDescription.gridy = 3;
contentPane.add(lblDescription, gbc_lblDescription);
textAreaDesription = new JTextArea();
textAreaDesription.setLineWrap(true);
textAreaDesription.setWrapStyleWord(true);
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.insets = new Insets(0, 0, 5, 0);
gbc_textArea.fill = GridBagConstraints.BOTH;
gbc_textArea.gridx = 1;
gbc_textArea.gridy = 3;
JScrollPane scroll = new JScrollPane (textAreaDesription,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scroll, gbc_textArea);
JButton btnOk = new JButton("Ok");
GridBagConstraints gbc_btnOk = new GridBagConstraints();
gbc_btnOk.gridwidth = 2;
gbc_btnOk.gridx = 0;
gbc_btnOk.gridy = 4;
contentPane.add(btnOk, gbc_btnOk);
gvp = new GlassValidationPane();
FocusAdapter fl = new FocusAdapter() {
#Override
public void focusGained(FocusEvent fe) {
super.focusGained(fe);
((JTextComponent) fe.getSource()).setBorder(BorderFactory.createLineBorder(Color.gray));
}
public void focusLost(FocusEvent fe) {
super.focusLost(fe);
if(fe.getSource().equals(txtJobId)){
validationForInteger(txtJobId);
} else if(fe.getSource().equals(textAreaDesription)){
validationForText(textAreaDesription);
} else{
gvp.removeWarningIcon(((Component) fe.getSource()));
((JTextComponent) fe.getSource()).setBorder(BorderFactory.createLineBorder(Color.gray));
}
}
};
txtJobId.addFocusListener(fl);
textAreaDesription.addFocusListener(fl);
setGlassPane(gvp);
gvp.setVisible(true);
}
private void validationForInteger(JTextComponent comp){
String temp = comp.getText();
if(temp.matches("^[1-9]\\d*$")){
setGreen(comp);
} else {
setRed(comp);
}
}
private void validationForText(JTextComponent comp) {
System.out.println("In validation for text " + textAreaDesription.getY());
String temp = comp.getText();
if (temp.matches("^[a-zA-Z0-9][a-zA-Z0-9\\s_/-]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
private void setRed(JTextComponent comp) {
comp.setBorder(BorderFactory.createLineBorder(Color.red));
gvp.showWarningIcon(comp);
}
private void setGreen(JTextComponent comp) {
comp.setBorder(BorderFactory.createLineBorder(Color.green));
gvp.removeWarningIcon(comp);
}
}
thus the focus listners shall call for validation and there the classValidaionPane shall be called. If it is called then it goes wrong (but only for textArea's and not for textField) can somebody help me with this?
The parent component of the JTextArea is not the same as the parent component of the JTextField, since the JTextArea is inside a JScrollPane. I have not taken the time to read and understand all the code you posted, but you should probably placed the label relative to the position of the JScrollPane, and not relative to the position of the JTextArea.

Categories

Resources