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

/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./

Related

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

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

Buttons are being hidden by background image

I have set a background image on a JPanel but when i try to add buttons and selects to the custom background panel the buttons are hidden until i move the mouse over the buttons. I have included the code snippets below.
Below is my customized JPanel
package au.com.tankwarz.view.custompanels;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class BackgroundPanel extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1659728640545162103L;
public BackgroundPanel()
{
}
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(loadBackgroundImage(), 0, 0, this);
g2d.dispose();
}
private static BufferedImage loadBackgroundImage()
{
BufferedImage bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Paint a gradient from top to bottom
GradientPaint gp = new GradientPaint( 0, 0, Color.BLACK, 0, 600, new Color(0, 0, 255).darker( ).darker() );
g2d.setPaint( gp );
g2d.fillRect( 0, 0, 800, 600 );
g2d.dispose();
return bi;
}
}
And here is where i try to use it to display the panel with the buttons on it.
package au.com.tankwarz.view;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.jdesktop.application.Application;
import au.com.tankwarz.view.custompanels.BackgroundPanel;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;
public class NewGamePanel extends BackgroundPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel numberOfPlayersLable;
private JComboBox numberOfPlayersCB;
private JButton cancelButton;
private JButton createPlayersButton;
private JComboBox numberOfTanksCB;
private JLabel numberOfTanksLable;
private JComboBox numberOfRoundsCB;
private JLabel numberOfRounds;
public static final String[] numberOfPlayersCBValues = new String[] { "Two", "Three", "Four" };
public static final String[] numberOfRoundsCBValues = new String[] { "One", "Two", "Three", "Four" };
public static final String[] numberOfTanksCBValues = new String[] { "One", "Two", "Three", "Four" };
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//new NewGamePanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new NewGamePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public NewGamePanel() {
super();
initGUI();
}
private void initGUI() {
try {
AnchorLayout thisLayout = new AnchorLayout();
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(800, 600));
this.setSize(800, 600);
this.setOpaque(true);
this.setName("this");
{
numberOfPlayersLable = new JLabel();
this.add(numberOfPlayersLable, new AnchorConstraint(144, 320, 201, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfPlayersLable.setName("numberOfPlayersLable");
numberOfPlayersLable.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfPlayersCBModel =
new DefaultComboBoxModel(numberOfPlayersCBValues);
numberOfPlayersCB = new JComboBox();
this.add(numberOfPlayersCB, new AnchorConstraint(125, 697, 219, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfPlayersCB.setModel(numberOfPlayersCBModel);
numberOfPlayersCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
numberOfRounds = new JLabel();
this.add(numberOfRounds, new AnchorConstraint(298, 371, 355, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfRounds.setName("numberOfRounds");
numberOfRounds.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfRoundsCBModel =
new DefaultComboBoxModel(numberOfRoundsCBValues);
numberOfRoundsCB = new JComboBox();
this.add(numberOfRoundsCB, new AnchorConstraint(283, 697, 366, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfRoundsCB.setModel(numberOfRoundsCBModel);
numberOfRoundsCB.setName("numberOfRoundsCB");
numberOfRoundsCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
numberOfTanksLable = new JLabel();
this.add(numberOfTanksLable, new AnchorConstraint(453, 320, 509, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfTanksLable.setName("numberOfTanksLable");
numberOfTanksLable.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfTanksCBModel =
new DefaultComboBoxModel(numberOfTanksCBValues);
numberOfTanksCB = new JComboBox();
this.add(numberOfTanksCB, new AnchorConstraint(437, 697, 520, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfTanksCB.setModel(numberOfTanksCBModel);
numberOfTanksCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
createPlayersButton = new JButton();
this.add(createPlayersButton, new AnchorConstraint(795, 758, 878, 511, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
createPlayersButton.setName("createPlayersButton");
createPlayersButton.setPreferredSize(new java.awt.Dimension(99, 25));
}
{
cancelButton = new JButton();
this.add(cancelButton, new AnchorConstraint(795, 248, 878, 128, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
cancelButton.setName("cancelButton");
cancelButton.setPreferredSize(new java.awt.Dimension(48, 25));
}
Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setCreatePlayersButtonActionListener(ActionListener actionListener)
{
createPlayersButton.addActionListener(actionListener);
}
public void setCancelButtonActionListener(ActionListener actionListener)
{
cancelButton.addActionListener(actionListener);
}
public JComboBox getNumberOfPlayersCB()
{
return numberOfPlayersCB;
}
public void setNumberOfPlayersCB(JComboBox numberOfPlayersCB)
{
this.numberOfPlayersCB = numberOfPlayersCB;
}
public JComboBox getNumberOfTanksCB()
{
return numberOfTanksCB;
}
public void setNumberOfTanksCB(JComboBox numberOfTanksCB)
{
this.numberOfTanksCB = numberOfTanksCB;
}
public JComboBox getNumberOfRoundsCB()
{
return numberOfRoundsCB;
}
public void setNumberOfRoundsCB(JComboBox numberOfRoundsCB)
{
this.numberOfRoundsCB = numberOfRoundsCB;
}
}
Any help would be appreciate as i have been struggling with this for a while.
Don't change the state of the component from within any paintXxx method, this could cause a repaint event to be triggered, repeating the process until your CPU is running hot.
Never change the opacity state of the component from within any paintXxx, this will cause a cascading series of repaint's as Swing suddenly starts trying to figure out what components are now visible behind the current one...
Don't dispose of a Graphics context you didn't create, doing so could prevent what ever you paint after it not to be rendered on some systems.
Try not to create the background image on each paint cycle, this is not only expensive from memory point of view, but also expensive from a time point of view
I'm not sure why you flipping the opacity state, you don't really want it to be transparent. Simply call super.paintComponent to prepare the graphics state and then draw your image on top.
You should also avoid using setPreferredSize, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details...
Just illustrate the point, this is what you code produces (after I corrected the paint issues)
This is what my test code produces
Updated with test code
import com.apple.eawt.Application;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BackgroundPanel extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//new NewGamePanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new NewGamePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public BackgroundPanel() {
}
private static BufferedImage bi;
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(loadBackgroundImage(), 0, 0, this);
g2d.dispose();
}
private static BufferedImage loadBackgroundImage() {
if (bi == null) {
bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Paint a gradient from top to bottom
GradientPaint gp = new GradientPaint(0, 0, Color.BLACK, 0, 600, new Color(0, 0, 255).darker().darker());
g2d.setPaint(gp);
g2d.fillRect(0, 0, 800, 600);
g2d.dispose();
}
return bi;
}
public static class NewGamePanel extends BackgroundPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel numberOfPlayersLable;
private JComboBox numberOfPlayersCB;
private JButton cancelButton;
private JButton createPlayersButton;
private JComboBox numberOfTanksCB;
private JLabel numberOfTanksLable;
private JComboBox numberOfRoundsCB;
private JLabel numberOfRounds;
public static final String[] numberOfPlayersCBValues = new String[]{"Two", "Three", "Four"};
public static final String[] numberOfRoundsCBValues = new String[]{"One", "Two", "Three", "Four"};
public static final String[] numberOfTanksCBValues = new String[]{"One", "Two", "Three", "Four"};
public NewGamePanel() {
super();
initGUI();
}
private void initGUI() {
try {
GridBagLayout thisLayout = new GridBagLayout();
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(800, 600));
this.setSize(800, 600);
this.setOpaque(true);
this.setName("this");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
{
numberOfPlayersLable = new JLabel();
this.add(numberOfPlayersLable, gbc);
numberOfPlayersLable.setName("numberOfPlayersLable");
}
{
ComboBoxModel numberOfPlayersCBModel
= new DefaultComboBoxModel(numberOfPlayersCBValues);
numberOfPlayersCB = new JComboBox();
this.add(numberOfPlayersCB, gbc);
numberOfPlayersCB.setModel(numberOfPlayersCBModel);
}
{
numberOfRounds = new JLabel();
this.add(numberOfRounds, gbc);
numberOfRounds.setName("numberOfRounds");
}
{
ComboBoxModel numberOfRoundsCBModel
= new DefaultComboBoxModel(numberOfRoundsCBValues);
numberOfRoundsCB = new JComboBox();
this.add(numberOfRoundsCB, gbc);
numberOfRoundsCB.setModel(numberOfRoundsCBModel);
numberOfRoundsCB.setName("numberOfRoundsCB");
}
{
numberOfTanksLable = new JLabel();
this.add(numberOfTanksLable, gbc);
numberOfTanksLable.setName("numberOfTanksLable");
}
{
ComboBoxModel numberOfTanksCBModel
= new DefaultComboBoxModel(numberOfTanksCBValues);
numberOfTanksCB = new JComboBox();
this.add(numberOfTanksCB, gbc);
numberOfTanksCB.setModel(numberOfTanksCBModel);
}
{
createPlayersButton = new JButton();
this.add(createPlayersButton, gbc);
createPlayersButton.setName("createPlayersButton");
}
{
cancelButton = new JButton();
this.add(cancelButton, gbc);
cancelButton.setName("cancelButton");
}
// Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setCreatePlayersButtonActionListener(ActionListener actionListener) {
createPlayersButton.addActionListener(actionListener);
}
public void setCancelButtonActionListener(ActionListener actionListener) {
cancelButton.addActionListener(actionListener);
}
public JComboBox getNumberOfPlayersCB() {
return numberOfPlayersCB;
}
public void setNumberOfPlayersCB(JComboBox numberOfPlayersCB) {
this.numberOfPlayersCB = numberOfPlayersCB;
}
public JComboBox getNumberOfTanksCB() {
return numberOfTanksCB;
}
public void setNumberOfTanksCB(JComboBox numberOfTanksCB) {
this.numberOfTanksCB = numberOfTanksCB;
}
public JComboBox getNumberOfRoundsCB() {
return numberOfRoundsCB;
}
public void setNumberOfRoundsCB(JComboBox numberOfRoundsCB) {
this.numberOfRoundsCB = numberOfRoundsCB;
}
}
}

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:

JComboBox does not behave same as JTextField. How can i have it look similar?

I have this following combo box, where i am able to create my combo box with items etc, but the look is not same as JTextField. How can i make JCombobox look same like JTextField?
MyComboBox.java:
import java.awt.Color;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.plaf.basic.BasicComboBoxUI;
public class MyComboBox extends JComboBox {
public MyComboBox(String[] name) {
Border border = BorderFactory.createEmptyBorder(11, 11, 11, 11);
JComboBox cb = new JComboBox(name);
cb.setUI(new BasicComboBoxUI() {
#Override
protected JButton createArrowButton() {
return new JButton() {
#Override
public int getWidth() {
return 0;
}
};
}
});
setModel(cb.getModel());
setOpaque(false);
setBorder(new LineBorder(Color.black, 1, true));
//setBackground(Color.white);
setVisible(true);
}
// public void paintComponent(Graphics g) {
// super.paintComponent(g);
// g.setColor(new Color(red, green, blue) );
// g.fillOval(125, 125, 50, 50);
// }
}
best of all could be use Look and Feels
JComboBox has two states, JComboBox can be Editable and Non_Editable (default)
without CustomUI (as example by #aterai), but Look and Feel sensitive, only for Metal Look and Feel
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.MetalComboBoxButton;
public class MyComboBox {
private Vector<String> listSomeString = new Vector<String>();
private JComboBox someComboBox = new JComboBox(listSomeString);
private JComboBox editableComboBox = new JComboBox(listSomeString);
private JComboBox non_EditableComboBox = new JComboBox(listSomeString);
private JFrame frame;
public MyComboBox() {
listSomeString.add("-");
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
//
someComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
someComboBox.setFont(new Font("Serif", Font.BOLD, 16));
someComboBox.setEditable(true);
someComboBox.getEditor().getEditorComponent().setBackground(Color.YELLOW);
((JTextField) someComboBox.getEditor().getEditorComponent()).setBackground(Color.YELLOW);
//
editableComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
editableComboBox.setFont(new Font("Serif", Font.BOLD, 16));
editableComboBox.setEditable(true);
JTextField text = ((JTextField) editableComboBox.getEditor().getEditorComponent());
text.setBackground(Color.YELLOW);
JComboBox coloredArrowsCombo = editableComboBox;
Component[] comp = coloredArrowsCombo.getComponents();
for (int i = 0; i < comp.length; i++) {
if (comp[i] instanceof MetalComboBoxButton) {
MetalComboBoxButton coloredArrowsButton = (MetalComboBoxButton) comp[i];
coloredArrowsButton.setBackground(null);
break;
}
}
//
non_EditableComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
non_EditableComboBox.setFont(new Font("Serif", Font.BOLD, 16));
//
frame = new JFrame();
frame.setLayout(new GridLayout(0, 1, 10, 10));
frame.add(someComboBox);
frame.add(editableComboBox);
frame.add(non_EditableComboBox);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
UIManager.put("ComboBox.background", new ColorUIResource(Color.yellow));
UIManager.put("JTextField.background", new ColorUIResource(Color.yellow));
UIManager.put("ComboBox.selectionBackground", new ColorUIResource(Color.magenta));
UIManager.put("ComboBox.selectionForeground", new ColorUIResource(Color.blue));
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyComboBox aCTF = new MyComboBox();
}
});
}
}
I guess you are meaning RoundedCornerBorder:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.*;
public class RoundedComboBoxTest {
public JComponent makeUI() {
UIManager.put("Panel.background", Color.GRAY);
UIManager.put("ComboBox.foreground", Color.BLACK);
UIManager.put("ComboBox.background", Color.GRAY);
UIManager.put("ComboBox.selectionForeground", Color.WHITE);
UIManager.put("ComboBox.selectionBackground", Color.GRAY);
UIManager.put("ComboBox.buttonDarkShadow", Color.BLACK);
UIManager.put("ComboBox.border", new RoundedCornerBorder());
DefaultComboBoxModel<String> m = new DefaultComboBoxModel<>();
m.addElement("1234");
m.addElement("5555555555555555555555");
m.addElement("6789000000000");
JComboBox<String> combo = new JComboBox<>(m);
combo.setUI(new BasicComboBoxUI() {
#Override protected JButton createArrowButton() {
JButton b = super.createArrowButton();
b.setContentAreaFilled(false);
b.setBackground(Color.GRAY);
b.setBorder(BorderFactory.createEmptyBorder());
return b;
}
});
Object o = combo.getAccessibleContext().getAccessibleChild(0);
((JComponent)o).setBorder(
BorderFactory.createMatteBorder(0,1,1,1,Color.BLACK));
JPanel p = new JPanel(new BorderLayout());
p.add(combo, BorderLayout.NORTH);
p.setOpaque(true);
p.setBackground(Color.GRAY);
p.setBorder(BorderFactory.createEmptyBorder(15,15,15,15));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new RoundedComboBoxTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class RoundedCornerBorder extends AbstractBorder {
#Override public void paintBorder(
Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2 = (Graphics2D)g.create();
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int r = 12;
Area round = new Area(
new RoundRectangle2D.Float(x, y, width-1, height-1, r, r));
Rectangle b = round.getBounds();
b.setBounds(b.x, b.y + r, b.width, b.height - r);
round.add(new Area(b));
Container parent = c.getParent();
if(parent!=null) {
g2.setColor(parent.getBackground());
Area corner = new Area(new Rectangle2D.Float(x, y, width, height));
corner.subtract(round);
g2.fill(corner);
}
g2.setColor(Color.BLACK);
g2.draw(round);
g2.dispose();
}
#Override public Insets getBorderInsets(Component c) {
return new Insets(4, 8, 4, 8);
}
#Override public Insets getBorderInsets(Component c, Insets insets) {
insets.left = insets.right = 8;
insets.top = insets.bottom = 4;
return insets;
}
}
You will have to define your own custom renderer, check out this tutorial as how to define one.
You can also set your background and foreground in your MyComboBox.java but that will not have an impact on selected item foreground, background.

Categories

Resources