How to align buttons and checkboxes in different lines in java - java

Well I am a newbie in Java and i have written this simple case converter program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class caseconversion extends JFrame{
private JTextField tf;
private JCheckBox boldbox;
private JCheckBox italicbox;
private JButton up;
private JButton low;
public caseconversion(){
super ("Case Converter");
setLayout(new FlowLayout());
tf=new JTextField("Hello whats up Buddy !!",25);
tf.setFont(new Font("Segoe Print",Font.PLAIN,15));
add(tf);
boldbox = new JCheckBox("Bold");
italicbox = new JCheckBox("Italic");
add(boldbox);
add(italicbox);
up=new JButton("Upper Case");
low=new JButton("Lowercase");
add(up);
add(low);
HandlerClass handler = new HandlerClass();
boldbox.addItemListener(handler);
italicbox.addItemListener(handler);
up.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
tf.setText(tf.getText().toUpperCase());
}
}
);
low.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
tf.setText(tf.getText().toLowerCase());
}
}
);
}
private class HandlerClass implements ItemListener {
//For Checkboxes
public void itemStateChanged(ItemEvent event){
Font font= null;
if(boldbox.isSelected()&&italicbox.isSelected())
font = new Font("Segoe Print",Font.BOLD + Font.ITALIC ,15);
else if(boldbox.isSelected())
font = new Font("Segoe Print",Font.BOLD ,15);
else if(italicbox.isSelected())
font = new Font("Segoe Print",Font.ITALIC ,15);
else
font= new Font("Segoe Print",Font.PLAIN,15);
tf.setFont(font);
}
}
public static void main(String arg[]){
caseconversion go = new caseconversion();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400,250);
go.setVisible(true);
}
}
Its working fine but i want to display JTextField tf in center,boldbox&italicbok on next line in center and Similarly JButtons on 3rd line in Center Can you please tell me how to do it.

The most simple solution (with minimal changes to the original code) is probably to put each row into one JPanel (where each JPanel has a FlowLayout), and arrange these 3 panels using a GridLayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class caseconversion extends JFrame{
private JTextField tf;
private JCheckBox boldbox;
private JCheckBox italicbox;
private JButton up;
private JButton low;
public caseconversion(){
super ("Case Converter");
setLayout(new GridLayout(0,1));
JPanel p = null;
p = new JPanel();
tf=new JTextField("Hello whats up Buddy !!",25);
tf.setFont(new Font("Segoe Print",Font.PLAIN,15));
p.add(tf);
add(p);
p = new JPanel();
boldbox = new JCheckBox("Bold");
italicbox = new JCheckBox("Italic");
p.add(boldbox);
p.add(italicbox);
add(p);
p = new JPanel();
up=new JButton("Upper Case");
low=new JButton("Lowercase");
p.add(up);
p.add(low);
add(p);
HandlerClass handler = new HandlerClass();
boldbox.addItemListener(handler);
italicbox.addItemListener(handler);
up.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
tf.setText(tf.getText().toUpperCase());
}
}
);
low.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
tf.setText(tf.getText().toLowerCase());
}
}
);
}
private class HandlerClass implements ItemListener {
//For Checkboxes
public void itemStateChanged(ItemEvent event){
Font font= null;
if(boldbox.isSelected()&&italicbox.isSelected())
font = new Font("Segoe Print",Font.BOLD + Font.ITALIC ,15);
else if(boldbox.isSelected())
font = new Font("Segoe Print",Font.BOLD ,15);
else if(italicbox.isSelected())
font = new Font("Segoe Print",Font.ITALIC ,15);
else
font= new Font("Segoe Print",Font.PLAIN,15);
tf.setFont(font);
}
}
public static void main(String arg[]){
caseconversion go = new caseconversion();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400,250);
go.setVisible(true);
}
}
Note that you also have to think about the resizing behavior. Should these 3 rows always span the full height of the frame, or should they be compactly pushed to the top border of the frame?
However, a general hint (that seems to be underrated by newbies) is nesting: There's nothing wrong with creating a new JPanel in order to achieve a particular layout. Usually, a more "clean" solution to achieve this is to group several GUI components logically (and not re-using such a helper variable like the JPanel p that I used in the example).

If you using eclipse, i know a way that helped me.
JWindowbuilder: http://www.eclipse.org/windowbuilder/
If not you should look at this too:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
greetings Visores
i changed it the way you want with the WindowBuilder, i hope you like it :D
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class caseconversion extends JFrame {
private JTextField tf;
private JCheckBox boldbox;
private JCheckBox italicbox;
private JButton up;
private JButton low;
private Box verticalBox;
private Box horizontalBox;
private Box horizontalBox_1;
private Box horizontalBox_2;
private Component horizontalStrut;
private Component horizontalStrut_1;
private Component verticalStrut;
public caseconversion() {
super("Case Converter");
HandlerClass handler = new HandlerClass();
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
verticalBox = Box.createVerticalBox();
getContentPane().add(verticalBox);
horizontalBox = Box.createHorizontalBox();
verticalBox.add(horizontalBox);
horizontalStrut_1 = Box.createHorizontalStrut(20);
horizontalBox.add(horizontalStrut_1);
tf = new JTextField("Hello whats up Buddy !!", 25);
tf.setMaximumSize(new Dimension(2147483647, 60));
horizontalBox.add(tf);
tf.setFont(new Font("Segoe Print", Font.PLAIN, 15));
horizontalStrut = Box.createHorizontalStrut(20);
horizontalBox.add(horizontalStrut);
horizontalBox_1 = Box.createHorizontalBox();
verticalBox.add(horizontalBox_1);
boldbox = new JCheckBox("Bold");
horizontalBox_1.add(boldbox);
italicbox = new JCheckBox("Italic");
horizontalBox_1.add(italicbox);
italicbox.addItemListener(handler);
boldbox.addItemListener(handler);
horizontalBox_2 = Box.createHorizontalBox();
verticalBox.add(horizontalBox_2);
up = new JButton("Upper Case");
horizontalBox_2.add(up);
low = new JButton("Lowercase");
horizontalBox_2.add(low);
verticalStrut = Box.createVerticalStrut(20);
verticalBox.add(verticalStrut);
low.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
tf.setText(tf.getText().toLowerCase());
}
});
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
tf.setText(tf.getText().toUpperCase());
}
});
}
private class HandlerClass implements ItemListener {
// For Checkboxes
public void itemStateChanged(ItemEvent event) {
Font font = null;
if (boldbox.isSelected() && italicbox.isSelected())
font = new Font("Segoe Print", Font.BOLD + Font.ITALIC, 15);
else if (boldbox.isSelected())
font = new Font("Segoe Print", Font.BOLD, 15);
else if (italicbox.isSelected())
font = new Font("Segoe Print", Font.ITALIC, 15);
else
font = new Font("Segoe Print", Font.PLAIN, 15);
tf.setFont(font);
}
}
public static void main(String arg[]) {
caseconversion go = new caseconversion();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 250);
go.setVisible(true);
}
}

Well, you can add BorderLayout as follows, for the JTextField :
add(tf,BorderLayout.NORTH);
and add 2 JPanel items :-
private JPanel panel1;
private JPanel panel2;
and initialize them into constructor as follows:-
panel1 =new JPanel();
panel2 =new JPanel();
and add this code
panel1.add(boldbox);
panel1.add(italicbox);
add(panel1,BorderLayout.CENTER);
panel2.add(up);
panel2.add(low);
add(panel2,BorderLayout.SOUTH);
I hope this help you.

Related

Compiler Warning class uses unchecked or unsafe operations

My code is currently working fine, but whenever i compile, i get the Warning
C:\Users\etc\etc\FinalProject\AddItem.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.
Should I do something about it, and if so, what? if my debugging is right, it appears to be caused by the content pane properties.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.io.*;
class AddItem extends JFrame implements ActionListener
{
//text
private static JLabel TechforTeachingTitle;
private static JLabel TechforTeachingSubTitle;
//images
private static JLabel Logo;
//buttons
private JButton submitButton;
private static final int BUTTON_WIDTH = 100;
private static final int BUTTON_HEIGHT = 30;
//variables
public static void main(String[] args)
{
AddItem ProjectFrame = new AddItem();
ProjectFrame.setVisible(true); // Display the frame
//for combobox
//new AddItem().setVisible(true);
}
public AddItem ( )
{
//font properties
Font TitleFont = new Font("Serif", Font.BOLD, 80);
Font subFont = new Font("Serif", Font.BOLD, 40);
// set the frame properties
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Inventory system");
setSize(900, 700);
setLocationRelativeTo(null);
setResizable(true);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.decode("#FDF3E7"));
//set text properties
TechforTeachingTitle = new JLabel();
TechforTeachingTitle.setText("Tech For Teaching");
TechforTeachingTitle.setBounds(200, 30, 900, 95);
TechforTeachingTitle.setForeground(Color.decode("#8f8f8f"));
TechforTeachingTitle.setFont(TitleFont);
contentPane.add(TechforTeachingTitle);
TechforTeachingSubTitle = new JLabel();
TechforTeachingSubTitle.setText("Add an item");
TechforTeachingSubTitle.setBounds(400, 90, 900, 95); //left, top, length, height
TechforTeachingSubTitle.setForeground(Color.decode("#799177")); //7E8F7C (slightly less green)
TechforTeachingSubTitle.setFont(subFont);
contentPane.add(TechforTeachingSubTitle);
//set image properties
Logo = new JLabel(new ImageIcon("SmallLogo.png"));
Logo.setBounds(10,20,179,178); // //left, top, width, height
contentPane.add(Logo);
Logo.setVisible(true);
Logo.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
setVisible(false);
FinalProject FP = new FinalProject();
FP.setVisible(true);
}
});
//set button properties
//for combobox
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(null); //ONLY PROBLEM WITH THIS IS GETTING THE SCREEN TO APPEAR AT CORRECT SIZE
String[] values = {"Computer", "Monitor", "Keyboard"};
final JComboBox b = new JComboBox(values);
b.setEditable(true);
add(b);
b.setBounds(300, 300, 100, 50); //this works
add(b);
submitButton = new JButton("Submit");
submitButton.setBounds(700,600, BUTTON_WIDTH, BUTTON_HEIGHT);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String item=b.getSelectedItem().toString();
}
});
contentPane.add(submitButton);
//pack(); //not quite sure what this is for, but it makes the window tiny, so i commented it out
setLocationRelativeTo(null); //positions window center on screen
}
public void actionPerformed(ActionEvent event) // Actions
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
}
}
you get the warning here I think:
final JComboBox b = new JComboBox(values);
to avoid this you have the following possibilities:
add SupressWarning above the JComboBox
#SuppressWarnings("unchecked")
final JComboBox b = new JComboBox(values);
or add SupressWarning above your method
#SuppressWarnings("rawtypes")
public AddItem ( )
or my favourite add the generic:
final JComboBox<Object> b = new JComboBox<Object>(values);

Java Simple Simulator

I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Firstly capitalize the name of your class always in Java, then check this code :
public class Sim extends JPanel {
public Sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/1.png");
Icon c = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/2.png");
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
final JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
button.addActionListener(new HandlerClass(label));
}
private class HandlerClass implements ActionListener{
final JLabel label;
public HandlerClass(JLabel label){
this.label = label;
}
public void actionPerformed(ActionEvent e)
{
label.setText("SSSSSSSSSSSSSsssss");
JOptionPane.showMessageDialog(null, "Something");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new Sim());
frame.setVisible(true);
}
}

how to do keypress event in jpanel text field?

when i select something in combobox :
it show joptionPane Dialog box wiht two inputs.
here i want to first focusing amount field and then, when i entered in amount field its goes to no of App field then enter go to OK .
Here is my code for JOption Dialog:
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Amount:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("No of App:"));
myPanel.add(yField);
int value = 0;
xField.requestFocus();
int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter Amount and No.of app", JOptionPane.OK_CANCEL_OPTION);
You simply try to focus a component which is not layout in a window.
Replace
xField.requestFocus();
by
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xField.requestFocusInWindow();
}
});
You can create your own JDialog on the event that an item has changed to a new item. Then, you can get values entered in the JDialog and appropriately set the information in your parent. If you want to change the order of focus, use a custom focus policy. If you want to change the traversal focus key to the Enter key, you should re-map the key so that it reacts the same as the Tab key. There are several resources online and on this site with information on how to do that.
You should note that the default focus traversal policy is dependent on the order in which you add you elements to your content panel.
I have created a simple example for you on using a JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class RankSelection extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RankSelection frame = new RankSelection();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public RankSelection() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Slave", "Peasant", "Minion", "Knight", "Bishop", "Prince", "Coder King"}));
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
Amount amount = new Amount();
textField.setText(Integer.toString((Integer) amount.getStinkiness().getValue()));
}
}
});
contentPane.add(comboBox, BorderLayout.CENTER);
JLabel lblYourRank = new JLabel("Your Rank");
contentPane.add(lblYourRank, BorderLayout.NORTH);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
JLabel lblYourStinkiness = new JLabel("Your Stinkiness:");
panel.add(lblYourStinkiness);
textField = new JTextField();
textField.setEditable(false);
textField.setEnabled(false);
textField.setText("0");
panel.add(textField);
textField.setColumns(10);
pack();
}
}
The custom JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Amount extends JDialog {
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JSpinner amount;
private JSpinner stinkiness;
public Amount() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
JLabel lblAmount = new JLabel("Amount:");
amount = new JSpinner();
JLabel lblStinkiness = new JLabel("Stinkiness:");
stinkiness = new JSpinner();
contentPanel.add(lblAmount);
contentPanel.add(amount);
contentPanel.add(lblStinkiness);
contentPanel.add(stinkiness);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
pack();
setVisible(true);
}
public JSpinner getAmount() {
return amount;
}
public JSpinner getStinkiness() {
return stinkiness;
}
}

setlayout when dynamic adding textField

I am adding dynamic JTextField and JLabel in panel1 but I am not able to set the layout of JTextField and JLabel. I need to add JTextfield and JLabel to panel1 and I add panel1 to panel. I need to add JTextFields and JLabels in a Top-Bottom manner and set layout. panel1 and panel are instances of JPanel.
My code :
public class MakeScrollablePanel extends JFrame implements ActionListener
{
static JButton jButton11,jButton12;
static JPanel panel,panel1;
static JTextField jTextFields;
static JLabel label;
static JComboBox<String> jComboBox;
static Dimension dime,dime1,dime2,dime3,dime4,dime5;
static JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
BoxLayout bx=null;// #jve:decl-index=0:
int count=1,i=0;
public MakeScrollablePanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11);
add(scroll);
dime=new Dimension(600,550);
setSize(dime);
setTitle("Priyank Panel");
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
private void Show()
{
jButton11=new JButton("Add Designation");
panel=new JPanel();
bx=new BoxLayout(panel,BoxLayout.Y_AXIS);
scroll=new JScrollPane(panel);
dime1=new Dimension(500,3000);
dime5=new Dimension(500,450);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230 , 255));
jButton11.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==jButton11)
{
label=new JLabel("Add Designation "+count +" :-");
jTextFields=new JTextField(30);
panel1=new JPanel();
panel1.setBackground(new Color(204, 230 , 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel1.revalidate();
panel.revalidate();
panel.updateUI();
count++;
i++;
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}
still not working
still I can't see thre any problem with (depsite fact that there is used BoxLayout instead of GridLayout, but result could be very similair in the case that is used many JTextFields)
.
.
from (little bit) modifyied OPs code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class MakeScrollablePanel extends JFrame implements ActionListener {
private JButton jButton11, jButton12;
private JPanel panel, panel1;
private JTextField jTextFields;
private JLabel label;
private JComboBox<String> jComboBox;
private Dimension dime, dime1, dime2, dime3, dime4, dime5;
private JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
private BoxLayout bx = null;// #jve:decl-index=0:
private int count = 1, i = 0;
public MakeScrollablePanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11, BorderLayout.NORTH);
add(scroll);
setTitle("Priyank Panel");
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
private void Show() {
jButton11 = new JButton("Add Designation");
panel = new JPanel();
bx = new BoxLayout(panel, BoxLayout.Y_AXIS);
scroll = new JScrollPane(panel);
dime5 = new Dimension(500, 150);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230, 255));
jButton11.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == jButton11) {
label = new JLabel("Add Designation " + count + " :-");
jTextFields = new JTextField(30);
panel1 = new JPanel();
panel1.setBackground(new Color(204, 230, 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel.revalidate();
panel.repaint();
count++;
i++;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}

Change Button to JButton can't fixe it(((

I'm stuck using Button and JButton
expected result.. ( all information working )
http://i.stack.imgur.com/3qX7v.png
and what I have
http://i.stack.imgur.com/a4gao.png
I want to replace this:
Button butRock = new Button("Rock");
butRock.addActionListener(this);
ButtPan.add(butRock);
To This:
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
I'm stuck because when I replace Button to JButton the program doesn't work properly...when I use this JButton
Question: How to replace the button with picture and that program still work properly...
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class gui extends JFrame implements ActionListener
{
public JLabel JWoL,JWoLPlayer,JWoLPC,JNumWin,JNumLose,JNumTie, logo;
public JLabel JWinT,JLoseT,JTieT, rpsP, rpsC, result;
JPanel LabelsPan;
static final int WINS = 0, LOSSES = 1, DRAWS = 2;
int[] counts = new int[3];
String[] strings = {"| You Win", "| You Lose", "| Draw"};
JLabel[] labels = {JNumWin, JNumLose, JNumTie};
#SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
gui theWindow = new gui();
theWindow.show();
}
private void record(int type)
{
JWoL.setText(strings[type]);
counts[type]++;
labels[type].setText(""+counts[type]);
}
public gui() throws IOException
{
JPanel logo = new JPanel();
logo.setLayout(new GridLayout(1,1));
BufferedImage myPicture = ImageIO.read(new File("logo.jpg"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add(picLabel);
JPanel ButtPan=new JPanel();
ButtPan.setLayout(new GridLayout(1,3));
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
Button butPaper = new Button("Paper");
butPaper.addActionListener(this);
ButtPan.add(butPaper);
Button butScissors = new Button("Scissors");
butScissors.addActionListener(this);
ButtPan.add(butScissors);
JWoLPlayer = new JLabel();
JWoLPC = new JLabel();
JWoL= new JLabel();
JLabel rpsPlayer= new JLabel("| Your Choice: ");
JLabel rpsComputer= new JLabel("| Computers Choice: ");
setTitle("| RoPaS GAME |");
LabelsPan=new JPanel();
LabelsPan.setLayout(new GridLayout(3,2));
rpsP = new JLabel();
LabelsPan.add(rpsPlayer);
LabelsPan.add(JWoLPlayer);
rpsC = new JLabel();
LabelsPan.add(rpsComputer);
LabelsPan.add(JWoLPC);
result =new JLabel();
LabelsPan.add(JWoL,"Center");
JPanel WLPan = new JPanel();
WLPan.setLayout(new GridLayout(3, 2));
JWinT = new JLabel("Wins: ");
JLoseT = new JLabel("Losses: ");
JTieT = new JLabel("Ties: ");
WLPan.add(JWinT);
JNumWin = new JLabel();
WLPan.add(JNumWin);
WLPan.add(JLoseT);
JNumLose = new JLabel();
WLPan.add(JNumLose);
WLPan.add(JTieT);
JNumTie = new JLabel();
WLPan.add(JNumTie);
JLabel[] labels1 = {JNumWin, JNumLose, JNumTie};
labels = labels1;
JPanel TwoPanesN1=new JPanel();
TwoPanesN1.setLayout(new BorderLayout());
TwoPanesN1.add(logo,"North");
TwoPanesN1.add(LabelsPan,"West");
TwoPanesN1.add(WLPan,"East");
getContentPane().setLayout(new GridLayout(3,2));
getContentPane().add(ButtPan);
getContentPane().add(TwoPanesN1);
Font fontDisplay = new Font("Arial", Font.BOLD, 16);
JWoL.setFont(fontDisplay);
LabelsPan.setFont(fontDisplay);
setSize(400,250);
setVisible(true);
setResizable(false);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent ev){System.exit(0);}});
}
public void Play(String PlayerChoice)
{
String PCchoice=PCansw();
JWoLPC.setText(PCchoice);
if(PlayerChoice.equals(PCchoice))
record(DRAWS);
else if(PlayerChoice.equals("Rock"))
if(PCchoice.equals("Paper"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Paper"))
if(PCchoice.equals("Scissors"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Scissors"))
if(PCchoice.equals("Rock"))
record(LOSSES);
else
record(WINS);
}
public String PCansw()
{
String rpsPC2="";
int rpsPC=(int)(Math.random( )*3)+1;
if(rpsPC==1)
rpsPC2= "Rock";
else if(rpsPC==2)
rpsPC2= "Paper";
else if(rpsPC==3)
rpsPC2= "Scissors";
return rpsPC2;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Exit"))
System.exit(0);
else
{
JWoLPlayer.setText(e.getActionCommand());
Play(e.getActionCommand());
}
}
}
The problem is that you are using getActionCommand to determine which JButton was clicked but this property is not set by default in Swing. You would have to call
butRock.setActionCommand("Rock");
java.awt.Button automatically uses the label property as the ActionCommand if it not explicitly set. From the docs
If the command name is null (default) then this method returns the label of the button.
Some asides:
Better to avoid mixing heavy & lightweight components and use lightweight components throughout the application.
As your Rock, Paper, Scissors buttons have identical functionality, consider using an Action.
A direct instance JFrame is typically used rather than extending the class
Use Initial Threads
Window#show is deprecated. Use Window#setVisible.
Don't use System.exit - See more here

Categories