JRadioButton Question
Hi,
I have the following code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShowCardLayout extends JApplet implements ActionListener
private CardLayout cardLayout = new CardLayout(20, 10);
private JPanel cardPanel = new JPanel(cardLayout);
JButton previous, next;
public ShowCardLayout()
cardPanel.setBorder(new javax.swing.border.LineBorder(Color.black));
for(int i = 1; i <= 8; i++)
JPanel subPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Question #" + i);
JPanel buttonPanel = new JPanel();
JRadioButton button1 = new JRadioButton("Excellent");
JRadioButton button2 = new JRadioButton("Good");
JRadioButton button3 = new JRadioButton("Fair");
JRadioButton button4 = new JRadioButton("Poor");
ButtonGroup answers = new ButtonGroup();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS ));
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(button4);
subPanel.add(label, BorderLayout.NORTH);
subPanel.add(buttonPanel, BorderLayout.WEST);
cardPanel.add(subPanel, String.valueOf(i));
JPanel p = new JPanel();
p.add(previous = new JButton("Previous"));
p.add(next = new JButton("Next"));
getContentPane().add(cardPanel, BorderLayout.CENTER);
getContentPane().add(p, BorderLayout.SOUTH);
previous.addActionListener(this);
next.addActionListener(this);
public void actionPerformed(ActionEvent e)
String actionCommand = e.getActionCommand();
if(e.getSource() instanceof JButton)
if("Previous".equals(actionCommand))
cardLayout.previous(cardPanel);
else if("Next".equals(actionCommand))
cardLayout.next(cardPanel);
public static void main(String[] args)
ShowCardLayout applet = new ShowCardLayout();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(3);
frame.setTitle("ShowCardLayout");
frame.getContentPane().add(applet, BorderLayout.CENTER);
applet.init();
applet.start();
frame.setSize(570, 220);
frame.setVisible(true);
}How can I capture button selection from each question?
a simple demo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Testing extends JFrame
final int MAX_PANELS = 5;
CardLayout cl = new CardLayout();
JPanel clPanel = new JPanel(cl);
int currentPanel = 0;
public Testing()
setSize(300,200);
setLocation(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
for(int x = 0; x < MAX_PANELS; x++)
JPanel p = new JPanel();
p.add(new JLabel("Panel "+ x));
clPanel.add(""+x,p);
final JButton btnPrev = new JButton("Previous");
final JButton btnNext = new JButton("Next");
JPanel p = new JPanel(new GridLayout(1,2,25,0));
p.add(btnPrev);
p.add(btnNext);
JPanel p1 = new JPanel();
p1.add(p);
getContentPane().add(clPanel,BorderLayout.CENTER);
getContentPane().add(p1,BorderLayout.SOUTH);
btnPrev.setEnabled(false);
btnPrev.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
cl.previous(clPanel);
currentPanel--;
btnNext.setEnabled(true);
if(currentPanel == 0) btnPrev.setEnabled(false);}});
btnNext.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
cl.next(clPanel);
currentPanel++;
btnPrev.setEnabled(true);
if(currentPanel == MAX_PANELS-1) btnNext.setEnabled(false);}});
public static void main(String[] args){new Testing().setVisible(true);}
}
Similar Messages
-
3 questions on visual changes and positioning
Hello everyone,
I hope I have the right section for my questions. (so many categories) I have three questions that I hope I can get answered.
Question 1 ) I am writing an application that uses a JDesktopPane. I have a menu that each choice opens up a JInternalFrame. One of my internal frames contains option settings for the app. One of the option selections is the type of look and feel of the gui. I have three JRadioButtons that chooses the three built in types. When I use the method (see below) to change the gui look, it only effects the Internal Frame, not the rest of the app. Is there a way I can get it to change the rest of the frames and the main JDesktop.
private UIManager.LookAndFeelInfo looks[];
public void lookAndFeel()
looks = UIManager.getInstalledLookAndFeels();
try
UIManager.setLookAndFeel(looks[lookChoice].getClassName());
SwingUtilities.updateComponentTreeUI(this);
catch(Exception exception)
try
UIManager.setLookAndFeel(looks[0].getClassName());
catch(Exception guiException)
// Nothing yet...
}Question 2 ) Positioning --- I understand how to use layout managers, but is there a way I can override the positioning of objects? Sometimes, I want to postion objects to a point. Instead of automatic positioning.
Question 3 ) Adjusting properties --- I notice that when I create a different font and if I want an object to use that font then I need to setFont() for the object. Unfortunately, I have noticed that this needs to be done for every object. Is there a way to set the font for all the objects in a JPanel or JFrame at once?
Thanks everyone, (sorry for the numerous questions, just has been building for awhile)
7Question 1 ) I am writing an application that uses a
JDesktopPane. I have a menu that each choice opens up
a JInternalFrame. One of my internal frames contains
option settings for the app. One of the option
selections is the type of look and feel of the gui. I
have three JRadioButtons that chooses the three built
in types. When I use the method (see below) to change
the gui look, it only effects the Internal Frame, not
the rest of the app. Is there a way I can get it to
change the rest of the frames and the main JDesktop.Try doing
revalidate();
repaint()
on all of them
Question 2 ) Positioning --- I understand how to use
layout managers, but is there a way I can override the
positioning of objects? Sometimes, I want to postion
objects to a point. Instead of automatic positioning.Your choice is either to call setLayout(null) and set component positions yourself or to create/extend your own layout manager
>
Question 3 ) Adjusting properties --- I notice that
when I create a different font and if I want an object
to use that font then I need to setFont() for the
object. Unfortunately, I have noticed that this needs
to be done for every object. Is there a way to set the
font for all the objects in a JPanel or JFrame at
once?Not that I can think of. Why not just create one method where you can set everybody's font with a font parameter?
>
Thanks everyone, (sorry for the numerous questions,
just has been building for awhile)
7 -
Classes intercommunication question
hello folks,
another newbie question:
I have a JDialog with 3 components:
pane with 2 JRadioButton's
JButton,
and JScrollPane with a JList in it
elements of a Jlist are of my own class A and I am rewriting its toString() method, so elements of my class are correctly displayed in JList.
Now here comes the question:
this toString() method must depend on what JRadioButton is selected in a JDialog.
how do I do it? should I send the JDialog reference to my Class constructor?
thanksThat's a pretty confusing question without any code to look at. My first reaction is to say to pass some argument (something unique about the JRadioButton that's selected) to your toString() method so it can choose what to return.
-
JRadioButton.setSelected(false) doesn't work?
Hey there. I usually answer questions in this forum but this time I have a question myself. I'm trying to de-select JRadioButtons in a ButtonGroup but it's not working. I've searched the forum but didn't find anything. Here's the very simple code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonTest extends JFrame {
JRadioButton rb1 = new JRadioButton("button1", true);
JRadioButton rb2 = new JRadioButton("button2");
ButtonGroup bgroup = new ButtonGroup();
JButton b = new JButton("clear");
ButtonTest() {
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearbuttons();
bgroup.add(rb1);
bgroup.add(rb2);
Container c = getContentPane();
c.setLayout(new GridLayout(2,2));
c.add(rb1);
c.add(rb2);
c.add(b);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
void clearbuttons() {
Component [] components = getContentPane().getComponents();
for (int i = 0; i < components.length; i++) {
Component c = components[ i ];
System.out.println(c);
if (c instanceof JRadioButton) {
JRadioButton rb = (JRadioButton) c;
rb.setSelected(false); // once.
bgroup.setSelected(rb.getModel(), false); // twice.
System.out.println("\ncalled setSelected\n");
public static void main (String[]a) {
ButtonTest b = new ButtonTest();
b.setSize(200,100);
b.setVisible(true);
}Anybody know why the selected button remains selected?The ButtonGroup ensures that one JRadioButton is always selected, at least after the first one is initially selected. The workaround to fix this is to add an additional "dummy" JRadioButton to the ButtonGroup, and have your code select it when you want to deselect the rest of the buttons. The dummy JRadioButton doesn't need to be added to the GUI or displayed, or anything.
-
Help needed with Jradiobuttons
Hi i am new to awt programming.
I have created a Frame in AWT and Frame consists fo some checkboxes and some buttons so that when i press some button it performs necessary calculations. Now i want to add some radiobuttons in my frame. Well we can create radiobutons in awt by creating a buttongroup and addind some checkboxes in that group. But my question is can I create JRadiobuttons in myframe.
Since i have created Frame using AWT will the code work if i add some JRadioButtons in my Frame as JRadioButtons belongs to Swings.
Thankyou
Any king of help is appreciated.First of all you should read this article about why it's generally not wise to mix Swing and AWT:
http://java.sun.com/products/jfc/tsc/articles/mixing/
Since i have created Frame using AWT will the code
work if i add some JRadioButtons in my Frame as
JRadioButtons belongs to Swings.
I guess that depends on what you want to do. Try it, and see what happens. -
hi everyone...i have a panel that have a flow layout and a scroll pane attached to it and i also have a button that when pressed, a component is added to the panel...my problem is that when i press the button, the components are added fine but when there is no more place on the line, the components are not placed on the second line even though i have a scroll pane and a flow layout....
please help
here are the three classes needed to show the problem
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class GUI extends JFrame implements ActionListener {
public GUI() {
initializeGUI();
public void initializeGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(true);
setTitle("DVD");
setSize(1000, 700);
setLocation(20, 20);
JTabbedPane tp = new JTabbedPane(JTabbedPane.LEFT);
getContentPane().add(tp);
tp.addTab("Rent Page", new MultipleRentGUI());
public static void main(String[] args) {
new GUI().setVisible(true);
* Invoked when an action occurs.
public void actionPerformed(ActionEvent e) {
ActionListener BackupListener = new ActionListener() {
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MultipleRentGUI extends JPanel implements ActionListener, GUIConstants {
private JRadioButton id = new JRadioButton("Customer ID", true);
private JRadioButton name = new JRadioButton("Customer name");
private JLabel label = new JLabel("Customer ID: ");
private JTextField cust = new JTextField(10);
private JButton rent = new JButton("Rent");
private JButton reset = new JButton("Reset");
private JButton add = new JButton("Add");
private JButton remove = new JButton("Remove");
private JPanel bPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JPanel lPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JPanel b2Panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JPanel tPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JPanel b3Panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JPanel nPanel = new JPanel();
private ArrayList<MultipleTitleRentGUI> titles = new ArrayList<MultipleTitleRentGUI>();
private int count = 0;
private Calendar c = Calendar.getInstance();
private final int FONT_SIZE = 15;
private Font f = new Font("Times New Roman", Font.BOLD, FONT_SIZE);
private Font borderFont = new Font("Times New Roman", Font.BOLD, FONT_SIZE + 5);
public MultipleRentGUI() {
setupComponents();
setupFonts();
setupButtons();
initializeGUI();
public void setupFonts() {
id.setFont(f);
name.setFont(f);
rent.setFont(f);
reset.setFont(f);
cust.setFont(f);
public void setupComponents() {
Border b = BorderFactory.createLoweredBevelBorder();
this.setBorder(BorderFactory.createTitledBorder(b
, "Multiple Rent Page"
, TitledBorder.DEFAULT_JUSTIFICATION
, TitledBorder.DEFAULT_POSITION
, borderFont
, Color.blue));
cust.setBorder(BorderFactory.createLoweredBevelBorder());
nPanel.setLayout(new BoxLayout(nPanel, BoxLayout.Y_AXIS));
public void initializeGUI() {
rent.setEnabled(true);
reset.setEnabled(false);
ButtonGroup bg = new ButtonGroup();
bg.add(id);
bg.add(name);
setLayout(new BorderLayout());
add(nPanel, BorderLayout.NORTH);
bPanel.add(id);
bPanel.add(name);
nPanel.add(bPanel);
lPanel.add(label);
lPanel.add(cust);
nPanel.add(lPanel);
b2Panel.add(add);
b2Panel.add(remove);
nPanel.add(b2Panel);
JScrollPane sp = new JScrollPane(tPanel
, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(sp, BorderLayout.CENTER);
b3Panel.add(rent);
b3Panel.add(reset);
add(b3Panel, BorderLayout.SOUTH);
public void setupButtons() {
rent.addActionListener(this);
rent.setActionCommand("rent");
reset.addActionListener(this);
reset.setActionCommand("reset");
id.addActionListener(this);
id.setActionCommand("id");
name.addActionListener(this);
name.setActionCommand("name");
add.addActionListener(this);
add.setActionCommand("add");
remove.addActionListener(this);
remove.setActionCommand("remove");
public void resetFields() {
rent.setEnabled(true);
reset.setEnabled(false);
id.setSelected(true);
cust.setText("");
label.setText("Customer ID: ");
public Box addComponent(Component c1, Component c2, int spacing) {
return null;
* Invoked when an action occurs.
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("id")) {
label.setText("Customer ID: ");
if (e.getActionCommand().equalsIgnoreCase("name")) {
label.setText("Customer Name: ");
if (e.getActionCommand().equalsIgnoreCase("reset")) {
resetFields();
if (e.getActionCommand().equalsIgnoreCase("add")) {
titles.add(new MultipleTitleRentGUI());
tPanel.add(titles.get(count));
count++;
revalidate();
if (e.getActionCommand().equalsIgnoreCase("remove")) {
if (count == 0) {
return;
} else {
tPanel.remove(titles.get(count - 1));
titles.remove(count - 1);
count--;
tPanel.revalidate();
tPanel.repaint();
if (e.getActionCommand().equalsIgnoreCase("rent")) {
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class MultipleTitleRentGUI extends JPanel implements ActionListener {
private JLabel title = new JLabel("Title Barcode: ");
private JTextField barcode = new JTextField(5);
private JRadioButton reg = new JRadioButton("Regular price", true);
private JRadioButton half = new JRadioButton("Half price");
private JRadioButton free = new JRadioButton("Free of Charge");
private int fee = getRentFee();
private JPanel text = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JPanel buttons = new JPanel();
private final int FONT_SIZE = 15;
private Font f = new Font("Times New Roman", Font.BOLD, FONT_SIZE);
private Font borderFont = new Font("Times New Roman", Font.BOLD, FONT_SIZE + 5);
public MultipleTitleRentGUI() {
setupButtons();
setupComponents();
initializeGUI();
private void initializeGUI() {
setLayout(new BorderLayout());
setSize(50, 60);
ButtonGroup bg = new ButtonGroup();
bg.add(reg);
bg.add(half);
bg.add(free);
text.add(title);
text.add(barcode);
add(text, BorderLayout.NORTH);
buttons.add(reg);
buttons.add(half);
buttons.add(free);
add(buttons, BorderLayout.CENTER);
private void setupButtons() {
reg.setFont(f);
half.setFont(f);
free.setFont(f);
reg.addActionListener(this);
reg.setActionCommand("regular");
half.addActionListener(this);
half.setActionCommand("half");
free.addActionListener(this);
free.setActionCommand("free");
private void setupComponents() {
Border b = BorderFactory.createLoweredBevelBorder();
this.setBorder(BorderFactory.createTitledBorder(b
, "Title"
, TitledBorder.DEFAULT_JUSTIFICATION
, TitledBorder.DEFAULT_POSITION
, borderFont
, Color.blue));
barcode.setBorder(BorderFactory.createLoweredBevelBorder());
buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS));
public String getBarcode() {
return barcode.getText();
public int getFee() {
return fee;
private int getRentFee() {
int cost = 0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/dvd", "root", "swordfrogy");
String sql = "SELECT rent " +
"FROM fees";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
cost = rs.getInt("rent");
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return cost;
* Invoked when an action occurs.
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("regular")) {
fee = getRentFee();
if (e.getActionCommand().equalsIgnoreCase("half")) {
fee = getRentFee() / 2;
if (e.getActionCommand().equalsIgnoreCase("free")) {
fee = 0;
}Sorry, I've just read the question more carefully :)
FlowLayout will add the component on a second line if it runs out of space on the first. That's not the cause of the problem.
However, this container is in a scroll pane. That means it will never run out of space. The layout manager is still adding components to the first line - it's just that they can't be seen because you've suppressed the horizontal scroll bar.
Note that suppressing the scroll bar does just that: it doesn't restrict the size of the component in the viewport.
If you want to check that that's what happening, add a println() after your revalidate() call to dump the preferred size of the container - you should see it growing horizontally.
In order to make the components flow as you intend, the solution I use is an extension of JViewport which uses its own custom layout manaer.
There may be an easier solution but I didn't find one before I wrote that and I've stuck with it ever since. -
Multiple JRadioButtons in a JTable cell
I have this code that works, but I want to make it so only a single click is require to change the radio buttons in the cell. Right now it takes a double click.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
* @version 1.2 08/13/99
public class JRadioButtonTableExample2 extends JFrame {
public JRadioButtonTableExample2(){
super( "JRadioButtonTable Example" );
String[] columnHeader = {"Questions","Answer"};
Object[][] o = new Object[50][2];
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(o,columnHeader);
JTable table = new JTable(dm);
String[] answer = {"A","B","C"};
table.getColumn("Answer").setCellRenderer(
new RadioButtonRenderer(answer)
table.getColumn("Answer").setCellEditor(
new RadioButtonEditor(new JCheckBox(),
new RadioButtonPanel(answer))
JScrollPane scroll = new JScrollPane(table);
getContentPane().add( scroll );
// Cell base
class RadioButtonPanel extends JPanel {
JRadioButton[] buttons;
RadioButtonPanel(String[] str) {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
buttons = new JRadioButton[str.length];
for (int i=0; i<buttons.length; i++) {
buttons[i] = new JRadioButton(str);
buttons[i].setFocusPainted(false);
add(buttons[i]);
public void setSelectedIndex(int index) {
for (int i=0;i<buttons.length;i++) {
buttons[i].setSelected(i == index);
public int getSelectedIndex() {
for (int i=0; i<buttons.length; i++) {
if (buttons[i].isSelected()) {
return i;
return -1;
public JRadioButton[] getButtons() {
return buttons;
class RadioButtonRenderer extends RadioButtonPanel
implements TableCellRenderer {
RadioButtonRenderer(String[] strs) {
super(strs);
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Integer) {
setSelectedIndex(((Integer)value).intValue());
return this;
class RadioButtonEditor extends DefaultCellEditor
implements ItemListener {
RadioButtonPanel panel;
public RadioButtonEditor(JCheckBox checkBox,RadioButtonPanel panel) {
super(checkBox);
this.panel = panel;
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton[] buttons = panel.getButtons();
for (int i=0; i<buttons.length; i++) {
buttonGroup.add(buttons[i]);
buttons[i].addItemListener(this);
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (value instanceof Integer) {
panel.setSelectedIndex(((Integer)value).intValue());
return panel;
public Object getCellEditorValue() {
return new Integer(panel.getSelectedIndex());
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
public static void main(String[] args) {
JRadioButtonTableExample2 frame = new JRadioButtonTableExample2();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.setSize( 230, 140 );
frame.setVisible(true);It looks to me like the problem is that the renderer is interfering with the editor. When the editor is invoked, something in jtable is rerendering the other items. This is causing a flood of change events to be fired. I'm not sure how you would fix this. The first thing that occurred to me was to make a separate set of buttons for the renderer vs the editor. I don't have time to try it right now.
-
Figuring out which JRadioButton is selected
Hey guys. I have a simple program that calculates tempurature in Fahrenheit, Celcius and Kelven.
There are 6 Radiobuttons in a ButtonGroup. I need to know how to get which radiobutton is selected.
Here is my code....I already have an action listener for the buttons that runs the code to do the calculations and display the answer, I just need to know how to figure out which radiobuton is selected.
Thanks!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class DegreeConverter extends JFrame{
JLabel lblFah, lblConversion,lblShowConversion;
JTextField getFah;
JButton btnConvert;
JRadioButton btnFahToCel, btnFahToKel,
btnCelToFah,btnCelToKel,
btnKelToFah, btnKelToCel;
ButtonGroup radioGroup;
public DegreeConverter(){
super("Degree Converter");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame.setDefaultLookAndFeelDecorated(true);
Container container1 = getContentPane();
SpringLayout layout = new SpringLayout();
container1.setLayout(layout);
lblFah = new JLabel("Enter Temperature:");
container1.add(lblFah);
getFah = new JTextField(5);
container1.add(getFah);
lblConversion = new JLabel("Conversion Answer:");
container1.add(lblConversion);
lblShowConversion = new JLabel("...");
container1.add(lblShowConversion);
btnConvert = new JButton("Convert");
btnConvert.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
String strFah = getFah.getText();
double dblFah = Double.parseDouble(strFah);
lblShowConversion.setText(Double.toString(convertDegrees(dblFah)));
container1.add(btnConvert);
btnFahToCel = new JRadioButton("Fahrenheit To Celcius", true);
container1.add(btnFahToCel);
btnFahToKel = new JRadioButton("Fahrenheit To Kelvin", true);
container1.add(btnFahToKel);
btnCelToFah = new JRadioButton("Celcius To Fahrenheit", true);
container1.add(btnCelToFah);
btnCelToKel = new JRadioButton("Celcius To Kelvin", true);
container1.add(btnCelToKel);
btnKelToFah = new JRadioButton("Kelvin To Fahrenheit", true);
container1.add(btnKelToFah);
btnKelToCel = new JRadioButton("Kelvin To Celcius", true);
container1.add(btnKelToCel);
radioGroup = new ButtonGroup();
radioGroup.add(btnFahToCel);
radioGroup.add(btnFahToKel);
radioGroup.add(btnCelToFah);
radioGroup.add(btnCelToKel);
radioGroup.add(btnKelToFah);
radioGroup.add(btnKelToCel);
//layout for btnFahToCel
layout.putConstraint(SpringLayout.WEST, btnFahToCel,
5,
SpringLayout.WEST, container1);
layout.putConstraint(SpringLayout.NORTH, btnFahToCel,
5,
SpringLayout.NORTH, container1);
//layout for btnFahToKel
layout.putConstraint(SpringLayout.WEST, btnFahToKel,
5,
SpringLayout.WEST, container1);
layout.putConstraint(SpringLayout.NORTH, btnFahToKel,
5,
SpringLayout.SOUTH, btnFahToCel);
//layout for btnCelToFah
layout.putConstraint(SpringLayout.WEST, btnCelToFah,
5,
SpringLayout.WEST, container1);
layout.putConstraint(SpringLayout.NORTH, btnCelToFah,
5,
SpringLayout.SOUTH, btnFahToKel);
//layout for btnCelToKel
layout.putConstraint(SpringLayout.WEST, btnCelToKel,
5,
SpringLayout.WEST, container1);
layout.putConstraint(SpringLayout.NORTH, btnCelToKel,
5,
SpringLayout.SOUTH, btnCelToFah);
//layout for btnKelToFah
layout.putConstraint(SpringLayout.WEST, btnKelToFah,
5,
SpringLayout.WEST, container1);
layout.putConstraint(SpringLayout.NORTH, btnKelToFah,
5,
SpringLayout.SOUTH, btnCelToKel);
//layout for btnKelToCel
layout.putConstraint(SpringLayout.WEST, btnKelToCel,
5,
SpringLayout.WEST, container1);
layout.putConstraint(SpringLayout.NORTH, btnKelToCel,
5,
SpringLayout.SOUTH, btnKelToFah);
//layout for lblFah
layout.putConstraint(SpringLayout.WEST, lblFah,
15,
SpringLayout.EAST, btnFahToCel);
layout.putConstraint(SpringLayout.NORTH, lblFah,
5,
SpringLayout.NORTH, container1);
//layout for getFah
layout.putConstraint(SpringLayout.WEST, getFah,
5,
SpringLayout.EAST, lblFah);
layout.putConstraint(SpringLayout.NORTH, getFah,
5,
SpringLayout.NORTH, container1);
//layout for lblConversion
layout.putConstraint(SpringLayout.WEST, lblConversion,
22,
SpringLayout.EAST, btnFahToKel);
layout.putConstraint(SpringLayout.NORTH, lblConversion,
5,
SpringLayout.SOUTH, lblFah);
//layout for lblShowConversion
layout.putConstraint(SpringLayout.WEST, lblShowConversion,
5,
SpringLayout.EAST, lblConversion);
layout.putConstraint(SpringLayout.NORTH, lblShowConversion,
5,
SpringLayout.SOUTH, lblFah);
//layout for btnConvert
layout.putConstraint(SpringLayout.WEST, btnConvert,
15,
SpringLayout.EAST, btnFahToCel);
layout.putConstraint(SpringLayout.NORTH, btnConvert,
5,
SpringLayout.SOUTH, lblConversion);
//layout for container
layout.putConstraint(SpringLayout.EAST, container1,
50,
SpringLayout.EAST, getFah);
layout.putConstraint(SpringLayout.SOUTH, container1,
5,
SpringLayout.SOUTH, btnKelToCel);
pack();
setVisible(true);
}// end constructor
public static void main(String args[]){
DegreeConverter application = new DegreeConverter();
public double convertDegrees( double fah){
//currently there is only one calculation here.. I need to figure out
//how to get which radiobutton is selected so i can do a select case
//or if/else here to do the appropriate calculations.
DecimalFormat twoDigits = new DecimalFormat("00");
String celcius;
double returnCelcius;
celcius = twoDigits.format(5.0/9.0 * (fah - 32));
returnCelcius = Double.parseDouble(celcius);
return returnCelcius;
}//end convertDegrees
}//end classSwing related questions should be posted in the Swing forum.
1) Test each button
If (button1.isSelected() )
else if (button2.isSelected() )
.... -
Im wanting to increase the size of the radio buttons in my application. Hows this done?
Thanks
MartinmyRadioButton.setPreferredSize(new java.awt.Dimension(640, 480));//?But I suspect that the actual question is How do I increase the size of the RadioButton's Image. No magic method to do this... you will have to sub JRadioButton and override its paintComponent(Graphics g) method....
-
Implement a Listener on JRadioButtons
Hi! I'm new here so be gentle I have a group of 4 JRadioButtons and also a JButton. I have added ItemListeners to the radio buttons and ActionListener to the JButton. How can I know which is the last radio button selected before I click the JButton. I hope you understand my question and any help would be appreciated.
Have you added your radio buttons to a ButtonGroup. If not add them use getElements() from the button group to get an Enumeration of all the buttons and find the selected button from the Enumeration.
ICE -
HI gurus
i have some problem with my application
1. the resultSet method previous() throws an exception
this is the code snippet
if(obj ==prev)
try
result.previous();
catch(Exception e)
where result is the object of the ResultSet interface
how can i solve this problem so that my button can allow me to move to the next record in my database
2.How can i populate my radiobutton with information from my database
becos this code snippet throws an exception
JRadioButton radio;
radio = new JRadioButton(result.getString(1));
pls help becos this is urgenthi, Greatone
i did what you told me to do but still here is the full code:
import java.awt.*;
import javax.swing.*;
import java.util.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;import java.net.URL;
import java.io.IOException;
import java.sql.*;
public class TestEngine extends Thread implements ActionListener
{ static JFrame frame;
JPanel panel;
JPanel paneln;
JPanel panelc;
JPanel panels;
URL helpURL;
JPanel panelHolder,quepanelnorth2,quepanelsouth2;
JEditorPane editorPane;
int cont=0;
JButton next,mark,exhibit;
JLabel logolabel;
JLabel invlabel;
JButton prev;
JLabel question;
BorderLayout bl;
//Thread & time
static Thread timerThread;
static int hrs=1;
static int minCD = 59;
static int secCD = 59;
JLabel timeer;
String s = null;
static ResultSet result;
static String ans2;
static String ans3 ;
static String ans4 ;
static String ans5;
//++++++++++++++ MAIN METHOD +++++++++
public static void main(String cc[])
{ SplashWindowFrame splash =new SplashWindowFrame();
/**name = JOptionPane.showInputDialog("Enter You Name");
if ((name==null) || name.equals(""))
name = "Mr. X";
System.out.println(name);
frame =new JFrame(":::: TestEngine :::::");
TestEngine eng = new TestEngine ();
frame.setIconImage(new ImageIcon("ico_test5.gif").getImage());
frame.setVisible(true);
frame.setResizable(false);
frame.pack();
//setting the connection
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect = DriverManager.getConnection("jdbc:odbc:quest","null","");
Statement state = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
result=state.executeQuery("Select question,ans1,ans2,ans3,ans4 from question");
result.next();
ans2=result.getString(2);
ans3 = result.getString(3);
ans4=result.getString(4);
ans5 = result.getString(5);
catch(Exception e)
System.out.println("could not execute query" + e);
eng.showRecord(result);
public void run()
while(timerThread != null)
calctime();
//lblCountDwnSec.setText("sec: " + secCD);
timeer.setText(hrs+" :"+"min: "+minCD+" " + "sec: "+secCD);
try
timerThread.sleep(1000);
catch(InterruptedException e)
public void calctime()
secCD = secCD - 1;
if(secCD == 0 && minCD == 00)
hrs = 0;
secCD = 0;
minCD = 0;
timeer.setText(hrs+" :"+"min: "+ minCD+" " + "sec: "+0);
System.out.println("end!!");
timerThread=null;
if(secCD == 0 && minCD != 0)
secCD =59;
minCD = minCD - 1;
//+++++++++ METHOD TO SHOW RECORDS +++++++++
public void showRecord(ResultSet result)
try
s = "file:"
+ System.getProperty("user.dir")
+ System.getProperty("file.separator")
+ result.getString(1);
URL helpURL = new URL(s);
editorPane.setPage(helpURL);
editorPane.setPage(helpURL);
catch (Exception e)
//System.err.println("Couldn't create help URL: " + s);
JOptionPane.showMessageDialog(frame,"Do you want to Exit the Program","ATTENTION",JOptionPane.INFORMATION_MESSAGE); }
public TestEngine ()
bl=new BorderLayout();
panel=new JPanel();
panel.setPreferredSize(new Dimension(600,400));
frame.setContentPane(panel);
panel.setLayout(bl);
//CRreating Objects of questions class
Question2 question2= new Question2();
//every thing for north panel
paneln=new JPanel();
timeer =new JLabel();
paneln.add(timeer);
//every thing for center panel
panelc=new JPanel();
panelc.add("Abigal",question2);
GridBagConstraints gbc;
GridBagLayout gl;
gbc= new GridBagConstraints();
gl=new GridBagLayout();
quepanelnorth2= new JPanel();
quepanelnorth2.setLayout(gl);
quepanelnorth2.setPreferredSize(new Dimension(300,200));
//south panel for answers
quepanelsouth2 = new JPanel();
//this positions the panels
panelc.setLayout(new BorderLayout());
panelc.add(quepanelnorth2, BorderLayout.NORTH);
panelc.add(quepanelsouth2, BorderLayout.SOUTH);
//database engine
editorPane = new JEditorPane();
//positioning the component
gbc.anchor=GridBagConstraints.CENTER;
gbc.gridx=1;
gbc.gridy=2;
quepanelnorth2.add(editorPane,gbc);
JScrollPane editorScrollPane = new JScrollPane(editorPane);
editorScrollPane.setMinimumSize(new Dimension(10, 10));
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
editorScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
editorScrollPane.setPreferredSize(new Dimension(560,160));
gbc.anchor=GridBagConstraints.CENTER;
gbc.gridx=1;
gbc.gridy=2;
quepanelnorth2.add(editorScrollPane,gbc);
//create border
TitledBorder title;
Border etched;
etched = BorderFactory.createEtchedBorder();
title=BorderFactory.createTitledBorder(etched," Question 2");
quepanelnorth2.setBorder(title);
JRadioButton radio1 = new JRadioButton(ans2);
JRadioButton radio2= new JRadioButton(ans3);
JRadioButton radio3 = new JRadioButton(ans4);
JRadioButton radio4= new JRadioButton(ans5);
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
group.add(radio3);
group.add(radio4);
// Put the radio buttons in a column in a panel
quepanelsouth2.setLayout(new GridLayout(0, 1));
quepanelsouth2.add(radio1);
quepanelsouth2.add(radio2);
quepanelsouth2.add(radio3);
quepanelsouth2.add(radio4);
//create border
TitledBorder answertitle;
Border etched2;
etched2 = BorderFactory.createEtchedBorder();
answertitle=BorderFactory.createTitledBorder(etched2," Answers ");
quepanelsouth2.setBorder(answertitle);
//SOUTH PANEL
panels=new JPanel();
Icon logo =new ImageIcon("testE_logo.gif");
logolabel = new JLabel(logo);
invlabel = new JLabel(" ");
next=new JButton("Next");
next.setActionCommand("enable");
next.addActionListener(this);
prev=new JButton("Previous");
prev.setActionCommand("disable");
prev.setEnabled(false);
prev.addActionListener(this);
mark=new JButton("Mark Sheet");
panels.add(next);
panels.add(prev);
panels.add(mark);
panels.add(invlabel);
panels.add(logolabel);
panel.add("North",paneln);
panel.add("Center",panelc);
panel.add("South",panels);
timerThread = new Thread(this);
timerThread.start();
public void actionPerformed(ActionEvent evt)
{ Object obj =evt.getSource();
if (obj==next)
try
result.next();
cont++;
catch(Exception e)
System.out.println("there is trobol" + e);
showRecord(result);
if(evt.getActionCommand().equals("enable"))
prev.setEnabled(true);
if(obj==prev)
try
result.previous();
catch(Exception e)
System.out.println("there is trobprevol" + e);
showRecord(result);
} -
I'm trying to extend JRadioButton to make their GUI representation smaller (and thus allow for a small panel with a number of small options on it). Here's my code, which should be pretty easy for any of you to compile and run:
package gs.globalrepo.Clients.TradeExplorer.temp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class SmallJRadio extends JFrame
public SmallJRadio()
initComponents();
pack();
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
private void initComponents()
JPanel panel = new JPanel(new GridBagLayout());
SmallJRadioButton a = new SmallJRadioButton(">");
SmallJRadioButton b = new SmallJRadioButton("=");
SmallJRadioButton c = new SmallJRadioButton("<");
ButtonGroup bg = new ButtonGroup();
bg.add(a);
bg.add(b);
bg.add(c);
panel.add(a, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
panel.add(b, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
panel.add(c, new GridBagConstraints(0, 2, 1, 1, 1, 1, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
getContentPane().add(panel);
private class SmallJRadioButton extends JRadioButton
public SmallJRadioButton(String text)
super(text);
protected void paintComponent(Graphics g)
g.setColor(Color.white);
g.fillRoundRect(1, 1, 7, 7, 2, 2);
g.setColor(Color.black);
g.drawRoundRect(0, 0, 8, 8, 2, 2);
if (isSelected()) {
g.fillRoundRect(3, 3, 3, 3, 1, 1);
g.setFont(new Font("Arial", Font.PLAIN, 10));
g.drawChars(getText().toCharArray(), 0, getText().length(), 12, 8);
public static void main(String[] args)
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("Unable to install system look and feel, use default");
SmallJRadio smallJRadio = new SmallJRadio();
smallJRadio.show();
}I have two questions:
1) Why are the buttons so far apart (horizontally)? I think it may have something to do with the predefined height of a JRadioButton, but overriding getHeight(), or calling setSize() doesn't seem to work. Any ideas?
2) When I move the mouse around the frame, the element painting gets messed up. I think it's painting all the different Strings ("<", "=", ">") over each other, but I can't figure out why or how to prevent it.
Any help will be appreciated (and good help will be rewarded!).
Thanks,
ReuvenFor your questions:
(1) It depends on the layout manager. You can try using FlowLayout then all may layout
horizontally instead vertically.
(2) The way you did is really not a good idea.
You do not "clean" the background that's why the text mess up.
Simply add g.setColor(getBackground()); g.fillRect(0, 0, 25, 12); at the beginning
of paintComponent will help the text mess up problem.
However, this is still not the "right" way to do the job. Your drawing stuff do not check
anything about component size, component border ... etc.
I think the right way is not create a sub class of JRadionButton,
it is better develop your own ButtonUI and set the RadionButton use your UI. -
JRadioButton icon that do not replace the circle
Hi,
I'm a student that learn how to code and I wanted to add some JRadioButton to one of my project. I wanted to put an icon next to my text (in my JRadioButton) but instead of that it replaced the circle of selection.
So my question is : how can I put an icon next to my text without replacing the circle of selection. I hope it's possible
ThanksOh for sure there are other possiblilities. It's really a question of exactly what you want and how hard you want to look/work to get it.
-
A JRadioButton Listener problem!
Here is a situation, Trying to create a JRadioButton Listener for kinda multiple choice Quiz. Questions and answers are written to the respective RadioButtons from a text file.
So once a button is selected, it should check if the selected button is the correct answer(getCorrectAnswer() returns the correct answer)to the particular question, if it is then it updates a score JTextField and also status JTextField otherwise just the status JTextField.
Below is the RadioButtonListener doesn't do what it is suppose to do i.e no effect on score & status JTextField.
Any suggestions to why or where I am going wrong?
//Listener for RADIOBUTTONS
class RadioButtonListener implements ItemListener
public void itemStateChanged(ItemEvent e)
for (int i=0; i<v.size(); i++)
QAs A = (QAs) v.elementAt(i);
if (e.getSource() == checkbox1)
if (checkbox1.equals(A.getCorrectAnswer()))
statusText.setText("Correct!");
scoreText.setText(score + " ");
score++;
else
statusText.setText("Incorrect");
else if(e.getSource() == checkbox2)
if (checkbox2.equals(A.getCorrectAnswer()))
statusText.setText("Correct!");
scoreText.setText(score + " ");
score++;
else
statusText.setText("Incorrect");
else if(e.getSource() == checkbox3)
if (checkbox3.equals(A.getCorrectAnswer()))
statusText.setText("Correct!");
scoreText.setText(score + " ");
score++;
else
statusText.setText("Incorrect");
} // END OF FOR LOOP
} // END OF itemStateChanged METHOD
} // END OF RadioButtonListener CLASSyou may try this:
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
//do something
} else {
//do something
} -
Questions on Print Quote report
Hi,
I'm fairly new to Oracle Quoting and trying to get familiar with it. I have a few questions and would appreciate if anyone answers them
1) We have a requirement to customize the Print Quote report. I searched these forums and found that this report can be defined either as a XML Publisher report or an Oracle Reports report depending on a profile option. Can you please let me know what the name of the profile option is?
2) When I select the 'Print Quote' option from the Actions drop down in the quoting page and click Submit I get the report printed and see the following URL in my browser.
http://<host>:<port>/dev60cgi/rwcgi60?PROJ03_APPS+report=/proj3/app/appltop/aso/11.5.0/reports/US/ASOPQTEL.rdf+DESTYPE=CACHE+P_TCK_ID=23731428+P_EXECUTABLE=N+P_SHOW_CHARGES=N+P_SHOW_CATG_TOT=N+P_SHOW_PRICE_ADJ=Y+P_SESSION_ID=c-RAuP8LOvdnv30grRzKqUQs:S+P_SHOW_HDR_ATTACH=N+P_SHOW_LINE_ATTACH=N+P_SHOW_HDR_SALESUPP=N+P_SHOW_LN_SALESUPP=N+TOLERANCE=0+DESFORMAT=RTF+DESNAME=Quote.rtf
Does it mean that the profile in our case is set to call the rdf since it has reference to ASOPQTEL.rdf in the above url?
3) When you click on submit button do we have something like this in the jsp code: On click call ASOPQTEL.rdf. Is the report called using a concurrent program? I want to know how the report is getting invoked?
4) If we want to customize the jsp pages can you please let me know the steps involved in making the customizations and testing them.
Thanks and Appreciate your patience
-PC1) We have a requirement to customize the Print Quote report. I searched these forums and found that this report can be defined either as a XML Publisher report or an Oracle Reports report depending on a profile option. Can you please let me know what the name of the profile option is?
I think I posted it in one of the threads2) When I select the 'Print Quote' option from the Actions drop down in the quoting page and click Submit I get the report printed and see the following URL in my browser.
http://<host>:<port>/dev60cgi/rwcgi60?PROJ03_APPS+report=/proj3/app/appltop/aso/11.5.0/reports/US/ASOPQTEL.rdf+DESTYPE=CACHE+P_TCK_ID=23731428+P_EXECUTABLE=N+P_SHOW_CHARGES=N+P_SHOW_CATG_TOT=N+P_SHOW_PRICE_ADJ=Y+P_SESSION_ID=c-RAuP8LOvdnv30grRzKqUQs:S+P_SHOW_HDR_ATTACH=N+P_SHOW_LINE_ATTACH=N+P_SHOW_HDR_SALESUPP=N+P_SHOW_LN_SALESUPP=N+TOLERANCE=0+DESFORMAT=RTF+DESNAME=Quote.rtf
Does it mean that the profile in our case is set to call the rdf since it has reference to ASOPQTEL.rdf in the above url?
Yes, your understanding is correct.3) When you click on submit button do we have something like this in the jsp code: On click call ASOPQTEL.rdf. Is the report called using a concurrent program? I want to know how the report is getting invoked?
No, there is no conc program getting called, you can directly call a report in a browser window, Oracle reports server will execute the report and send the HTTP response to the browser.4) If we want to customize the jsp pages can you please let me know the steps involved in making the customizations and testing them.
This is detailed in many threads.Thanks
Tapash
Maybe you are looking for
-
I want to make change number in CS02 and CS20 as mandatory. Pls suggest the procedure..
-
When attempting to burn, "The drive reported an Error..."
"The Drive reported an error: Sense Key=MEDUIM ERROR; Sense Code=X0C; WRITE ERROR" (Toast) also the 0x8002006E (with Apple OSX disk burner) sometimes get 0x80020063 I have not seen an answer and have been looking for a while as I am busy and don't ha
-
My Mac's sound won't work-the buttons do though
When I play videos(i haven't checked youtube yet) my sound was out if i paused the video and restarted. Now my sound won't work at all or even for my Facebook games. I had this problem before with just youtube and i was able to fix that, but now i ca
-
my i phone 4 s has started flickering and changeing coulor on the screen , its got ios 6.1.3 can any 1 help
-
No puedo eliminar los registros de llamadas recientes que hago?
No puedo eliminar los registros de llamadas recientes que hago?