I would like to simply add a JLabel into a JButton and center it horizontally. I've tried many thing but the text stay left side... Here is my code :
JLabel labeltest = new JLabel("Simple test");
JButton myButton = new JButton();
myButton.setHorizontalTextPosition(SwingConstants.CENTER);
myButton.add(labeltest);
Create an Icon of the text and give the Icon the foreground/background colors that you want.
I tried this but the problem comes when I had to do button.setenabled(false); after this the text becomes almost invisible
You can set the disabled Icon to be the same as the Icon and it will not be painted in the disabled state:
JButton button = new JButton( new ImageIcon(...) );
button.setDisabledIcon( button.getIcon() );
button.setEnabled(false);
Of course the problem with this approach is that the user doesn't know the button is disabled. So in reality you would need 2 icons:
one for the normal state
one for the disabled state
A JButton is also a java.awt.Container. Thus you can set a layout manager. E.g. you can use a GridBagLayout.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JToggleButton toggleButton = new JToggleButton();
JLabel jLabel = new JLabel("3");
JToggleButton.ToggleButtonModel toggleButtonModel = (JToggleButton.ToggleButtonModel) toggleButton.getModel()
ToggleForegroundAction toggleForegroundAction =
new ToggleForegroundAction(toggleButtonModel, Color.WHITE, Color.RED);
toggleForegroundAction.setComponent(jLabel);
toggleButton.setAction(toggleForegroundAction);
toggleButton.setLayout(new GridBagLayout());
toggleButton.add(jLabel, new GridBagConstraints());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
panel.add(toggleButton, BorderLayout.CENTER);
Container contentPane = frame.getContentPane();
contentPane.add(panel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
An action that toggles the label's foreground color might look like this
public class ToggleForegroundAction extends AbstractAction {
private JComponent component;
private JToggleButton.ToggleButtonModel toggleButtonModel;
private final Color selectedColor;
private final Color unselectedColor;
public ToggleForegroundAction(JToggleButton.ToggleButtonModel toggleButtonModel, Color selectedColor, Color unselectedColor) {
this.toggleButtonModel = toggleButtonModel;
this.selectedColor = selectedColor;
this.unselectedColor = unselectedColor;
}
public void setComponent(JComponent component) {
this.component = component;
setForeground(component, toggleButtonModel.isSelected());
}
#Override
public void actionPerformed(ActionEvent e) {
JComponent targetComponent = this.component;
if (targetComponent == null) {
targetComponent = (JComponent) e.getSource();
}
setForeground(targetComponent, toggleButtonModel.isSelected());
}
private void setForeground(JComponent targetComponent, boolean isSelected) {
Color foreground;
if (isSelected) {
foreground = selectedColor;
} else {
foreground = unselectedColor;
}
targetComponent.setForeground(foreground);
}
}
=>
Related
So, basically, the main idea for this project is that I wanted to change the background color by using the jcombobox method. and the background will change with the option chosen when the button(proceed) is clicked. The background color chosen will then be implemented to the next page when the button is clicked. The background that im talking about is the background for all the JPanel(including the other page's JPanel). If (getsource() == f2.btenter2) , it will go to f2(2nd file) btenter2(button)'s when clicked.
public class MainPage extends JFrame implements ActionListener {
JLabel lbTitle, lbWelcome, lbSelect;
JComboBox cbColor;
public Color color[] = {RED, GREEN, BLUE, YELLOW, GRAY};
public String clr[] ={"RED","GREEN","BLUE","YELLOW","GRAY"};
public int index;
JButton btProceed;
public static void main(String[] args) {
MainPage f1 = new MainPage();
f1.setSize(800, 500);
f1.setTitle("Java Assignment");
f1.setVisible(true);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public MainPage() {
lbTitle = new JLabel("Rock-Paper-Scissors-Lizard-Spock");
lbWelcome = new JLabel("Welcome!");
lbSelect = new JLabel("Please select the background color before you proceed:");
lbWelcome.setFont(new Font("Courier", Font.PLAIN, 18));lbSelect.setFont(new Font("Courier", Font.PLAIN, 15)); cbColor = new JComboBox(color);btProceed = new JButton("Proceed");
//1st panel on the north side to set the title
JPanel p1 = new JPanel();
p1.add(lbTitle);
p1.setBackground(new Color(255, 106, 0));
//2nd panel on the center position
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(14, 1));JPanel a1 = new JPanel();
JPanel a2 = new JPanel();
JPanel a3 = new JPanel();
JPanel e1 = new JPanel();
a1.add(lbWelcome);
a2.add(lbSelect);
a3.add(cbColor);
p2.add(e1);
p2.add(a1);
p2.add(a2);
p2.add(a3);
JPanel p3 = new JPanel();
p3.add(btProceed);
setLayout(new BorderLayout());
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.CENTER);
add(p3, BorderLayout.SOUTH);
btProceed.addActionListener(this);
cbColor.addActionListener(this);
color().addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
index = cbColor.getSelectedIndex(); //to get the index
if (e.getSource()==cbColor) {
index = cbColor.getSelectedIndex();
p2.setBackground(color[index]);
a1.setBackground(color[index]);
a2.setBackground(color[index]);
a3.setBackground(color[index]);
e1.setBackground(color[index]);
e1.setBackground(color[index]);
p3.setBackground(color[index]);
}
Team f2 = new Team();
GamePage f3 = new GamePage();
GamePage2 f4 = new GamePage2();
Result f5 = new Result();
if (e.getSource()==btProceed) {
this.setVisible(false);
f2.setVisible(true);
f2.setSize(800, 500);
f2.p2.setBackground(color[index]);
f2.p3.setBackground(color[index]);
f2.p4.setBackground(color[index]);
// btenter2 is located in the second file under the same package
if (e.getSource()==f2.btenter2){
this.setVisible(false);
f3.setVisible(true);
f3.setSize(800,500);
f3.p2.setBackground(color[index]);
f3.p3.setBackground(color[index]);
f3.p4.setBackground(color[index]);
f3.p5.setBackground(color[index]);}
if (e.getSource()==f3.btNext){this.setVisible(false);
f4.setVisible(true);
f4.setSize(800,500);
f4.p2.setBackground(color[index]);
f4.p3.setBackground(color[index]);
f4.p4.setBackground(color[index]);
f4.p5.setBackground(color[index]); }
if (e.getSource() == f4.btResult)
{
this.setVisible(false);
f5.setVisible(true);
f5.setSize(800,500);
f5.p2.setBackground(color[index]);
f5.p3.setBackground(color[index]);
f5.p4.setBackground(color[index]);
f5.p5.setBackground(color[index]);}}
Introduction
I started working on this before I saw the OP's latest edit.
Here's the GUI I came up with.
Here's the GUI when you pick red.
Here's the GUI when you pick yellow.
The red GUI uses white text for better contrast. Some background colors work better with black text.
I didn't create an ActionListener for the button. I wanted to demonstrate two things.
A JComboBox can hold any class, not just the String class.
An ActionListener that changes the background and foreground color of a JPanel.
Explanation
When creating a Swing GUI, or almost any Java application, I use the model / view / controller pattern. This pattern allows me to focus on one part of the application at a time and helps me separate my concerns.
So, the first thing I did was create a ColorPair class. The ColorPair class holds a background color, a foreground color, and a String name of the background color. When passing class instances to a JComboBox, the class toString method is used to display the combo box options.
Next, I created a Pallete class. The Pallete class holds a List of ColorPair instances.
Once I created the model, I started on the view. I reorganized the OP's view code so it was easier to read. Generally, I keep all the methods for each Swing component together, and create the Swing components in the order they appear on the JPanel.
I separated the JFrame and JPanel creation into separate methods.
After I was satisfied with the view, I wrote the ActionListener for the JComboBox. I didn't need to pass all the components to the ActionListener class since I could get the children components of the JPanel.
The propagateColors method of the ActionListener is recursive. This is one of those rare instances where a recursive method makes sense in the real world since you can have JPanels as children of a JPanel.
Here's the complete runnable code. I hope it's helpful.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
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 BackgroundColorGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new BackgroundColorGUI());
}
private ColorPair colorPair;
private JPanel mainPanel;
private JPanel buttonPanel;
private Pallete pallete;
public BackgroundColorGUI() {
this.pallete = new Pallete();
}
#Override
public void run() {
JFrame frame = new JFrame("Java Assignment");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTitlePanel(), BorderLayout.BEFORE_FIRST_LINE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
this.buttonPanel = createButtonPanel();
frame.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTitlePanel() {
//1st panel on the north side to set the title
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel lbTitle = new JLabel("Rock-Paper-Scissors-Lizard-Spock");
lbTitle.setFont(panel.getFont().deriveFont(Font.BOLD, 24f));
panel.add(lbTitle);
panel.setBackground(new Color(255, 106, 0));
return panel;
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.setLayout(new GridLayout(0, 1, 5, 5));
JPanel e1 = new JPanel();
JLabel dummy = new JLabel(" ");
e1.add(dummy);
panel.add(e1);
JPanel a1 = new JPanel();
JLabel lbWelcome = new JLabel("Welcome!");
lbWelcome.setFont(new Font("Courier", Font.PLAIN, 18));
a1.add(lbWelcome);
panel.add(a1);
JPanel a2 = new JPanel();
JLabel lbSelect = new JLabel("Please select the background "
+ "color before you proceed:");
lbSelect.setFont(new Font("Courier", Font.PLAIN, 15));
a2.add(lbSelect);
panel.add(a2);
JPanel a3 = new JPanel();
JComboBox<ColorPair> cbColor = new JComboBox<ColorPair>();
List<ColorPair> colors = pallete.getColors();
for (ColorPair colorPair : colors) {
cbColor.addItem(colorPair);
}
cbColor.addActionListener(new ColorListener(this));
a3.add(cbColor);
panel.add(a3);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
JButton btProceed = new JButton("Proceed");
panel.add(btProceed);
return panel;
}
public JPanel getMainPanel() {
return mainPanel;
}
public JPanel getButtonPanel() {
return buttonPanel;
}
public class ColorListener implements ActionListener {
private BackgroundColorGUI frame;
public ColorListener(BackgroundColorGUI frame) {
this.frame = frame;
}
#Override
public void actionPerformed(ActionEvent event) {
JComboBox<?> comboBox = (JComboBox<?>) event.getSource();
colorPair = (ColorPair) comboBox.getSelectedItem();
propagateColors(frame.getMainPanel(), colorPair);
propagateColors(frame.getButtonPanel(), colorPair);
}
private void propagateColors(JPanel panel, ColorPair colorPair) {
panel.setBackground(colorPair.getBackgroundColor());
panel.setForeground(colorPair.getForegroundColor());
Component[] components = panel.getComponents();
for (Component component : components) {
if (component instanceof JPanel) {
JPanel childPanel = (JPanel) component;
propagateColors(childPanel, colorPair);
}
component.setBackground(colorPair.getBackgroundColor());
component.setForeground(colorPair.getForegroundColor());
}
}
}
public class Pallete {
private final List<ColorPair> colors;
public Pallete() {
this.colors = generatePalleteFactory();
}
private List<ColorPair> generatePalleteFactory() {
List<ColorPair> colors = new ArrayList<>();
colors.add(new ColorPair("Light Grey",
new Color(238, 239, 238), Color.BLACK));
colors.add(new ColorPair("Red", Color.RED, Color.WHITE));
colors.add(new ColorPair("Green", Color.GREEN, Color.BLACK));
colors.add(new ColorPair("Blue", Color.BLUE, Color.WHITE));
colors.add(new ColorPair("Yellow", Color.YELLOW, Color.BLACK));
colors.add(new ColorPair("Grey",
new Color(153, 153, 153), Color.WHITE));
return colors;
}
public List<ColorPair> getColors() {
return colors;
}
}
public class ColorPair {
private final Color backgroundColor;
private final Color foregroundColor;
private final String backgroundColorName;
public ColorPair(String backgroundColorName,
Color backgroundColor, Color foregroundColor) {
this.backgroundColorName = backgroundColorName;
this.backgroundColor = backgroundColor;
this.foregroundColor = foregroundColor;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public Color getForegroundColor() {
return foregroundColor;
}
public String getBackgroundColorName() {
return backgroundColorName;
}
#Override
public String toString() {
return getBackgroundColorName();
}
}
}
The background assigned by the renderer is overriden by the selection background color of the JList that is used in the popup for the combo box.
JComboBox cbColor = new JComboBox(...);
Object child = cbColor.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
list.setSelectionBackground(Color.RED);
Credits to this answer
My Jframe is setting every component at the middle of the screen even if i set a specific location...
for exmaple, the button and the searchbar are right next to each other.
Here is the image of the program:
thanks!
It really seems easy but i can't figure out why it doesn't work
private String msg;
private JFrame frame;
private JButton button;
private JPanel panel;
private JTextField searchBar;
private JLabel name;
private JLabel logo;
public GUI() {
this.frame = new JFrame();
this.panel = new JPanel();
this.panel.setBorder(BorderFactory.createEmptyBorder(300, 300, 300, 300));
//this.panel.setLayout(new GridLayout(10, 10));
this.frame.add(panel, BorderLayout.CENTER);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setTitle("emdb (ezon's movie database)");
Icon icon = new ImageIcon("images/search.png");
this.button = new JButton(icon);
this.button.setBounds(100, 20, 25, 25);
this.button.addActionListener(this);
this.searchBar = new JTextField(30);
this.searchBar.setBounds(100, 20, 200, 25);
this.name = new JLabel();
this.name.setBounds(50, 20, 80, 25);
ImageIcon log = new ImageIcon("images/logo.png");
this.logo = new JLabel(log);
this.logo.setBounds(100, 0, 300, 150);
}
public void clearScreen() {
this.panel.removeAll();
this.panel.revalidate();
this.panel.repaint();
}
public void searchScreen() {
this.panel.add(this.searchBar);
this.panel.add(this.button);
this.panel.add(this.logo);
this.frame.pack();
this.frame.setVisible(true);
}
public void searchedScreen() {
this.panel.add(this.name);
}
public String getMsg() {
return(this.msg);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Searched: " + this.searchBar.getText());
this.name.setText(this.searchBar.getText());
this.msg = this.searchBar.getText();
clearScreen();
searchedScreen();
}
Swing was designed to be used with layout managers.
even if i set a specific location.
The job of the layout manager is to set the size and location of the component based on the rules of the layout manager. So your setBounds() statements will be overridden. Don't attempt to use setBounds().
the button and the searchbar are right next to each other
The default layout manager for a JPanel is the FlowLayout, which does exactly that.
this.frame.add(panel, BorderLayout.CENTER);
Change the above statement to:
this.frame.add(panel, BorderLayout.PAGE_START);
to see a difference.
Read the section from the Swing tutorial on Layout Managers for more information and examples. Decide which layout manager (or combination of layout managers on different panels) will achieve your desired layout.
The problem: I have no control on implementing more into the histogram package, so I create an array of buttons and overlay them on top of the histogram using JLayeredPane. However, I cannot get both the histogram plot and the buttons panels to scale when the JFrame is enlarged or contracted.
The JLayedPane is composed of 2 JPanels, see MWE.
To repeat the issue, just run program and extend JFrame.
I have read the following on SO posts; jlayeredpane-with-gridlayout, jlayeredpane-with-a-layoutmanager, jlayeredpane-not-resizing-with-jframe, resize-jframe-to-jpanels-inside-jlayeredpane, automatic-content-resizing-of-jlayeredpane,
as well as the Oracle page on JLayeredPane which has some examples
As useful as these links were, I still cannot get both JPanels to extend/contract with the JFrame.
Question: Is there a way to get both JPanels in the JLayeredPane to rescale without implementing a new layout? If new layout is needed, would someone please provide a MWE on how to do such?
public class FrameDemo extends JPanel {
private JLayeredPane layeredPane;
private final int width = 800;
private final int height = 800;
private String[] layerStrings = { "Yellow (0)", "Magenta (1)", "Cyan (2)", "Red (3)", "Green (4)", "Blue (5)" };
private Color[] layerColors = { Color.yellow, Color.magenta, Color.cyan, Color.red, Color.green, Color.blue };
public FrameDemo() {
setLayout(new BorderLayout());
init();
addPanels();
add(layeredPane, BorderLayout.CENTER);
}
private void init() {
this.layeredPane = new JLayeredPane();
this.layeredPane.setPreferredSize(new Dimension(width, height));
this.layeredPane.setBorder(BorderFactory.createTitledBorder("Histogram should go here"));
this.layeredPane.setLayout(new BorderLayout());
}
private void addPanels() {
this.layeredPane.add(createHistogramPanel(), BorderLayout.CENTER, new Integer(1));
this.layeredPane.add(createButtonPanel(), BorderLayout.CENTER, new Integer(0));
this.layeredPane.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
Dimension size = layeredPane.getSize(); // get size
createHistogramPanel().setSize(size); // push size through
createButtonPanel().setSize(size); // push size trhough
// otherChildOfLayers.setSize(size); // push size trhough
layeredPane.revalidate(); // revalidate to see updates
layeredPane.repaint(); // "Always invoke repaint after
// revalidate"
}
});
}
private JPanel createHistogramPanel() {
JPanel histpanel = new JPanel();
histpanel.setLayout(new GridLayout(2, 3));
for (int i = 0; i < layerStrings.length; i++) {
JLabel label = createColoredLabel(layerStrings[i], layerColors[i]);
histpanel.add(label);
}
histpanel.setOpaque(false);
histpanel.setBounds(10, 10, width, height);
return histpanel;
}
private JLabel createColoredLabel(String text, Color color) {
JLabel label = new JLabel("");
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(color);
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.setPreferredSize(new Dimension(120, 120));
return label;
}
private JPanel createButtonPanel() {
ButtonGroup buttons = new ButtonGroup();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2, 3));
for (int i = 0; i < 6; i++) {
final int placer = i + 1;
JButton freshButton = new JButton();
freshButton.addActionListener(e -> {
System.out.println("Button " + placer + " clicked");
});
freshButton.setText("Button " + (i + 1));
freshButton.setOpaque(true);
freshButton.setContentAreaFilled(false);
freshButton.setBorderPainted(false);
freshButton.setBounds(new Rectangle(132, 75 + (i * 20), 40, 20));
buttonPanel.add(freshButton, null);
buttons.add(freshButton);
}
buttonPanel.setOpaque(false);
buttonPanel.setBounds(10, 10, width, height);
return buttonPanel;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new FrameDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Your code won't work because in componentResized you're creating new panels and applying the size to them. You need to resize the existing panels added to the layered pane. This could be done by assigning histogramPanel and buttonPanel as instance variables.
I'm trying to add a button using an JOptionPane in another button, but after I clicked the original button just keeps disappearing.
I've tried adding the JPanel manually instead of using 'handPanelNPC.getHandPanel()' by iterating through the handPanel.buttons but it stil wont work. I've checked the ArrayList size and it is already inserted properly.
LayoutTesting.java
public class LayoutTesting extends JFrame{
HandPanel handPanelNPC = new HandPanel();
public LayoutTesting(HandPanel handPanel, int type){
Container pane = getContentPane();
if (type==1){
handPanelNPC = handPanel;
}
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
validate();
repaint();
}
public LayoutTesting(){
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(handPanelNPC.getHandPanel(), BorderLayout.NORTH);
}
}
HandPanel.java
public class HandPanel implements ActionListener{
JFrame frame = null;
JPanel panel = new JPanel();
ArrayList<JButton> buttons = new ArrayList<JButton>();
public HandPanel(){
addNewButton();
panel.setLayout(new FlowLayout());
panel.add(buttons.get(0));
}
public JComponent getHandPanel(){
panel = new JPanel();
for(int i=0; i<buttons.size(); i++){
JButton button = buttons.get(i);
panel.add(button);
}
return panel;
}
public void addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40,58));
button.addActionListener(this);
buttons.add(button);
}
public void actionPerformed(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
frame,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addNewButton();
LayoutTesting frame = new LayoutTesting(this, 1);
}
}
}
Main.java
public class Main extends JFrame{
public static void main(String[] args){
LayoutTesting frame = new LayoutTesting();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
You have too many odd things happening in your code to give a simple answer.
Try debugging your own code by looking at this line in HandPanel.java:
LayoutTesting frame = new LayoutTesting(this, 1);
What does it really do? Now remove that line and the button will not disappear. Now try and work out what that line was doing, and why the button disappeared.
Also 'panel.add(buttons.get(0));' does nothing because there is never a button in the array when you make that call (You add the button afterwards in another method).
Here is a rough working demo that lets you add as many new cards as you want to the first frame, and each card has a button that will let you summon a new card.
public class LayoutTesting extends JFrame{
Container pane;
//Add card when button is pressed:
public void addCard(){
Container card = new JPanel();
card.setBackground(Color.red);
JButton newButton = addNewButton();
newButton.setBackground(Color.red);
card.add(newButton);
pane.add(card);
revalidate();
repaint();
}
//Setup window and add button:
public LayoutTesting(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
setLayout(new FlowLayout());
pane = new JPanel();
pane.setLayout(new GridBagLayout());
JButton firstButton = addNewButton();
firstButton.setBackground(Color.green);
add(pane);
add(firstButton);
}
//Create button and action listener:
public JButton addNewButton(){
JButton button = new JButton();
button.setPreferredSize(new Dimension(40, 58));
button.addActionListener(new java.awt.event.ActionListener(){
#Override
public void actionPerformed(java.awt.event.ActionEvent evt){
buttonAction(evt);
}
});
return button;
}
//Action fer each button:
public void buttonAction(ActionEvent e) {
String[] options = {"Summon", "Set", "Add Card"};
int messageType = JOptionPane.QUESTION_MESSAGE;
int code = JOptionPane.showOptionDialog(
this,
"What would you like to do?",
"Card Name",
0, messageType, null,
options, options[1]);
if (code==2){
addCard();
}
}
}
I have problem with setting JPanel and JFrame color to white, though I used panel.setBackground(Color.white). The second problem is that setting ImageIcon in JRadioButton constructor causes that JRadioButton is invisible. Here is my code:
public class proby {
static JPanel panel = new JPanel();
static JPanel panel2 = new JPanel();
private void createAndShowGUI() {
final ImageIcon zielonaikona = new ImageIcon("green2.png");
final ImageIcon czerwonaikona = new ImageIcon("red2.png");
final ImageIcon niebieskaikona = new ImageIcon("blue.png");
final ImageIcon szaraikona = new ImageIcon("grey.png");
JFrame frame1 = new JFrame("MasterMind");
final JRadioButton zielony = new JRadioButton(zielonaikona);
zielony.setBackground(Color.WHITE);
final JRadioButton czerwony = new JRadioButton("czerwony");
czerwony.setBackground(Color.white);
final JRadioButton niebieski = new JRadioButton("niebieski");
niebieski.setBackground(Color.white);
final JRadioButton szary = new JRadioButton("szary");
szary.setBackground(Color.white);
zielony.setSelected(true);
ButtonGroup gruparadio = new ButtonGroup();
gruparadio.add(zielony);
gruparadio.add(czerwony);
gruparadio.add(niebieski);
gruparadio.add(szary);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton akceptuj = new JButton("Akceptuj");
akceptuj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel label2;
if (zielony.isSelected()) {
label2 = new JLabel(zielonaikona);
} else if (czerwony.isSelected()) {
label2 = new JLabel(czerwonaikona);
} else if (szary.isSelected()) {
label2 = new JLabel(szaraikona);
} else {
label2 = new JLabel(niebieskaikona);
}
panel2.add(label2);
panel2.revalidate();
}
});
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
BoxLayout layout2 = new BoxLayout(panel2, BoxLayout.Y_AXIS);
panel.setLayout(layout);
panel2.setLayout(layout2);
panel.add(zielony);
panel.add(czerwony);
panel.add(niebieski);
panel.add(szary);
panel.add(akceptuj);
panel.setBackground(Color.WHITE);
panel2.setBackground(Color.white);
frame1.getContentPane().add(panel);
frame1.getContentPane().add(panel2);
BoxLayout layout3 = new BoxLayout(frame1.getContentPane(), BoxLayout.Y_AXIS);
frame1.setLayout(layout3);
frame1.setBackground(Color.white);
frame1.setSize(300, 300);
frame1.setVisible(true);
}
public static void main(String[] args) {
proby kk = new proby();
kk.createAndShowGUI();
}
}
If you want to set your JFrame background color to white, you have to get the ContentPane and set that to white:
frame1.getContentPane().setBackground(Color.white);
Take a look at JFrame.setBackground() not working — why?
As for the ImageIcon problem, it's probably because you don't have the image file at the path you indicated. (Which in your case is just inside the project folder).
Edit:
Now that I know what you're trying to do with the ImageIcon, I came up with this after seeing Andrew Thompson's trick
String imageText = "<html><img src=\""+this.getClass().getResource("green2.png")
.toString()+"\"></img></html>";
JRadioButton zielony = new JRadioButton(imageText);
However, it does involve you placing the images inside the src folder, not the project one.
There is only image visible without JRadioButton's hole.
The appearance is controlled by the Look & Feel dependent UI delegate, a subclass of ButtonUI. Short of writing your own replacement, you can use ColorIcon, seen here, to render the button as you like—with or without the hole. You can then update the icon using setIcon(), shown here.
Icon czerwonaikona = new ColorIcon(SIZE, Color.red);
JRadioButton czerwony = new JRadioButton("czerwony", czerwonaikona);