JRadio Buttons and images - java

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.

Related

color of JButton

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

How do I transfer a Java console program into a window application? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've been looking but have not been able to find something in simple enough terms for me to understand. I currently have a program running on a java console, and I make options available through text. I now want to make this into a window program that uses buttons instead of a text option.
I found info on how to create a JFrame, but I am having issues finding info on how to make a button that calls a method, and have text that changes to show updates.
Any links or info would be much appreciated, I dont know where to go and any nudge is a help!
You can put something like the following code into your "public static void main(String[] args)" method.
JFrame frmMain = new JFrame(); // Create our JFrame
// Set the layout for main frame. This controls how things get arranged on the screen
frmMain.setLayout(new BorderLayout());
// panels are what you put everything else on
JPanel panel1 = new JPanel(new FlowLayout()); // another layout
JPanel panel2 = new JPanel();
BoxLayout box = new BoxLayout(panel2, BoxLayout.PAGE_AXIS); // another layout
panel2.setLayout(box);
// here are a couple of buttons
JButton btnAdd = new JButton("Add");
JButton btnRemove = new JButton("Remove");
// here are a couple of textboxes. They accept typed in information
JTextField txtFirstName = new JTextField();
JTextField txtMiddleInitial = new JTextField();
JTextField txtLastName = new JTextField();
// add our buttons to panel1. It has a FlowLayout, so they will be centered left to right as we add them
panel1.add(btnAdd);
panel1.add(btnRemove);
// Create a panel to hold First Name
JPanel pnlFirstName = new JPanel(new BorderLayout()); // also set its layout
// here we add a JLabel.class they just display text, they don't allow input
pnlFirstName.add(new JLabel("first name"), BorderLayout.WEST);
// here we put our text box onto the First name panel
pnlFirstName.add(txtFirstName, BorderLayout.CENTER);
// repeat for middle initial panel
JPanel pnlMiddleInitial = new JPanel(new BorderLayout());
pnlMiddleInitial.add(new JLabel("M.I."), BorderLayout.WEST);
pnlMiddleInitial.add(txtMiddleInitial, BorderLayout.CENTER);
// repeat for last name panel
JPanel pnlLastName = new JPanel(new BorderLayout());
pnlLastName.add(new JLabel("last name"), BorderLayout.WEST);
pnlLastName.add(txtLastName, BorderLayout.CENTER);
// put a 3 pixel border arounnd panel 2 to keep things away from the edge
panel2.setBorder(new EmptyBorder(3, 3, 3, 3));
// add all of our input panels to panel 2, according to BoxLayout (up above)
panel2.add(pnlFirstName);
panel2.add(pnlMiddleInitial);
panel2.add(pnlLastName);
// add panel1 and panel2 to the Frame. You have to add to the .getContentPane(), or you might mess things up.
frmMain.getContentPane().add(panel1, BorderLayout.NORTH);
frmMain.getContentPane().add(panel2, BorderLayout.CENTER);
// This is how we tell the program what to do when the user presses the "Add" button.
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtFirstName.setText("My First Name");
}
});
// This is how we tell the program what to do when the user presses the "Remove" button.
btnRemove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtFirstName.setText("");
}
});
// pack just makes everything take up it's proper space on the screen in as tight of a package as possible
frmMain.pack();
// if you don't set visible to true, you won't see your Frame
frmMain.setVisible(true);
// what to do when the user clicks the "X" to close or used "Close" from the context menu
frmMain.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Go to bellow link here is the full example how to use button in java using Frame.
Here you got all the details about the Example.
http://www.javatpoint.com/java-jbutton
write your code in actionPerformed() method which you want to do on button click.
going to file menu and export your project in runnable JAR file
than you have a jar file to start in windows

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

Image button created from JLabel is not working

I'm trying to make a buttom from an image on the JFrame using the ImageIcon and the addMouseListener that will replace the current image with another image by clicking it.
static JPanel jp = new JPanel();
final JLabel jl = new JLabel();
final JFrame jf = new JFrame();
ImageIcon image = new ImageIcon("image1.jpg");
jl.setIcon(image);
jp.add(jl);
jf.add(jp);
jf.validate();
JLabel button = new JLabel(image);
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
jl.setIcon( null );
ImageIcon image = new ImageIcon("image2.jpg");
jl.setIcon(image);
}
});
The GUI is displayed with image1.jpg, but the button does not work at all and I can't even test whether the replacement from image1 to image2 works. GUI will not do anything even if I attempt to click the image1.jpg displayed on the window.
Edit: Adjusted JLabel varaible to be final for now. Other similar questions intimate that this method should be working but I can't figure out what is wrong with the code.
Not really sure ActionListener works with JLabel either.
No you can't add an ActionListener to a JLabel. An easier approach is to make a JButton look like a JLabel, then you can add the ActionListener to the button:
JButton button = new JButton(...);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.addActionListener(...);
but the button does not work at all
A mouse click is generated when a mousePressed and mouseReleased is received for the same mouse point. So if you move the mouse slightly the event will not get generated. Instead listen for the mousePressed() event.

How to display different JPanels in the same region of the panel with clicking a button

I want a different JPanel to be displayed when I press a button. The other two JPanels that are displayed in the panel are not to be moved. I've tried, but when pressing the button, nothing happens. When pressing the button even times, many textfields must be displayed, else a simple scrollpane. Here is the code:
final JPanel choseTypeOfAnswer = new JPanel();
choseTypeOfAnswer.add(radioBox);
radioBox.setToolTipText("Answer in form of radiobox");
radioBox.setIcon(GUI.createImageIcon("check.png"));
radioBox.setAlignmentX(Component.LEFT_ALIGNMENT);
radioBox.setPreferredSize(new Dimension(30, 20));
radioBox.setVisible(true);
radioBox.addActionListener(new ActionListener(){
private int clicked;
public void actionPerformed(ActionEvent e){
clicked++;
//reset contents of the image preview field
if((clicked % 2) == 0){
add(new JLabel("<html><b>Answer:</b>"));
JTextField textField = new JTextField(20);
JTextField textField1 = new JTextField(20);
JTextField textField2 = new JTextField(20);
JTextField textField3 = new JTextField(20);
choseTypeOfAnswer.add(textField);
choseTypeOfAnswer.add(textField1);
choseTypeOfAnswer.add(textField2);
choseTypeOfAnswer.add(textField3);
add(BorderLayout.NORTH,choseTypeOfAnswer);
}else{
add(new JLabel("<html><b>Answer:</b>"));
//now a scroll pane for the answer area
JScrollPane answerScroller = new JScrollPane(answerArea);
answerScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
answerScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
choseTypeOfAnswer.add(answerScroller);
//add(answerScroller);
add(choseTypeOfAnswer);
}
}
});//den emfanizei tpt me to patima tou koympiou
add(choseTypeOfAnswer);
//holds the bottom two components: "important" checkbox, "create card" button
JPanel bottomContainer = new JPanel();
//bottomContainer.setLayout(new BoxLayout(bottomContainer,BoxLayout.PAGE_AXIS));
//important.setAlignmentX(Component.CENTER_ALIGNMENT);
//bottomContainer.add(important);
createCard.setText("Finish and add card");
createCard.setIcon(GUI.createImageIcon("check.png"));
createCard.setAlignmentX(Component.CENTER_ALIGNMENT);
createCard.setAlignmentY(Component.BOTTOM_ALIGNMENT);
createCard.setPreferredSize(new Dimension(180, 45));
createCard.addActionListener(new cardListener());
bottomContainer.add(createCard);
//now add the bottom container
add(bottomContainer, BorderLayout.SOUTH);
Use Component#setVisible(...) making one panel visible, and hide the other.

Categories