Getting new bound values from JFrame (Java) - 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();

Related

Why couldn't I add a jpanel with graphics to another jpanel?

/I want to add a moving square into a jPanel, jpSpot which is to be added to another jpanel, jp. But when I add "jp.add(jpSpot); frm1.add(jp);" into my code, on these two lines errors appear. Please see the code below:/
import java.awt.*;
import javax.swing.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
class jpSpot extends JPanel{
int x = 250;
int y = 100;
public void display(){
x --;
//y ++;
this.repaint();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
Color customColor = new Color(100,0,153); //Purple color
g2d.setColor(customColor);
g2d.fill3DRect(x, y, 50, 50, true);
}
}
public class PlaySong {
public static void main(String[] args) {
Song song1 = new Song("紫竹調", 4, 4, "C");
char[] lyric = {};
int[] numNotes = {};
int[][] notes = {};
JFrame frm1 = new JFrame("康樂彩歌");
frm1.setBounds(0, 0, 1368, 500);
frm1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label1 = new JLabel("選歌:"); //Label is created
label1.setFont(new Font("新細明體", Font.PLAIN, 20));
JPanel jp = new JPanel(); //The first jPanel is created
JComboBox cmbox = new JComboBox(); //ComboBox is created
cmbox.setFont(new Font("新細明體", Font.PLAIN, 20));
cmbox.addItem("紫竹調");
cmbox.addItem("走一同去郊遊");
cmbox.addItem("大野狼");
cmbox.addItem("歸來吧蘇連多");
cmbox.addItem("追尋");
cmbox.addItem("三輪車");
cmbox.addItem("我家門前有小河");
cmbox.addItem("漁家樂");
cmbox.addItem("嚕啦啦");
cmbox.addItem("踏雪尋梅");
jp.add(label1);
jp.add(cmbox);
frm1.setVisible(true);
JRadioButton rb1 = new JRadioButton("加簡譜", false);
rb1.setFont(new Font("新細明體", Font.PLAIN, 20));
JRadioButton rb2 = new JRadioButton("加人聲", false);
rb2.setFont(new Font("新細明體", Font.PLAIN, 20));
rb1.setBounds(450, 180, 50, 50);
rb2.setBounds(500, 180, 50, 50);
jp.add(rb1);
jp.add(rb2);
jpSpot spot1 = new jpSpot();
spot1.setVisible(true);
while(true){
spot1.display();
try {
Thread.sleep(300);
}
catch (InterruptedException e)
{
e.printStackTrace();}
}
}
jp.add(jpSpot);// Error appears on this line
frm1.add(jp); // Error appears on this line
}
public class Song {
String title;
int beats;
int noteunit;
String key;
Song(String title, int beats, int noteunit, String key){
this.title = title;
this.beats = beats;
this.noteunit = noteunit;
this.key = key;
}
}
/Since these two lines, jp.add(jpSpot); and frm1.add(jp); have errors , the program couldn't run./

Graph not showing inside JPanel

I need some help with my code; I have a program that will show the graph of Ohm's Law. The graph was showing before I put a save button. When i run the program, it will only show the everything except for the graph. Also, I have problems in saving the current and voltage array into a .txt file. Please help!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import static java.nio.file.Files.newBufferedWriter;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class DrawGraph extends JPanel {
double current[] = new double [999];
double voltage[] = new double [999];
final int TEXT = 20;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int w = 400;
int h = 400;
g2.setStroke(new BasicStroke(3));
g2.drawLine(TEXT, TEXT, TEXT, h-TEXT);
g2.drawLine(TEXT, h-TEXT, w-TEXT, h-TEXT);
for(int x= 0; x<1000; x++ )
{
current[x]=x+1;
voltage[x]=x+1;
}
g2.setPaint(Color.red);
g2.setStroke(new BasicStroke(2));
g2.draw(new Line2D.Double(TEXT, h-TEXT, w-TEXT ,TEXT ));
// Draw labels.
g2.setPaint(Color.black);
Font font = g2.getFont();
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = font.getLineMetrics("0", frc);
float sheight = lm.getAscent() + lm.getDescent();
// Ordinate label.
g2.setFont(new Font("Century Gothic", Font.PLAIN, 15));
String s = "Voltage V";
float sY = TEXT + ((h - 2*TEXT) - s.length()*sheight)/2 + lm.getAscent();
for(int r = 0; r < s.length(); r++)
{
String letter = String.valueOf(s.charAt(r));
float swidth = (float)font.getStringBounds(letter, frc).getWidth();
float sX = (TEXT - swidth)/2;
g2.drawString(letter, sX, sY);
sY += sheight;
}
// Abcissa label.
s = "Current A";
sY = h - TEXT + (TEXT - sheight)/2 + lm.getAscent();
float swidth = (float)font.getStringBounds(s, frc).getWidth();
float sX = (w - swidth)/2;
g2.drawString(s, sX, sY);
//Gridlines
int b=TEXT+(((w-TEXT)-TEXT)/10);
g2.setPaint(Color.gray);
for(int a=1; a<=10; a++)
{
b+=36;
g2.setStroke(new BasicStroke(1));
g2.drawLine(b, h-TEXT, b, TEXT);
g2.drawLine(TEXT, b, w-TEXT, b);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Ohm's Law");
JPanel panel = new JPanel(new BorderLayout(3,1));
JPanel titlepanel = new JPanel();
titlepanel.setPreferredSize(new Dimension(400,50));
JLabel title = new JLabel("OHM'S LAW");
title.setFont(new Font("Century Gothic", Font.BOLD, 25));
titlepanel.add(title);
panel.add(titlepanel,BorderLayout.NORTH);
JPanel graphpanel = new JPanel();
graphpanel.setBackground(Color.white);
graphpanel.setPreferredSize(new Dimension(420,420));
DrawGraph drawgraph = new DrawGraph();
graphpanel.add(drawgraph);
panel.add(graphpanel,BorderLayout.CENTER);
JPanel buttonpanel = new JPanel ();
buttonpanel.setPreferredSize(new Dimension(400,50));
JButton save = new JButton("SAVE");
save.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed (ActionEvent event)
{
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION)
{
java.io.File fileToSave = fileChooser.getSelectedFile();
try
{
fileToSave.createNewFile();
try (BufferedWriter writer = newBufferedWriter(fileToSave.toPath(), Charset.defaultCharset(), StandardOpenOption.WRITE))
{
writer.write("V=I\t R=1\r Voltage \t Current\n");
//writer.write("Material: " + material.getSelectedValue().toString()+"\r\nv = " + v + "\r\nE1 = " + e1 + "\r\nE2 = " + e2);
}
}
catch (IOException ex)
{
Logger.getLogger(DrawGraph.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
}
}
);
save.setFont(new Font("Century Gothic", Font.BOLD, 15));
buttonpanel.add(save);
panel.add(buttonpanel, BorderLayout.SOUTH);
frame.add(panel);
frame.getContentPane().setBackground(Color.GREEN);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
JPanel graphpanel = new JPanel();
graphpanel.setBackground(Color.white);
graphpanel.setPreferredSize(new Dimension(420,420));
DrawGraph drawgraph = new DrawGraph();
graphpanel.add(drawgraph);
panel.add(graphpanel,BorderLayout.CENTER);
You add your DrawGraph component to a JPanel. By default a JPanel uses a FlowLayout() which respects the preferred size of any component added to it. Your custom DrawGraph component has a preferred size of 0, so there is nothing to paint.
Every Swing component is responsible for determining its own preferred size so you need to override the getPreferredSize() method of your DrawGraph components to return its preferred size so the layout manager can do its job.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.
Also, don't use setPreferredSize(). The layout manager will determine the preferred size of the panel based on the components added to it.
First things first. Make a JFrame derived class and in that class insert separately your buttonPanel which extends JPanel on the BorderLayout.SOUTH and your DrawGraph panel on the BorederLayout.Center. Don't add butttonPanel to the window you are drawing in.
I also suggest to change name from DrawGraph to GraphPanel you can do it just by clicking on any reference to the class and hitting alt+shift+r if you use Eclipse IDE.
So to conclude:
public class MainWindow extends JFrame(){
public void createGUI(){
add(graphPanel = new GraphPanel(), BorderLayout.CENTER);
add(buttonPanel = new JPanel(), BorderLayout.SOUTH);
}
}
and build your solution around that.

Place image at random grid point on button click

I'm using Java with Window builder
I've created a 4x4 grid out of jlabels (each grid point is a different jlabel) on my jframe.
I also have a button called btnPlace.
What I want to do is have an image appear at a random grid point on button click. The image file is called red.png which is a red circle. The image can appear at any grid point except the grid point number 1.
Sort of like this: http://i.stack.imgur.com/bBn6D.png
Here's my code:
public class grid {
public static void main (String[] args)
{
JFrame grid =new JFrame();
grid.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
JPanel set = new JPanel();
set.setBounds(10, 11, 307, 287);
grid.getContentPane().add(set);
set.setLayout(new GridLayout(4, 4, 0, 0));
JLabel a = new JLabel("");
set.add(a);
JLabel b = new JLabel("");
set.add(b);
JLabel c = new JLabel("");
set.add(c);
^^ this repeats up to JLabel p. just to save time.
JButton btnPlace = new JButton("Place");
grid.getContentPane().add(btnPlace);
grid.setVisible(true);
} }
Here is fully working example:
On pressing button it'll draw Image on randomly selected JLabel
package stackoverflow;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DummyColor {
private JFrame frame;
private JLabel[] labels = new JLabel[4];
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DummyColor window = new DummyColor();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DummyColor() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 657, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lbl1 = new JLabel("First BOX");
lbl1.setBounds(10, 11, 273, 194);
frame.getContentPane().add(lbl1);
JLabel label = new JLabel("Second BOX");
label.setBounds(336, 11, 273, 194);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("Third BOX");
label_1.setBounds(10, 251, 273, 194);
frame.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Fourth BOX");
label_2.setBounds(347, 251, 273, 194);
frame.getContentPane().add(label_2);
labels[0] = lbl1;
labels[1] = label;
labels[2] = label_1;
labels[3] = label_2;
JButton btnPick = new JButton("Place");
btnPick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon imageIcon = new ImageIcon(DummyColor.class.getResource("/red.jpg"));
int randInt = randInt(1, 4);
System.out.println(randInt);
for (int i = 0; i < labels.length; i++) {
JLabel jLabel = labels[i];
if (i == randInt - 1) {
jLabel.setIcon(imageIcon);
} else {
jLabel.setIcon(null);
}
}
}
});
btnPick.setBounds(10, 439, 57, 23);
frame.getContentPane().add(btnPick);
}
private static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
I would create a custom JPanel and add a MouseListener. Whenever the Panel is clicked, an image will be draw at that point clicked on the panel
public class grid{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.add(new MyPanel());
}
}
class MyPanel extends JPanel{
Point p;
BufferedImage img;
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
p = e.getLocationOnScreen();
repaint();
}
});
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
try{
img = ImageIO.read("someImage.png");
}catch(Exception e){e.printStackTrace();}
g.drawImage(img, p.getX(), p.getY(), width, height, this);
}
}

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:

Issues with ActionListener(Java) [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Issues with ActionListener (Java)
I am trying to implement action listener on two buttons in JFrame, but the issue is one of the two button is performing both the functions; but i've not configured it to do so.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyChangingCirlce implements ActionListener {
JButton colorButton, labelButton;
JLabel myLabel;
MyDrawPanel mdp;
JFrame frame;
public static void main(String[] args) {
MyChangingCirlce mcc = new MyChangingCirlce();
mcc.createFrame();
} // end of main
public void createFrame() {
frame = new JFrame();
colorButton = new JButton("Changing Colors");
labelButton = new JButton("Change Label");
myLabel = new JLabel("I'm a label");
mdp = new MyDrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, mdp);
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, myLabel);
colorButton.addActionListener(this);
labelButton.addActionListener(this);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == colorButton) {
frame.repaint();
} else {
myLabel.setText("That's it");
}
}
}
My labelButton is performing both the action only 1 time; i.e it changes the color of the circle along with the label text.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel{
public void paintComponent(Graphics g)
{
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue= (int) (Math.random() * 255);
Color randomColor = new Color(red,green,blue);
g.setColor(randomColor);
g.fillOval(20,70,100,100);
}
}
You override colorButton and labelButton. So the 'else' is always kicking in. Changing the label will cause a redraw.
change
JButton colorButton = new JButton("Changing Colors");
JButton labelButton = new JButton("Change Label");
to
colorButton = new JButton("Changing Colors");
labelButton = new JButton("Change Label");
After writing myself a class to test it, I came about with this:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Date;
public class Foo implements ActionListener {
JButton colorButton, labelButton;
JLabel myLabel;
JFrame frame;
MyDrawPanel mdp;
public static void main(String[] args) {
Foo mcc = new Foo();
mcc.createFrame();
} //end of main
public void createFrame() {
frame = new JFrame();
colorButton = new JButton("Changing Colors");
labelButton = new JButton("Change Label");
myLabel = new JLabel("I'm a label");
mdp = new MyDrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
mdp.setPreferredSize(new Dimension(150, 150));
jsp.setLeftComponent(mdp);
frame.setBounds(10, 10, 600, 600);
JPanel right = new JPanel();
right.add(BorderLayout.SOUTH, colorButton);
right.add(BorderLayout.EAST, labelButton);
right.add(BorderLayout.WEST, myLabel);
jsp.setRightComponent(right);
frame.getContentPane().add(jsp);
colorButton.addActionListener(this);
labelButton.addActionListener(this);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == colorButton) {
myLabel.setText("Color button's it");
frame.repaint();
} else {
myLabel.setText("That's it" + new Date().toString());
}
}
public class MyDrawPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.fillOval(20, 70, 100, 100);
}
}
}

Categories

Resources