color of JButton - java

After reviewing many previous StackOverflow posts, I am still unable to get my JButton to be black instead of the default color. Here is what my button looks like:
And here's my code:
public void setStartButton() {
JPanel panel = this.jPanel1;
panel.setLayout(null);
JButton button = new JButton("START");
// size and location of start button
int res = java.awt.Toolkit.getDefaultToolkit().getScreenResolution();
int length = (int) Math.floor(10.0*res/25.4); // side lengths of square button
int offset = length/2; // because button should be centered...but its x and y location are given by its upper left hand corner
button.setBounds(centerX-offset, centerY-offset, length, length);
// color of start button
button.setBackground(BLACK);
button.setOpaque(true);
button.setContentAreaFilled(false);
// font
button.setFont(new Font("Arial", Font.PLAIN, 8));
button.setVisible(true);
panel.add(button);
}
By the way, when I change setContentAreaFilled to true, it makes no difference.
I know that the function is indeed being called, because the location and font info for my button is working just fine.
Any assistance would be much appreciated! Thanks!

A JButton is made of a series of layers, including the content, border and focus layers. Depending on what you're trying to do, you may need to remove all of them, for example...
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
setStartButton();
}
public void setStartButton() {
JButton button = new JButton("START");
button.setMargin(new Insets(20, 20, 20, 20));
// color of start button
button.setOpaque(true);
button.setContentAreaFilled(true);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setBackground(BLACK);
button.setForeground(WHITE);
// font
button.setFont(new Font("Arial", Font.PLAIN, 8));
add(button);
}
}
I'd also strongly encourage you to consider making use of an appropriate layout manager and using the properties of it and the JButton to generate the desired padding you need, these will work together with the font metrics, which tend to be different between systems, to generate an appropriate size for the button

Related

How can I start a newline in a JPanel when the added text are two different font sizes

So I am creating a project that is a skeleton of a Java GUI but I am having some alignment issues. When I run my code the centered top text that says "Help Page" is pushed to the left side, while the help string is shifted downwards a little bit but also pushed to the right.
My goal is to have the top text centered and underlined with the other text below it and also centered. I have tried using multiple panels but still nothing has worked, Im guessing it's the mismatching font size by I dont know. Any help is appreciated!
private void helpGUI() {
clearGUI();
helpStr = "<html><br>This is the help page where the user can come for help<html/>";
label = new JLabel("<html><u>Help Page</u></html>");
label.setFont(new Font("Times", Font.PLAIN, 24));
helpTxt = new JLabel(helpStr);
helpTxt.setFont(new Font("Times", Font.PLAIN, 16));
panel.add(label);
panel.add(helpTxt);
panel.setAlignmentX(CENTER_ALIGNMENT);
button = new JButton("Previous");
bttnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bttnPanel.add(button);
frame.add(panel);
class previousButton implements ActionListener {
public void actionPerformed (ActionEvent e) {
GUIPG1(name);
}
}
button.addActionListener(new previousButton());
}
It really depends on what you are trying to achieve (for instance, what other components is that JPanel supposed to contain. Is it just those two labels? You show a button in your code as well. Where is that supposed to be added?). Regardless, for that specific panel with the two texts on the top, you could use BoxLayout for adding your JLabels vertically, and use setAlignmentX() to set the horizontal alignment of the texts. Example below:
Edit:
Alternatively (regarding underlying and centering the text), you can use the following in the example below:
titleLbl = new JLabel("<html><u>Help Page</u></html>", SwingConstants.CENTER);
titleLbl.setFont(new Font("Times New Roman", Font.PLAIN, 24));
titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
App.java
import java.awt.*;
import java.awt.font.*;
import javax.swing.*;
import java.util.*;
public class App {
private void addComponentsToPane(Container pane) {
JLabel titleLbl = new JLabel("Help Page");
// add text attributes (i.e., underline, font family, font size, etc)
Font font = titleLbl.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
attributes.put(TextAttribute.FAMILY, "Times New Roman");
attributes.put(TextAttribute.SIZE, 24);
titleLbl.setFont(font.deriveFont(attributes));
titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
JLabel infoLbl = new JLabel("This is the help page where the user can come for help");
infoLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
infoLbl.setFont(new Font("Times New Roman", Font.PLAIN, 16));
Box box = new Box(BoxLayout.Y_AXIS);
box.add(titleLbl);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(infoLbl);
pane.add(box, BorderLayout.NORTH);
}
private void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.setSize(640, 480);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new App().createAndShowGUI();
}
});
}
}

JRadio Buttons and images

I am currently teaching myself the java language and I now learing about GUI's by using eclpise, JFrame, and window builder. I have created a GUI with two radiobutton and above them I have two labels each with a picture on them. When I click on the radiobutton on the left I want the left label to display the image and the right label to display nothing. And then when I click on the right radio button I want the label on the right to display the image. I am stuck and i've tried a few different things and was hoping for some guidance. Here is some of the code so far
JLabel lblLeft = new JLabel("");
//This is to retrieve your image and put it in the GUI
Image imgL = new ImageIcon(getClass().getResource ("schlange.gif")).getImage();
lblLeft.setIcon(new ImageIcon(imgL));
lblLeft.setPreferredSize(new Dimension(290, 26));
lblLeft.setOpaque(true);
lblLeft.setBackground(Color.BLACK);
contentPane.add(lblLeft, BorderLayout.WEST);
JLabel lblRight = new JLabel("");
//This is to retrieve your image and put it in the GUI
Image imgR = new ImageIcon(getClass().getResource("schlange.gif")).getImage();
lblRight.setIcon(new ImageIcon(imgR));
lblRight.setPreferredSize(new Dimension(290, 26));
lblRight.setBackground(Color.BLACK);
lblRight.setOpaque(true);
contentPane.add(lblRight, BorderLayout.EAST);
//To get this code to come up you click on your radio button then right click on it go down to add event
//then go to item and itemStateChanged
JRadioButton rdbtnLeft = new JRadioButton("Left");
rdbtnLeft.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0)
{
lblLeft.setIcon((Icon) imgL);
}
});
buttonGroupLeftRight.add(rdbtnLeft);
rdbtnLeft.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(rdbtnLeft);
JRadioButton rdbtnRight = new JRadioButton("Right");
buttonGroupLeftRight.add(rdbtnRight);
rdbtnRight.setToolTipText(" ");
rdbtnRight.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(rdbtnRight);
Wrap each image in its own JPanel (leftImagePanel and rightImagePanel).
Then you can use:
leftImagePanel.setVisible(true);
rightImagePanel.setVisible(false);
or
leftImagePanel.setVisible(false);
rightImagePanel.setVisible(true);
Wherever you need.

ActionListener - Radio buttons

I'm trying to get a program working where you press the specific radio button that says a color on it, and it makes the entire page that color. The window opens as a square with 4 different color options in it. I just can't for the life of me get the actionPerformed method working. Here is my code. Any help is appreciated.
public class ColorPanel3 extends JPanel implements ActionListener {
Color darkBlue = new Color(5,41,186);
Color lightBlue = new Color(35,253,253);
Color darkRed = new Color(158,19,47);
Color lightRed = new Color(255,105,105);
JRadioButton lightRedButton = new JRadioButton("Light Red");
JRadioButton darkBlueButton = new JRadioButton("Dark Blue");
JRadioButton lightBlueButton = new JRadioButton("Light Blue");
JRadioButton darkRedButton = new JRadioButton("Dark Red");
public ColorPanel3() {
setName("Color Panel");
setLayout(new GridLayout(1, 0, 0, 0));
JPanel panel = new JPanel();
add(panel);
panel.setLayout(null);
panel.setOpaque(true);
lightRedButton.setHorizontalAlignment(SwingConstants.CENTER);
lightRedButton.setBounds(0, 150, 150, 150);
lightRedButton.setBackground(lightRed);
panel.add(lightRedButton);
darkBlueButton.setHorizontalAlignment(SwingConstants.CENTER);
darkBlueButton.setBounds(0, 0, 150, 150);
darkBlueButton.setBackground(darkBlue);
panel.add(darkBlueButton);
lightBlueButton.setHorizontalAlignment(SwingConstants.CENTER);
lightBlueButton.setBounds(150, 0, 150, 150);
lightBlueButton.setBackground(lightBlue);
panel.add(lightBlueButton);
darkRedButton.setHorizontalAlignment(SwingConstants.CENTER);
darkRedButton.setBounds(150, 150, 150, 150);
darkRedButton.setBackground(darkRed);
panel.add(darkRedButton);
ButtonGroup group = new ButtonGroup(); //creates a button group so that only one radio button may be pressed at a time.
group.add(darkBlueButton);
group.add(lightBlueButton);
group.add(darkRedButton);
group.add(lightRedButton);
lightRedButton.addActionListener(actionListener);
darkRedButton.addActionListener(actionListener);
lightBlueButton.addActionListener(actionListener);
darkBlueButton.addActionListener(actionListener);
}
ActionListener actionListener = new ActionListener(){
public void actionPerformed (ActionEvent e){
if(darkBlueButton.isSelected()){
darkBlueButton.setBackground(darkBlue);
lightBlueButton.setBackground(darkBlue);
lightRedButton.setBackground(darkBlue);
darkRedButton.setBackground(darkBlue);
}
if(lightBlueButton.isSelected()){
darkBlueButton.setBackground(lightBlue);
lightBlueButton.setBackground(lightBlue);
lightRedButton.setBackground(lightBlue);
darkRedButton.setBackground(lightBlue);
}
if(darkRedButton.isSelected()){
darkBlueButton.setBackground(darkRed);
lightBlueButton.setBackground(darkRed);
lightRedButton.setBackground(darkRed);
darkRedButton.setBackground(darkRed);
}
if(lightRedButton.isSelected()){
darkBlueButton.setBackground(lightRed);
lightBlueButton.setBackground(lightRed);
lightRedButton.setBackground(lightRed);
darkRedButton.setBackground(lightRed);
}
}
And I made a new class file to put the panel in. This worked.
public class ColorFrame{
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new ColorPanel3());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Color Frame");
}
}
};
}
Final edit: the above code is what I ended up with.
Your action listener should look like this:
ColorPanel3.setOpaque(true);
ColourPanel3.this.setBackground(yourcolor);
And moreover, if you are not writing this code for a code obfuscation contest please use different actionlisteners for all the radio buttons.
Cheers.
Edit: You will have to add the panel to a JFrame
First of all, get rid of these lines:
JRadioButton darkBlueButton = (JRadioButton) e.getSource();
JRadioButton lightBlueButton = (JRadioButton) e.getSource();
JRadioButton darkRedButton = (JRadioButton) e.getSource();
JRadioButton lightRedButton = (JRadioButton) e.getSource();
What is happening is that you are creating four JRadioButton instances with a reference to the JRadioButton given by e.getSource(). If you want the background to change color, then this isn't necessary. I get the feeling that the effect of this isn't what you intended to do, anyway.
When creating your JRadioButton objects with the constructor that takes a String, you're giving it a label (i.e. Dark Blue), along with an action command, which is the same as the text. You can take advantage of this by using the getActionCommand method of the ActionEvent class to determine what color the JPanel should be:
if (e.getActionCommand().equals("Dark Blue")) {
ColorPanel3.this.setBackground(darkBlue);
}
But in order for any color change to be apparent, you must set the transparency of the top panel:
panel.setOpaque(false);

add the gui components dynamically?

I'm working on a program and I want to create an app in which I can repeat the gui components using the for loop. I've done this using card layout and it works fine but when I use container and JPanel without card layout the gui components overlap on the previous components. Please give me a hint or advise where my code is wrong. Thanks for your advise and time in advance.
Here's the code of my app:
class form extends JFrame implements ActionListener {
JTextArea text;
static int openFrameCount = 0;
public form(){
super("Insert Form");
Container panel=getContentPane();
JPanel cc = new JPanel();
cc.setLayout(null);
for(int i=1;i<=2;i++){
JLabel label1=new JLabel(" Question"+(++openFrameCount));
label1.setBounds(15, 40, 185, 50);
cc.add(label1);
text=new JTextArea();
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(750,50));
text.setBounds(80, 60,750,50);
cc.add(text);
JLabel symbol=new JLabel("Selection for Option?");
symbol.setBounds(100, 120,850,60);
cc.add(symbol);
ButtonGroup group = new ButtonGroup();
JRadioButton rbut=new JRadioButton("Radio Button for option");
rbut.setBounds(300, 120,300,60);
JCheckBox cbox=new JCheckBox("Check Box for option");
cc.add(rbut);
cbox.setBounds(650, 120,350,60);
cc.add(cbox);
group.add(rbut);
group.add(cbox);
cc.revalidate();
validate();
panel.add(cc);
}
}
You have set the layout of the cc panel to null, which is not a good idea. Then, using the setBounds(x, y, width, height) you set the location and size of the components that you add and they of course overlap.
Try to use any layout manager that fits your needs, but don't set it to null unless you really have a very strong reason to do that.

Increasing/Decreasing Font Size inside textArea using JButton

I'm creating a sticky note application using Java.
What I want to do:
I want to increase the size of the texts inside textArea each time I click on the increase size.
I will know how to do the opposite obviously.
Short Code:
JButton incButton = new JButton("+");
fontFrame.add(incButton);
incButton.addActionListener(new fontIncAction());
JButton DecButton = new JButton("-");
fontFrame.add(DecButton);
//textArea.setFont( Font("Serif", Font.PLAIN, fz));
}
}
private class fontIncAction implements ActionListener{
public void actionPerformed(ActionEvent e){
textArea.setFont(new Font("Serif",Font.PLAIN,20));
}
}
To make the code more general you can do something like the following in your ActionListener:
Font font = textArea.getFont();
float size = font.getSize() + 1.0f;
textArea.setFont( font.deriveFont(size) );

Categories