ImageManager program - java

I am working on a project where I have to create an image manager program in Java. The program will have the following features in it: Program should take image from the user as input. Then it should display the image in panel(1), and in panel(2) it should give the user an options of changing width, height, hgap, vgap, top margin and left margin of the image with an 'OK' button at the end including an 'action listener' feature. Using the above mentioned features we will get the grids on the image. Now if the user clicks on the particular grid then that particular image should get extracted into a folder.
I am attaching the program which we have done so far.
The difficulties we are facing are: we are not able to insert a JScrollPane for the image. As well as we are unaware of how to add action listeners to the grids so that we can extract that particular image.
package project_image_manager_imp_files;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
class SidePanel1 extends JPanel implements ActionListener {
JTextField top_margin = new JTextField(10);
JTextField left_margin = new JTextField(10);
JTextField Width = new JTextField(10);
JTextField Height = new JTextField(10);
JTextField Vgap = new JTextField(10);
JTextField Hgap = new JTextField(10);
JLabel j1 = new JLabel("Top margin");
JLabel j2 = new JLabel("Left margin");
JLabel j3 = new JLabel("Width");
JLabel j4 = new JLabel("Height");
JLabel j5 = new JLabel("Vertical gap");
JLabel j6 = new JLabel("Horizontal gap");
JButton b = new JButton("OK");
public SidePanel1() {
this.setBackground(Color.black);
Dimension d1 = new Dimension(1000, 1000);
this.setMaximumSize(d1);
this.setPreferredSize(d1);
JPanel p = new JPanel();
JScrollPane vertical = new JScrollPane();
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(vertical);
vertical.setVerticalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(vertical);
//showCoo.build(c);
//c.add(p);
//p.setOpaque(false);
//t1.addActionListener(new JTextFieldEventClass() );
//b.addActionListener(new JTextFieldEventClass() );
// String s=t3.getText();
//int c=Integer.parseInt(s);
p.add(j1);
p.add(top_margin);
p.add(j2);
p.add(left_margin);
p.add(j3);
p.add(Width);
p.add(j4);
p.add(Height);
p.add(j5);
p.add(Vgap);
p.add(j6);
p.add(Hgap);
p.add(b);
p.setLayout(new GridLayout(7, 2));
b.addActionListener(this);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1, 2));
frame.setBounds(200, 200, 600, 400);
frame.setTitle("Hello World Test");
frame.setResizable(true);
//frame.setSize (500, 300);
Container c = frame.getContentPane();
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.WEST);
frame.add(p, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
int height;
int width;
int hgap;
int vgap;
int tm;
int lm;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(Toolkit.getDefaultToolkit().getImage("images1.jpg"), 0, 0, this);
Graphics2D g2d = (Graphics2D) g.create();
//File f=new File("images1.jpg");
//BufferedImage im=ImageIO.read(f);
int frame_width = getWidth();
int frame_height = getHeight();
for (int j = 0; j < frame_height; j++) {
int y = tm + (height * j) + (vgap * j);
for (int i = 0; i < frame_width; i++) {
int x = lm + (width * i) + (hgap * i);
g.drawRect(x, y, width, height);
}
}
}
public static void main(String[] argv) {
//static JScrollBar scrollbar;
SidePanel1 panel = new SidePanel1();
panel.setLayout(new FlowLayout());
//scrollbar = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//panel.add(scrollbar);
try {
while (true) {
Thread.sleep(100);
///.out.println("("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+")");
}
} catch (InterruptedException e) {}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
width = Integer.parseInt(Width.getText());
height = Integer.parseInt(Height.getText());
hgap = Integer.parseInt(Hgap.getText());
vgap = Integer.parseInt(Vgap.getText());
lm = Integer.parseInt(left_margin.getText());
tm = Integer.parseInt(top_margin.getText());
repaint();
}
}

Related

Java swing JLabel doesn't appear in BorderLayout

I'm making 10 stars on JPanel with random location.
But the thing is when i set layout, the starts doesn't show up.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = frame.getContentPane();
c.setLayout(new BorderLayout());
JPanel northPanel = new JPanel(new FlowLayout());
northPanel.add(new JButton("Open"));
c.add(northPanel, BorderLayout.NORTH);
JPanel southPanel = new JPanel(new FlowLayout());
southPanel.add(new JButton("Integer Input"));
c.add(southPanel, BorderLayout.SOUTH);
JPanel centerPanel = new JPanel(null);
centerPanel.setBackground(Color.pink);
for(int i = 0; i < 10; i++) {
int x = (int) (Math.random() * 300);
int y = (int) (Math.random() * 300);
JLabel label = new JLabel("*");
label.setLocation(x, y);
label.setForeground(Color.green);
label.setOpaque(true);
centerPanel.add(label);
}
c.add(centerPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
in the pink section, it is supposed to be shown 10 stars
I found my own way.
after set label.setSize(10,10);
i could find 10 stars in the panel.
Basically, every container like JPanel, JFrame used some layout to place the component in some specific order. as per your code, you are passing null as argument to centralPanel. so basically central panel has no layout to place component.
Note : Flow Layout is a default layout.
in this case lets try with below steps.
1. please use setBound(x, y, height, width), on the place of setLocation(x, y).
for (int i = 0; i < 10; i++) {
int x = (int) (Math.random() * 300);
int y = (int) (Math.random() * 300);
JLabel label = new JLabel("*");
**label.setBounds(x,y,10,10);**
label.setForeground(Color.green);
label.setOpaque(true);
centerPanel.add(label);
}
[1]: https://i.stack.imgur.com/RUlUI.png
If you want to place 10 chars (*) in random locations I would recommend doing it by custom painting as demonstrated in the following mre:
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
//frame.setSize(300, 300); don't set size let the layout managers do it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = frame.getContentPane();
//c.setLayout(new BorderLayout()); not needed, it is the default
JPanel northPanel = new JPanel(new FlowLayout()); //FlowLayout is the default
northPanel.add(new JButton("Open"));
c.add(northPanel, BorderLayout.NORTH);
JPanel southPanel = new JPanel(new FlowLayout());
southPanel.add(new JButton("Integer Input"));
c.add(southPanel, BorderLayout.SOUTH);
JPanel centerPanel = new PinkPlanet();
c.add(centerPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
class PinkPlanet extends JPanel{
private static final int W = 300, H = 300;
private static final String STAR ="*";
private final Dimension pSize = new Dimension(W, H);
private final List<Point> locations = new ArrayList<>();
public PinkPlanet() {
setBackground(Color.pink);
for(int i = 0; i < 10; i++) {
int x = (int) (Math.random() * W);
int y = (int) (Math.random() * H);
locations.add(new Point(x, y));
}
}
#Override
public Dimension getPreferredSize() {
return pSize;
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for(Point location : locations){
g.drawString(STAR, location.x, location.y);
}
}
}

JComponents Moving to Origin After Repaint()

Similar to JButton showing up in the wrong spot after repaint is called, but the responses to that question only addressed the fact that he wasn't using a layout manager, while I am using a layout manager (poorly), so it didn't really help, unfortunately.
Details
Intent of the Program:
To show a preview of a 1920x1080 grid (scaled down to 640x480 to save space), stretching and shrinking as you change the height of each square, width of each square, and the number of columns it'll have. (You specify a number of total squares to be in the grid first, so the number of rows is inferred by the program.)
Structure:
One top-level JFrame.
Contains two JPanels: the Grid, and the sidebar, using a BorderLayout to snap them to the east and west sides.
Sidebar is one JPanel containing all of the JComponents in a Y-Axis aligned BoxLayout.
Grid extends JComponent, and uses Graphics.drawLine() to draw the grid.
Each component in the sidebar calls Grid.repaint() when changed to update the grid.
Current UI, with the two main JPanels outlined in red.
The Problem
Whenever I change any of the components and thus call Grid.repaint():
The grid doesn't clear, resulting in multiple lines appearing;
All of the sidebar components get painted at the top-left corner, while still showing/functioning on the sidebar;
The grid resizes itself to be wider than normal for some reason.
Current UI, but borked.
What I've Tried
Changing the repaint() region to be a rectangle that only covers the grid,
Checking the documentation for anything about this,
Google,
Asking you guys.
The Code
Reprex: (Simplified to "Press the button to reproduce", while still keeping the essence of the potential problem areas.)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BuildGridGUI2
{
static final int WIDTH_MIN = 100;
static final int WIDTH_MAX = 2000;
static final int WIDTH_INIT = 520;
static final int HEIGHT_MIN = 100;
static final int HEIGHT_MAX = 2000;
static final int HEIGHT_INIT = 300;
int widthOfFrames = 255;
int heightOfFrames = 255;
int numCols = 3;
int numFrames = 1;
private final JComponent makeUI()
{
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
Grid g = new Grid();
JComponent j = makeSideMenu(g);
g.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.red),
g.getBorder()));
j.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.red),
j.getBorder()));
p.add(j, BorderLayout.EAST);
p.add(g, BorderLayout.WEST);
return p;
}
private final JComponent makeSideMenu(Grid grid)
{
JPanel p = new JPanel();
JLabel numColsSelectorLabel = new JLabel("Frames Per Column");
JSpinner numColsSelectorField = new JSpinner();
JLabel widthLabel = new JLabel("Width per Frame (Pixels)");
JSpinner widthSpinner = new JSpinner();
JSlider widthSlider = new JSlider(WIDTH_MIN, WIDTH_MAX, WIDTH_INIT);
JLabel heightLabel = new JLabel("Height per Frame (Pixels)");
JSpinner heightSpinner = new JSpinner();
JSlider heightSlider = new JSlider(BuildGridGUI2.HEIGHT_MIN, BuildGridGUI2.HEIGHT_MAX, BuildGridGUI2.HEIGHT_INIT);
JButton confirmButton = new JButton("Confirm");
numColsSelectorField.setEditor(new JSpinner.NumberEditor(numColsSelectorField));
numColsSelectorField.setMaximumSize(numColsSelectorField.getPreferredSize());
widthSlider.setMajorTickSpacing(300);
widthSlider.setMinorTickSpacing(20);
widthSlider.setPaintTicks(true);
widthSlider.setPaintLabels(true);
widthSpinner.setEditor(new JSpinner.NumberEditor(widthSpinner));
widthSpinner.setPreferredSize(new Dimension(70, 30));
widthSpinner.setMaximumSize(widthSpinner.getPreferredSize());
heightSlider.setMajorTickSpacing(300);
heightSlider.setMinorTickSpacing(20);
heightSlider.setPaintTicks(true);
heightSlider.setPaintLabels(true);
heightSpinner.setEditor(new JSpinner.NumberEditor(heightSpinner));
heightSpinner.setPreferredSize(new Dimension(70, 30));
heightSpinner.setMaximumSize(heightSpinner.getPreferredSize());
confirmButton.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e)
{
widthOfFrames = 200;
grid.refresh();
}
});
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setPreferredSize(new Dimension(300, 480));
p.setSize(new Dimension(300, 480));
numColsSelectorLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
numColsSelectorField.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
confirmButton.setAlignmentX(Component.CENTER_ALIGNMENT);
widthLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
heightLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
p.add(Box.createRigidArea(new Dimension(300, 30)));
p.add(numColsSelectorLabel);
p.add(Box.createRigidArea(new Dimension(300, 5)));
p.add(numColsSelectorField);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(widthLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(widthSpinner);
p.add(widthSlider);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(heightLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(heightSpinner);
p.add(heightSlider);
p.add(Box.createRigidArea(new Dimension(300, 45)));
p.add(confirmButton);
return p;
}
private static void createAndShowGUI() {
BuildGridGUI2 b = new BuildGridGUI2();
JFrame mainFrame = new JFrame("Grid Builder");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(940, 480);
mainFrame.getContentPane().add(b.makeUI());
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
class Grid extends JComponent
{
static final int CANVAS_WIDTH = 640;
static final int CANVAS_HEIGHT = 480;
private final double conversionRatio = 4.0/9.0; // 1080p scaled down to 480p preview
private int squareHeight, squareWidth, numColumns, numRows;
public Grid()
{
setOpaque(true);
setSize(CANVAS_WIDTH, CANVAS_HEIGHT); // trying to get the size to work properly.
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
updateVars();
int k;
for (k = 0; k < numColumns; k++)
{
// #param: (x1, y1), (x2, y2)
g.drawLine(k * squareWidth, 0, k * squareWidth, CANVAS_HEIGHT);
}
for (k = 0; k < numRows; k++)
{
g.drawLine(0, k * squareHeight, CANVAS_WIDTH, k * squareHeight);
}
}
public void refresh()
{
// Attempting to set the repaint area to only the grid region
// because CTRL+F is free and parameters are not
repaint(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
public void updateVars()
{
this.squareWidth = (int)(
(double)BuildGridGUI2.this.widthOfFrames
*
conversionRatio);
this.squareHeight = (int)(
(double)BuildGridGUI2.this.heightOfFrames
*
conversionRatio);
this.numColumns = BuildGridGUI2.this.numCols;
this.numRows = (int)(
(
(double)BuildGridGUI2.this.numFrames
/
numColumns
)
+ 0.5);
}
}
}
Actual Source Code (Not strictly relevant, but if you're in the mood for code review then I'd love to learn better coding conventions.)
Thank you!
All of the sidebar components get painted at the top-left corner, while still showing/functioning on the sidebar;
JComponent is an abstract class that all Swing components extend from. It has no default painting logic.
Therefore invoking super.paintComponent(...) does not really do anything.
In particular it does not clear the background of the component before doing custom painting. This will result in the painting artifacts that you see.
Any time you extend JComponent your logic should be something something like:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// clear background
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
// do custom painting
g.setColor( getForeground() );
...
}
Note: this is the reason the many people override JPanel for simple custom painting as mentioned by Abra. The paintComponent(...) method of the JPanel will clear the background by default.
I made a few changes to the code you posted.
I changed class Grid such that it extends JPanel and not JComponent, since custom painting is usually done on a JPanel.
I added a instance member variable grid with type Grid, to class BuildGridGUI2 rather than creating one and sending it as a parameter to method makeSideMenu.
Here is your code with my modifications (and my preferred coding style). It simply solves your reported problem and nothing more.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BuildGridGUI2 {
static final int WIDTH_MIN = 100;
static final int WIDTH_MAX = 2000;
static final int WIDTH_INIT = 520;
static final int HEIGHT_MIN = 100;
static final int HEIGHT_MAX = 2000;
static final int HEIGHT_INIT = 300;
int widthOfFrames = 255;
int heightOfFrames = 255;
int numCols = 3;
int numFrames = 1;
Grid grid;
private final JComponent makeUI() {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
grid = new Grid();
JComponent j = makeSideMenu();
grid.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.red),
grid.getBorder()));
j.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.red),
j.getBorder()));
p.add(j, BorderLayout.EAST);
p.add(grid, BorderLayout.WEST);
return p;
}
private final JComponent makeSideMenu() {
JPanel p = new JPanel();
JLabel numColsSelectorLabel = new JLabel("Frames Per Column");
JSpinner numColsSelectorField = new JSpinner();
JLabel widthLabel = new JLabel("Width per Frame (Pixels)");
JSpinner widthSpinner = new JSpinner();
JSlider widthSlider = new JSlider(WIDTH_MIN, WIDTH_MAX, WIDTH_INIT);
JLabel heightLabel = new JLabel("Height per Frame (Pixels)");
JSpinner heightSpinner = new JSpinner();
JSlider heightSlider = new JSlider(BuildGridGUI2.HEIGHT_MIN,
BuildGridGUI2.HEIGHT_MAX,
BuildGridGUI2.HEIGHT_INIT);
JButton confirmButton = new JButton("Confirm");
numColsSelectorField.setEditor(new JSpinner.NumberEditor(numColsSelectorField));
numColsSelectorField.setMaximumSize(numColsSelectorField.getPreferredSize());
widthSlider.setMajorTickSpacing(300);
widthSlider.setMinorTickSpacing(20);
widthSlider.setPaintTicks(true);
widthSlider.setPaintLabels(true);
widthSpinner.setEditor(new JSpinner.NumberEditor(widthSpinner));
widthSpinner.setPreferredSize(new Dimension(70, 30));
widthSpinner.setMaximumSize(widthSpinner.getPreferredSize());
heightSlider.setMajorTickSpacing(300);
heightSlider.setMinorTickSpacing(20);
heightSlider.setPaintTicks(true);
heightSlider.setPaintLabels(true);
heightSpinner.setEditor(new JSpinner.NumberEditor(heightSpinner));
heightSpinner.setPreferredSize(new Dimension(70, 30));
heightSpinner.setMaximumSize(heightSpinner.getPreferredSize());
confirmButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
widthOfFrames = 200;
grid.refresh();
}
});
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setPreferredSize(new Dimension(300, 480));
p.setSize(new Dimension(300, 480));
numColsSelectorLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
numColsSelectorField.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSlider.setAlignmentX(Component.CENTER_ALIGNMENT);
confirmButton.setAlignmentX(Component.CENTER_ALIGNMENT);
widthLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
heightLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
widthSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
heightSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);
p.add(Box.createRigidArea(new Dimension(300, 30)));
p.add(numColsSelectorLabel);
p.add(Box.createRigidArea(new Dimension(300, 5)));
p.add(numColsSelectorField);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(widthLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(widthSpinner);
p.add(widthSlider);
p.add(Box.createRigidArea(new Dimension(300, 25)));
p.add(heightLabel);
p.add(Box.createRigidArea(new Dimension(300, 3)));
p.add(heightSpinner);
p.add(heightSlider);
p.add(Box.createRigidArea(new Dimension(300, 45)));
p.add(confirmButton);
return p;
}
private static void createAndShowGUI() {
BuildGridGUI2 b = new BuildGridGUI2();
JFrame mainFrame = new JFrame("Grid Builder");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(940, 480);
mainFrame.getContentPane().add(b.makeUI());
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
class Grid extends JPanel {
static final int CANVAS_WIDTH = 640;
static final int CANVAS_HEIGHT = 480;
private final double conversionRatio = 4.0 / 9.0; // 1080p scaled down to 480p preview
private int squareHeight, squareWidth, numColumns, numRows;
public Grid() {
setOpaque(true);
setSize(CANVAS_WIDTH, CANVAS_HEIGHT); // trying to get the size to work properly.
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
updateVars();
int k;
for (k = 0; k < numColumns; k++) {
// #param: (x1, y1), (x2, y2)
g.drawLine(k * squareWidth, 0, k * squareWidth, CANVAS_HEIGHT);
}
for (k = 0; k < numRows; k++) {
g.drawLine(0, k * squareHeight, CANVAS_WIDTH, k * squareHeight);
}
}
public void refresh() {
// Attempting to set the repaint area to only the grid region
// because CTRL+F is free and parameters are not
repaint(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
public void updateVars() {
this.squareWidth = (int) ((double) BuildGridGUI2.this.widthOfFrames * conversionRatio);
this.squareHeight = (int) ((double) BuildGridGUI2.this.heightOfFrames * conversionRatio);
this.numColumns = BuildGridGUI2.this.numCols;
this.numRows = (int) (((double) BuildGridGUI2.this.numFrames / numColumns) + 0.5);
}
}
}
One tip: Try to use specific sub-classes of JComponent rather than JComponent. For example, I suggest changing the return type of method makeSideMenu() to JPanel rather than JComponent since that method actually returns a JPanel.

JLabel panel opacity and general background coloring

The idea behind the code is a simple multiplying game where it generates 2 numbers and I have to input the corret answer.
Basically, my question(s) is(are):
When I do operacao.setOpaque(false); it does nothing, or at least not what I'd expect it to do (http://puu.sh/pyVcE/813aa1843a.png - shouldn't the grey area be pink, since the background is pink?). Same happens with JLabels, the setOpaque(false) leaves a grey background behind the (in this case) numbers.
I have that last commented section because I saw someone around here saying to alter the paint method, and it did work, but caused some weird issues (painted over everything when I started the console, only the JTextField would be clear), and then I "fixed" it with the setOpacity(1); setBackground(pink); - is this a proper way of doing it?
public class Frame extends JFrame {
private JPanel panel, mensagem, operacao;
private JTextArea sucesso;
private JLabel numero1, numero2;
private JTextField resposta;
private Color pink = new Color(255, 213, 224);
//more vars
public Frame() {
super("Jogo de Multiplicar!");
setOpacity(1);
setBackground(pink);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
panel = new JPanel();
mensagem = new JPanel();
operacao = new JPanel();
mensagem.setLayout(new FlowLayout(FlowLayout.CENTER));
operacao.setLayout(new FlowLayout(FlowLayout.CENTER));
sucesso = new JTextArea();
sucesso.setEditable(false);
sucesso.setOpaque(false);
sucesso.setFont(minhaFont2);
Random randomGen = new Random();
while (random1 == 0)
random1 = randomGen.nextInt(10);
while (random2 == 0)
random2 = randomGen.nextInt(10);
res = random1 * random2;
numero1 = new JLabel();
numero2 = new JLabel();
numero1.setText(random1 + " *");
numero2.setText(random2 + " =");
numero1.setOpaque(false);
numero1.setFont(minhaFont);
numero2.setFont(minhaFont);
resposta = new JTextField(2);
resposta.addActionListener(new MinhaAcao());
resposta.setFont(minhaFont);
operacao.add(numero1);
operacao.add(numero2);
operacao.add(resposta);
mensagem.add(sucesso);
operacao.setOpaque(true);
operacao.setBackground(pink);
mensagem.setOpaque(true);
mensagem.setBackground(pink);
//add(panel, BorderLayout.NORTH);
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}/*
public void paint(Graphics g) {
g.setColor(pink);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}*/
You need to textfield to be pink. You may have to do this.
resposta.setOpaque(false);
I have refactored your code like below.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Frame extends JFrame {
private JPanel panel, mensagem, operacao;
private JTextArea sucesso;
private JLabel numero1, numero2;
private JTextField resposta;
private Color pink = new Color(255, 213, 224);
//more vars
public Frame() {
super("Jogo de Multiplicar!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
getContentPane().setBackground(pink);
panel = new TransperantPanel();
mensagem = new TransperantPanel();
operacao = new TransperantPanel();
mensagem.setLayout(new FlowLayout(FlowLayout.CENTER));
operacao.setLayout(new FlowLayout(FlowLayout.CENTER));
sucesso = new JTextArea();
sucesso.setEditable(false);
Random randomGen = new Random();
int random1 =0 , random2 = 0;
while (random1 == 0)
random1 = randomGen.nextInt(10);
while (random2 == 0)
random2 = randomGen.nextInt(10);
int res = random1 * random2;
numero1 = new JLabel();
numero2 = new JLabel();
numero1.setText(random1 + " *");
numero2.setText(random2 + " =");
resposta = new JTextField(2);
resposta.setOpaque(false);
resposta.addActionListener(new MinhaAcao());
numero1.setFont(minhaFont);
numero2.setFont(minhaFont);
resposta.setFont(minhaFont);
operacao.add(numero1);
operacao.add(numero2);
operacao.add(resposta);
mensagem.add(sucesso);
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}
public static void main(String[] args){
Frame f = new Frame();
f.setVisible(true);
}
class TransperantPanel extends JPanel {
public TransperantPanel() {
setOpaque(false);
}
}
}
What i have done is
Setting background to contentPane of the frame.
Created a transparent panel(setting Opaque of the panel to false).
Setting JTextfield's Opaque to false.

Java JLabel Height with multiple lines

Hi I've got a problem in the code below ( in method "append(String str)" mostly). I want to show messages received in HTML format (so I need to use JLabel).
Without setting tac.preferredSize here is what I get:
BUT it isn't working using long string without blank spaces:
such as "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".
If I set tac.preferredSize the height of the bubble isn't increasing:
How can I overcome these problems? (working on layout/sizes and not modifying input string)
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClientGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel label;
private JTextField tf;
private JPanel chatPanel;
private JScrollPane scroll;
ClientGUI() {
super("Chat Client");
label = new JLabel("You can write messages below:", SwingConstants.CENTER);
chatPanel = new JPanel();
tf = new JTextField("");
tf.setBackground(Color.WHITE);
tf.requestFocus();
tf.setVisible(true);
tf.addActionListener(this);
chatPanel.setLayout(new BoxLayout(chatPanel, BoxLayout.PAGE_AXIS));
chatPanel.add(Box.createVerticalGlue());
JPanel centerPanel = new JPanel(new GridLayout(1,1));
scroll = new JScrollPane();
scroll.setViewportView(chatPanel);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
centerPanel.add(scroll);
add(centerPanel, BorderLayout.CENTER);
JPanel southPanel = new JPanel(new BorderLayout());
JPanel writeChatPanel = new JPanel(new GridLayout(2,1));
writeChatPanel.add(label);
writeChatPanel.add(tf);
southPanel.add(writeChatPanel, BorderLayout.NORTH);
add(southPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
chatPanel.scrollRectToVisible(new Rectangle(chatPanel.getSize()));
}
void append(String str) {
LeftArrowBubble leftArrowBubble = new LeftArrowBubble();
leftArrowBubble.setMaximumSize(new Dimension(400,350));
JLabel tac = new JLabel();
tac.setMaximumSize(new Dimension(350,400));
//tac.setPreferredSize(new Dimension(350,50)); //<----------
System.out.println(str);
tac.setText("<html><body style='width: 350px; padding:15px;display:block;'>"+str+"</body></html>");
tac.setOpaque(false);
leftArrowBubble.add(tac, BorderLayout.NORTH);
chatPanel.add(leftArrowBubble);
chatPanel.add(Box.createRigidArea(new Dimension(0,5)));
Rectangle rect = chatPanel.getBounds();
Rectangle r2 = scroll.getViewport().getVisibleRect();
chatPanel.scrollRectToVisible(new Rectangle((int) rect.getWidth(),
(int) rect.getHeight(), (int) r2.getWidth(), (int) r2.getHeight()));
revalidate();
repaint();
}
public void actionPerformed(ActionEvent e) {
// just have to send the message
append(tf.getText());
tf.setText("");
return;
}
public static void main(String[] args) {
new ClientGUI();
}
}
And the bubble class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
public class LeftArrowBubble extends JPanel {
private static final long serialVersionUID = -5389178141802153305L;
public LeftArrowBubble() {
this.setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
}
#Override
protected void paintComponent(final Graphics g) {
final Graphics2D graphics2D = (Graphics2D) g;
RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHints(qualityHints);
graphics2D.setPaint(new Color(80, 150, 180));
int width = getWidth();
int height = getHeight();
GeneralPath path = new GeneralPath();
path.moveTo(5, 10);
path.curveTo(5, 10, 7, 5, 0, 0);
path.curveTo(0, 0, 12, 0, 12, 5);
path.curveTo(12, 5, 12, 0, 20, 0);
path.lineTo(width - 10, 0);
path.curveTo(width - 10, 0, width, 0, width, 10);
path.lineTo(width, height - 10);
path.curveTo(width, height - 10, width, height, width - 10, height);
path.lineTo(15, height);
path.curveTo(15, height, 5, height, 5, height - 10);
path.lineTo(5, 15);
path.closePath();
graphics2D.fill(path);
}
}
If you break up the words that are too long by adding spaces, I think most of your problems are solved. Some small changes to the dimensions of the leftArrowBubble and tac components would be useful as well.
You could replace the following lines in the append method:
leftArrowBubble.setMaximumSize(new Dimension(400,350));
JLabel tac = new JLabel();
tac.setMaximumSize(new Dimension(350,400));
//tac.setPreferredSize(new Dimension(350,50)); //<----------
System.out.println(str);
tac.setText("<html><body style='width:350px;padding:15px;display:block;'>"
+ str + "</body></html>");
by the following code (you can also take a look at Split string to equal length substrings in Java for more ways to split a string in equal parts):
leftArrowBubble.setMaximumSize(new Dimension(500, 500));
JLabel tac = new JLabel();
tac.setMaximumSize(new Dimension(450, 450));
//tac.setPreferredSize(new Dimension(350, 50)); //<----------
final int maximumSize = 56;
String textWithSeparators = "";
final StringTokenizer textTokenizer
= new StringTokenizer(str, " \t\n\r", true);
while (textTokenizer.hasMoreTokens()) {
final String part = textTokenizer.nextToken();
for (int beginIndex = 0; beginIndex < part.length();
beginIndex += maximumSize)
textWithSeparators += (beginIndex == 0 ? "" : " ")
+ part.substring(beginIndex,
Math.min(part.length(),
beginIndex + maximumSize));
}
System.out.println(textWithSeparators);
tac.setText("<html><body style='width:350px;padding:15px;display:block;'>"
+ textWithSeparators + "</body></html>");
The value for maximumSize could be calculated using font metrics (see How to get the correct String width from FontMetrics in JAVA for more information), but I've used a fixed value here for the sake of simplicity.
It would be nice to link the dimensions of leftArrowBubble, tac, and the width in the html string, like:
final int size = 500;
leftArrowBubble.setMaximumSize(new Dimension(size, size));
JLabel tac = new JLabel();
tac.setMaximumSize(new Dimension(size - 50, size - 50));
// [...]
tac.setText("<html><body style='width:" + (size - 150)
+ "px;padding:15px;display:block;'>"
+ textWithSeparators + "</body></html>");

Cleaning up a Nested J panel

Rebuilt the SCCE for you guys.
My goal is this
The general idea is that clicking on the title bars of the menus (right side) will collapsible (set visible to false) the content panes associated with them:
gender_panel_BG collapses gender_panel_body
race_panel_BG collapses race_panel_body
class_panel_BG collapses class_panel_body
base_stats_panel_BG collapses base_stats_panel_body
merits_panel_BG collapses merits_panel_body
You get the idea
Another thing that is bugging me is the huge space at the top of the body and it's content.
Gradient bar img source
background source source
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.*;
public class JaGCharCreation {
//set inital size of window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int initalWidth = (int) screenSize.width - 50;
int initalHeight = (int) screenSize.height - 50;
JPanel gender_panel_body;
GridBagConstraints gbc;
JLabel viewdata_gender = new JLabel("gender");
ImageIcon BGicon = new ImageIcon("parchmentTall.jpg");
Image img1 = BGicon.getImage();
public static void main(String[] args) {
new JaGCharCreation ();
}
//set up thread safe invoking for GUI
public JaGCharCreation () {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
//frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Give the frame an initial size.
frame.setSize(initalWidth, initalHeight);
}
});
}
//main panel to hold all others
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(0, 2));
add(createLeftPane());
add(createRightPane());
}//end of class for master frame
/////////////////////////////////Left Panel Nest Begin//////////////////////////////////////////////////////////////
protected JPanel createLeftPane() {
img1 = img1.getScaledInstance(initalWidth/2, initalHeight, java.awt.Image.SCALE_SMOOTH);
final ImageIcon BGiconSM = new ImageIcon(img1);
JPanel panel = new JPanel(new BorderLayout()) {
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(BGiconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
panel.setOpaque( false );
panel.setBorder(new EmptyBorder(35, 80, 35, 80));
//panel.setBackground(Color.RED);
return panel;
}//end left pane
/////////////////////////////////Left Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Right Panel Nest Begin//////////////////////////////////////////////////////////////
protected JPanel createRightPane() {
img1 = img1.getScaledInstance(initalWidth/2, initalHeight, java.awt.Image.SCALE_SMOOTH);
final ImageIcon BGiconSM = new ImageIcon(img1);
JPanel content = new JPanel(new GridBagLayout());
content.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout()) {
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(BGiconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
panel.setOpaque( false );
panel.setBorder(new EmptyBorder(35, 80, 35, 80));
//panel.setBackground(Color.BLUE);
//set up our image for the title bars
ImageIcon icon = new ImageIcon("GradientDetail.png");
Image img = icon.getImage();
img = img.getScaledInstance(initalWidth/2, 40, java.awt.Image.SCALE_SMOOTH);
final ImageIcon iconSM = new ImageIcon(img);
/////////////////////////////////Gender Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel gender_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
gender_panel_BG.setOpaque( false );
JLabel gender_panel_label = new JLabel("Gender");
gender_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
gender_panel_label.setForeground(Color.white);
gender_panel_label.setOpaque(false);
gender_panel_body = new JPanel(new GridLayout(1, 3));
gender_panel_body.setBackground(Color.WHITE);
gender_panel_BG.add(gender_panel_label, BorderLayout.NORTH);
JPanel gender_panel = new JPanel(new GridLayout(2, 1));
//gender_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//gender_panel.setBackground(Color.GREEN);
gender_panel.setOpaque(false);
gender_panel.add(gender_panel_BG);
gender_panel.add(gender_panel_body);
MouseAdapter gender = new MouseAdapterMod(){
public void mousePressed(MouseEvent e) {
//System.out.println(e.getSource());
System.out.println("A mouse was pressed");
gender_panel_body.setVisible(!gender_panel_body.isVisible());
}//end of mousePressed(MouseEvent e)
};
// Create radio buttons and add them to content pane.
JRadioButton g1 = new JRadioButton("Male");
g1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
viewdata_gender.setText("Gender: Male");
}//action perfomed;
});//g1 add action listener
gender_panel_body.add(g1);
JRadioButton g2 = new JRadioButton("Female");
g2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
viewdata_gender.setText("Gender: Female");
}//action perfomed;
});//g2 add action listener
gender_panel_body.add(g2);
JRadioButton g3 = new JRadioButton("<Unknown>");
g3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
viewdata_gender.setText("Gender: <Unknown>");
}//action perfomed;
});//g3 add action listener
gender_panel_body.add(g3);
// Define a button group.
ButtonGroup genderButtons = new ButtonGroup();
genderButtons.add(g1);
genderButtons.add(g2);
genderButtons.add(g3);
gender_panel_BG.addMouseListener(gender);
content.add(gender_panel, gbc);
/////////////////////////////////Gender Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Race Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel race_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
race_panel_BG.setOpaque( false );
JLabel race_panel_label = new JLabel("Race");
race_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
race_panel_label.setForeground(Color.white);
race_panel_label.setOpaque(false);
JPanel race_panel_body = new JPanel(new GridLayout(5, 8));
race_panel_body.setBackground(Color.WHITE);
race_panel_BG.add(race_panel_label, BorderLayout.NORTH);
JPanel race_panel = new JPanel(new GridLayout(2, 1));
//race_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//race_panel.setBackground(Color.GREEN);
race_panel.setOpaque(false);
race_panel.add(race_panel_BG);
race_panel.add(race_panel_body);
for (int i=0; i <= 60; i++){
ImageIcon RCicon = new ImageIcon("headshot.jpg");
Image RCimg = RCicon.getImage();
RCimg = RCimg.getScaledInstance(40, 40, java.awt.Image.SCALE_SMOOTH);
final ImageIcon RCiconSM = new ImageIcon(RCimg);
JButton button = new JButton(RCiconSM);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
race_panel_body.add(button);
};//for loop
MouseAdapter race = new MouseAdapterMod();
race_panel_body.addMouseListener(race);
content.add(race_panel, gbc);
/////////////////////////////////Race Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Class Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel class_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
class_panel_BG.setOpaque( false );
JLabel class_panel_label = new JLabel("Class");
class_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
class_panel_label.setForeground(Color.white);
class_panel_label.setOpaque(false);
JPanel class_panel_body = new JPanel(new GridLayout(5, 8));
class_panel_body.setBackground(Color.WHITE);
class_panel_BG.add(class_panel_label, BorderLayout.NORTH);
JPanel class_panel = new JPanel(new GridLayout(2, 1));
//class_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//class_panel.setBackground(Color.GREEN);
class_panel.setOpaque(false);
class_panel.add(class_panel_BG);
class_panel.add(class_panel_body);
for (int g=0; g <= 50; g++){
ImageIcon CCicon = new ImageIcon("headshot.jpg");
Image CCimg = CCicon.getImage();
CCimg = CCimg.getScaledInstance(40, 40, java.awt.Image.SCALE_SMOOTH);
final ImageIcon CCiconSM = new ImageIcon(CCimg);
JButton cbutton = new JButton(CCiconSM);
cbutton.setBorder(BorderFactory.createEmptyBorder());
cbutton.setContentAreaFilled(false);
class_panel_body.add(cbutton);
};//for loop
MouseAdapter cclass = new MouseAdapterMod();
class_panel_body.addMouseListener(cclass);
content.add(class_panel, gbc);
/////////////////////////////////Class Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Base Stats Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel base_stats_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
base_stats_panel_BG.setOpaque( false );
JLabel base_stats_panel_label = new JLabel("Base Attributes");
base_stats_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
base_stats_panel_label.setForeground(Color.white);
base_stats_panel_label.setOpaque(false);
JPanel base_stats_panel_body = new JPanel(new GridLayout(1, 2));
base_stats_panel_body.setBackground(Color.WHITE);
base_stats_panel_BG.add(base_stats_panel_label, BorderLayout.NORTH);
JPanel base_stats_panel = new JPanel(new GridLayout(2, 1));
//base_stats_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//base_stats_panel.setBackground(Color.GREEN);
base_stats_panel.setOpaque(false);
base_stats_panel.add(base_stats_panel_BG);
base_stats_panel.add(base_stats_panel_body);
MouseAdapter base_stats = new MouseAdapterMod();
base_stats_panel_body.addMouseListener(base_stats);
content.add(base_stats_panel, gbc);
/////////////////////////////////Base Stats Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Merits Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel merits_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
merits_panel_BG.setOpaque( false );
JLabel merits_panel_label = new JLabel("Advantages and Disadvantages");
merits_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
merits_panel_label.setForeground(Color.white);
merits_panel_label.setOpaque(false);
JPanel merits_panel_body = new JPanel(new BorderLayout());
merits_panel_body.setBackground(Color.WHITE);
merits_panel_BG.add(merits_panel_label, BorderLayout.NORTH);
JPanel merits_panel = new JPanel(new GridLayout(2, 1));
//merits_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//merits_panel.setBackground(Color.GREEN);
merits_panel.setOpaque(false);
merits_panel.add(merits_panel_BG);
merits_panel.add(merits_panel_body);
MouseAdapter merits = new MouseAdapterMod();
merits_panel_body.addMouseListener(merits);
content.add(merits_panel, gbc);
/////////////////////////////////Merits Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Group Panel Nest Begin//////////////////////////////////////////////////////////////
JPanel viewData = new JPanel(new GridLayout(5, 1));
viewData.add(gender_panel);
viewData.add(race_panel);
viewData.add(class_panel);
viewData.add(base_stats_panel);
viewData.add(merits_panel);
panel.add(new JScrollPane(viewData));
return panel;
/////////////////////////////////Group Panel Nest End//////////////////////////////////////////////////////////////
}//end right pane
/////////////////////////////////Right Panel Nest End//////////////////////////////////////////////////////////////
public class MouseAdapterMod extends MouseAdapter {
// usually better off with mousePressed rather than clicked
public void mousePressed(MouseEvent e) {
//System.out.println(e.getSource());
System.out.println("A mouse was pressed");
if (e.getSource() == "gender_panel_BG"){
gender_panel_body.setVisible(!gender_panel_body.isVisible());
}//end of if (e.getSource() == "gender")
}//end of mousePressed(MouseEvent e)
}//end of MouseAdapterMod extends MouseAdapter
}//end master panel set
}//end master class
Now I need to figure out how to select multiple JButtons. It's not quite a check box, as I want to have images instead of tick boxes.
JToggleButton, the parent of JCheckBox, works well for this, as each button knows its selected state. You can nest GridLayout instances in a vertical Box, as shown below.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
/** #see http://stackoverflow.com/a/16733710/230513 */
public class Test {
private static final int N = 4;
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box b = new Box(BoxLayout.Y_AXIS);
b.add(createPanel());
b.add(createPanel());
f.add(new JScrollPane(b){
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 500);
}
});
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JPanel createPanel() {
JPanel p = new JPanel(new GridLayout(N, N));
p.setBorder(new TitledBorder(String.valueOf(p.hashCode())));
for (int i = 0; i < N * N; i++) {
p.add(createButton());
}
return p;
}
private JToggleButton createButton() {
JToggleButton b = new JToggleButton(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
});
b.setIcon(UIManager.getIcon("html.pendingImage"));
b.setText(String.valueOf(b.hashCode()));
b.setHorizontalTextPosition(JToggleButton.CENTER);
b.setVerticalTextPosition(JToggleButton.BOTTOM);
return b;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}

Categories