i cannot figure out how to get my code to tell when the button is pressed. i was taught poorly, just FYI so any help will need to be greatly detailed. also, i am new to the site so if the post isnt formatted correctly i am sorry.
public static void main(String[] args) {
final JFrame frame = new JFrame("JSlider Demo");
final double odd = 50;
final double bet = 1;
boolean auto = false;
double cash = 5.00;
int cash1 = 0;
JLabel jLabel1 = new JLabel("your cash: " + cash);
JButton b1 = new JButton("GO!");
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
// create odds slider
JSlider odds = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
odds.setMinorTickSpacing(5);
odds.setMajorTickSpacing(25);
odds.setPaintTicks(true);
odds.setPaintLabels(true);
odds.setLabelTable(odds.createStandardLabels(100));
//Create the label table for the odds slider
Hashtable labelTable1 = new Hashtable();
labelTable1.put( new Integer( 50 ), new JLabel("Odds") );
labelTable1.put( new Integer( 0 ), new JLabel("0") );
labelTable1.put( new Integer( 100 ), new JLabel("100") );
odds.setLabelTable( labelTable1 );
odds.setPaintLabels(true);
// create auto bet count slider
JSlider count = new JSlider(JSlider.HORIZONTAL, 1, 101, 1);
count.setMinorTickSpacing(5);
count.setMajorTickSpacing(20);
count.setPaintTicks(true);
count.setPaintLabels(true);
count.setLabelTable(count.createStandardLabels(50));
//Create the label table for auto bet count
Hashtable labelTable3 = new Hashtable();
labelTable3.put( new Integer( 50 ), new JLabel("Auto-bet count") );
labelTable3.put( new Integer( 1 ), new JLabel("1") );
labelTable3.put( new Integer( 101 ), new JLabel("100") );
count.setLabelTable( labelTable3 );
count.setPaintLabels(true);
// create auto bet speed slider
JSlider speed = new JSlider(JSlider.HORIZONTAL, 0, 4, 0);
speed.setMinorTickSpacing(20);
speed.setMajorTickSpacing(1);
speed.setPaintTicks(true);
speed.setPaintLabels(true);
speed.setLabelTable(speed.createStandardLabels(50));
//Create the label table for speed
Hashtable labelTable4 = new Hashtable();
labelTable4.put( new Integer( 2 ), new JLabel("Auto-bet speed") );
labelTable4.put( new Integer( 0 ), new JLabel("1(BPS)") );
labelTable4.put( new Integer( 4 ), new JLabel("5(BPS)") );
speed.setLabelTable( labelTable4 );
speed.setPaintLabels(true);
//sets the GUI
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 200);
frame.getContentPane().add(odds);
frame.getContentPane().add(count);
frame.getContentPane().add(speed);
frame.getContentPane().add(b1);
frame.getContentPane().add(jLabel1);
frame.setVisible(true);
}
Did you tried addActionListener method? For example;
JButton b1 = new JButton("GO!");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// execute this method when the button is pressed
}
});
Docs: https://docs.oracle.com/javase/8/docs/api/java/awt/event/ActionListener.html
You could make your class in which your main method exists, implement ActionListener, and then override the actionPerformed method. For example:
public class A implements ActionListener {
JButton b1 = new JButton("Hello");
b1.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if (e.getSource == b1) {
// do stuff when button b1 is clicked.
}
}
...
}
You can do this for all the buttons in the class. I'm not sure which way of doing this is recommended though, thought I'd add it anyway. :)
Related
I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way:
public class RandomMathGame extends JFrame {
public RandomMathGame(){
super("Random Math Game");
int random2;
JButton lvl1 = new JButton("LEVEL 1");
JButton lvl2 = new JButton("LEVEL 2");
JButton lvl3 = new JButton("LEVEL 3");
JLabel line1 = new JLabel("Line 1: ");
final JTextField jtf1 = new JTextField(10);
JLabel line2 = new JLabel("Line 2: ");
final JTextField jtf2 = new JTextField(10);
JLabel result = new JLabel("Result: ");
final JTextField jtf3 = new JTextField(10);
JButton ans = new JButton("Answer");
JLabel score = new JLabel("Score: ");
JTextField jtf4 = new JTextField(3);
JLabel itm = new JLabel("Number of Items: ");
JTextField items = new JTextField(3);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(lvl1);
add(lvl2);
add(lvl3);
add(line1);
add(jtf1);
add(line2);
add(jtf2);
add(result);
add(jtf3);
add(ans);
add(score);
add(jtf4);
add(itm);
add(items);
setSize(140,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
lvl1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i, j = 10;
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
int i3 = i1 + i2;
final int random1 = (int)(Math.random() * 10 + 1);
for (i = 0; i <= j + 1; i++){
try{
jtf1.setText(String.valueOf(random1));
jtf2.setText(String.valueOf(random1));
jtf3.setText(String.valueOf(i3));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)
Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.
I am trying to create this program for my class project. The compiler says process completed but nothing shows up when I try to run it.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class Project extends Applet implements ActionListener {
Label sp = new Label("Receipt Calculator");
Panel pl = new Panel();
Label cndy = new Label("Candy:");
TextField cndyi = new TextField(5);
Label bred = new Label("Bread:");
TextField bredi = new TextField(5);
Label sop = new Label("Soap:");
TextField sopi = new TextField(5);
Label mlk = new Label("Milk:");
TextField mlki = new TextField(5);
Label ham = new Label("Ham:");
TextField hami = new TextField(5);
Label srdns = new Label("Sardines:");
TextField srdnsi = new TextField(5);
Label cfee = new Label("Coffee:");
TextField cfeei = new TextField(5);
Label ndls = new Label("Noodles:");
TextField ndlsi = new TextField(5);
Label salt = new Label("Salt:");
TextField salti = new TextField(5);
Label btrs = new Label("Batteries:");
TextField btrsi = new TextField(5);
Button co = new Button("Compute Price");
Panel pnl = new Panel();
Label st = new Label("");
Label tx = new Label("");
Label t = new Label("");
public void init() {
setLayout(new GridLayout(2, 2));
setBackground(Color.blue);
add(sp);
add(pl);
pl.setLayout(new GridLayout(11, 2));
pl.add(cndy);
pl.add(cndyi);
pl.add(bred);
pl.add(bredi);
pl.add(sop);
pl.add(sopi);
pl.add(mlk);
pl.add(mlki);
pl.add(ham);
pl.add(hami);
pl.add(srdns);
pl.add(srdnsi);
pl.add(cfee);
pl.add(cfeei);
pl.add(ndls);
pl.add(ndlsi);
pl.add(salt);
pl.add(salti);
pl.add(btrs);
pl.add(btrsi);
add(co);
co.addActionListener(this);
add(pnl);
pnl.setLayout(new GridLayout(3, 2));
pnl.add(st);
pnl.add(tx);
pnl.add(t);
}
public void actionPerformed(ActionEvent z) {
int a, b, c, d, e, f, g, h, i, j;
double nst, ntx, nt;
a = Integer.parseInt(cndyi.getText());
b = Integer.parseInt(bredi.getText());
c = Integer.parseInt(sopi.getText());
d = Integer.parseInt(mlki.getText());
e = Integer.parseInt(hami.getText());
f = Integer.parseInt(srdnsi.getText());
g = Integer.parseInt(cfeei.getText());
h = Integer.parseInt(ndlsi.getText());
i = Integer.parseInt(salti.getText());
j = Integer.parseInt(btrsi.getText());
nst = (a * 31.50) + (b * 35) + (c * 25) +
(d * 38.85) + (e * 43.15) + (f * 13) +
(g * 39) + (h * 7) + (i * 10) + (j * 30);
ntx = nst + (nst * .12);
nt = nst + ntx;
st.setText("Sub-total = " + nst);
tx.setText("Sub-total = " + ntx);
t.setText("Sub-total = " + nt);
}
public static void main(String[] args) {
new Project();
}
}
Try to put all the panels in a Frame. Try to use this tutorial. http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html This is the Window used to display all the things, and make them visible.
This seems like a homework question to me. Problem is that you have nothing to run.
public static void main(String[] args) {
new Project();
}
All that does is make a new object but after that the program terminates: you need a loop.
Try this tutorial: Building Your First Java Applet.
Nothing shows up when I try to run it
That's because you haven't asked for anything. new Project() only creates a Project object and since you don't have a default constructor defined and you aren't explicitly calling any other methods, execution exits immediately. Make the following change
new Project().init();
You need to place your Panel in a JFrame to make it visible. Try something like the following in your init() method
JFrame frame = new JFrame();
frame.add(pl);
frame.pack();
frame.setVisible(true);
Your code runs fine for me. I see:
My guess is that you are trying to run it as a Java Application, instead of as a Java Applet. You do have main() method in your class, which is what might be causing this confusion. main() can be removed. In the case of applets, init() is the entry point, like main() would be if it was run as a application.
Right-click on the class and select Run As > Java Applet. For example:
So I am having a problem with my Java program. I currently want it to have 3 main course options Hamburger, Pizza, and Salad with add on options. Now currently the program starts with Hamburger selected and the add-ons available they calculate price as well. When the main item is selected the add-on options should change with the new item however they don't. I have been staring at this for awhile now so it could be I am missing something really simple like clearing the area and then having the new add-on options show. In any case any help would be appreciated, here is the current code.
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
public class LunchOrder extends JFrame {
private JRadioButton hamburgerJButton, pizzaJButton, saladJButton;
private JCheckBox lettuceButton, mayonnaiseButton, mustardButton, pepperoniButton,
sausageButton, mushroomsButton, croutonsButton, baconBitsButton, breadSticksButton;
private JLabel subTotal, tax, totalDue;
private JTextField subTotalText, taxText, totalDueText;
private JButton placeOrder, clearOrder, exitButton;
// no-argument constructor
public LunchOrder()
{
createUserInterface();
}
// create and position GUI components; register event handlers
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();
// enable explicit positioning of GUI components
contentPane.setLayout( null);
hamburgerJButton = new JRadioButton("Hamburger - $6.95" );
hamburgerJButton.setSelected(true);
pizzaJButton = new JRadioButton("Pizza - $5.95");
pizzaJButton.setSelected(false);
saladJButton = new JRadioButton("Salad - $4.95");
saladJButton.setSelected(false);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(hamburgerJButton);
bgroup.add(pizzaJButton);
bgroup.add(saladJButton);
JPanel mainCourse = new JPanel();
mainCourse.setLayout( new GridLayout( 3, 1 ));
mainCourse.setBounds( 10, 10, 150,135 );
mainCourse.add(hamburgerJButton);
mainCourse.add(pizzaJButton);
mainCourse.add(saladJButton);
mainCourse.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Main course" ) );
//contentPane.add( mainCourseJPanel, BorderLayout.NORTH );
contentPane.add( mainCourse );
//Add action listener to created button
//JCheckBox
lettuceButton = new JCheckBox("Lettuce, tomato, and onions");
lettuceButton.setSelected(true);
mayonnaiseButton= new JCheckBox("Mayonnaise");
mayonnaiseButton.setSelected(false);
mustardButton = new JCheckBox("Mustard");
mustardButton.setSelected(true);
pepperoniButton = new JCheckBox("Pepperoni");
sausageButton= new JCheckBox("Sausage");
mushroomsButton = new JCheckBox("Mushrooms");
croutonsButton = new JCheckBox("Croutons");
baconBitsButton= new JCheckBox("Bacon bits");
breadSticksButton = new JCheckBox("Bread sticks");
//JPanel addons
JPanel addOns = new JPanel();
GridLayout addOnGlay = new GridLayout(3,3);
addOns.setLayout(addOnGlay);
addOns.setBounds( 250, 10, 250, 135 );
addOns.add(lettuceButton);
addOns.add(pepperoniButton);
addOns.add(croutonsButton);
addOns.add(mayonnaiseButton);
addOns.add(sausageButton);
addOns.add(baconBitsButton);
addOns.add(mustardButton);
addOns.add(mushroomsButton);
addOns.add(breadSticksButton);
pepperoniButton.setVisible(false);
sausageButton.setVisible(false);
mushroomsButton.setVisible(false);
croutonsButton.setVisible(false);
baconBitsButton.setVisible(false);
breadSticksButton.setVisible(false);
addOns.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Add ons($.25/each)" ) );
contentPane.add( addOns );
// subtotal JLabel
subTotal = new JLabel();
subTotal.setBounds(10, 110, 100, 200);
contentPane.add(subTotal);
subTotal.setText( "Subtotal: " );
subTotal.setHorizontalAlignment(JLabel.RIGHT);
// subtotal JTextField
subTotalText = new JTextField();
subTotalText.setBounds(115, 200, 80, 22);
subTotalText.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(subTotalText);
// Tax JLabel
tax = new JLabel();
tax.setBounds(10, 135, 100, 200);
contentPane.add(tax);
tax.setText("Tax(7.85%) ");
tax.setHorizontalAlignment(JLabel.RIGHT);
// Tax JTextField
taxText = new JTextField();
taxText.setBounds(115, 225, 80, 22);
contentPane.add(taxText);
// total due JLabel
totalDue = new JLabel();
totalDue.setBounds(10, 160, 100, 200);
contentPane.add(totalDue);
totalDue.setText("Total due: " );
totalDue.setHorizontalAlignment(JLabel.RIGHT);
// total due JTextField
totalDueText = new JTextField();
totalDueText.setBounds(115, 250, 80, 22);
contentPane.add(totalDueText);
// order total JPanel
JPanel orderTotal = new JPanel();
GridLayout orderGLay = new GridLayout(3,1);
orderTotal.setLayout(orderGLay);
orderTotal.setBounds(10, 170, 200, 125 );
orderTotal.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Order total" ) );
contentPane.add( orderTotal );
// place order JButton
placeOrder = new JButton();
placeOrder.setBounds( 252, 175, 100, 24 );
placeOrder.setText( "Place order" );
contentPane.add( placeOrder );
placeOrder.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is pressed
public void actionPerformed(ActionEvent event) {
placeOrderActionPerformed(event);
}
} // end anonymous inner class
); // end call to addActionListener
// set up clearOrderJButton
clearOrder = new JButton();
clearOrder.setBounds(252,210, 100, 24 );
clearOrder.setText( "Clear order" );
contentPane.add( clearOrder );
clearOrder.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is pressed
public void actionPerformed(ActionEvent event) {
clearOrderActionPerformed(event);
}
} // end anonymous inner class
); // end call to addActionListener
// set up exitJButton
exitButton = new JButton();
exitButton.setBounds( 425, 260, 70, 24 );
exitButton.setText( "Exit" );
contentPane.add( exitButton );
// set properties of application's window
setTitle( "Lunch order" ); // set window title
setResizable(true); // prevent user from resizing window
setSize( 525, 350 ); // set window size
setVisible( true ); // display window
setLocationRelativeTo(null);
}
// calculate subtotal plus tax
private void placeOrderActionPerformed(ActionEvent event) {
DecimalFormat dollars = new DecimalFormat("$0.00");
// declare double variables
double hamburgerPrice = 6.95;
double pizzaPrice = 5.95;
double saladPrice = 4.95;
double addons = 0;
double subTotPrice;
double taxPercent;
double totalDuePrice;
if ( hamburgerJButton.isSelected())
{
if( lettuceButton.isSelected()){
addons += 0.25;
}
if( mayonnaiseButton.isSelected()){
addons += 0.25;
}
if( mustardButton.isSelected()){
addons += 0.25;
}
else{
addons -= 0.25;
}
subTotPrice = hamburgerPrice + addons;
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
if ( pizzaJButton.isSelected())
{
//lettuceButton.setVisible(false);
//mayonnaiseButton.setVisible(false);
//mustardButton.setVisible(false);
croutonsButton.setVisible(false);
baconBitsButton.setVisible(false);
breadSticksButton.setVisible(false);
pepperoniButton.setVisible(true);
sausageButton.setVisible(true);
mushroomsButton.setVisible(true);
//calculation for pizza selection
if( pepperoniButton.isSelected())
addons += 0.25;
if( sausageButton.isSelected())
addons += 0.25;
if( mushroomsButton.isSelected())
addons += 0.25;
else
addons -= 0.25;
subTotPrice = (pizzaPrice + addons);
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
if ( saladJButton.isSelected())
{
croutonsButton.setVisible(true);
baconBitsButton.setVisible(true);
breadSticksButton.setVisible(true);
if( croutonsButton.isSelected())
addons += 0.25;
if( baconBitsButton.isSelected())
addons += 0.25;
if( breadSticksButton.isSelected())
addons += 0.25;
else
addons -= 0.25;
//calculation for salad selection
subTotPrice = (saladPrice + addons);
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
} // end method calculateJButtonActionPerformed
private void clearOrderActionPerformed(ActionEvent event) {
//reset hamburger and addons to default state
hamburgerJButton.setSelected(true);
lettuceButton.setSelected(true);
mayonnaiseButton.setSelected(false);
mustardButton.setSelected(true);
subTotalText.setText("");
taxText.setText("");
totalDueText.setText("");
} // end method calculateJButtonActionPerformed
public static void main( String args[] )
{
LunchOrder application = new LunchOrder();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
You've not added any listeners that could notify of any kind of state change, Java can't magically know what you want it to...I wish...
You could use a ItemListener on each of the buttons, and based on what's selected, make a change to your UI, for example...
Create you're self a ItemListener...
ItemListener il = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Hamburger = " + hamburgerJButton.isSelected());
System.out.println("Pizza = " + pizzaJButton.isSelected());
System.out.println("Salad = " + saladJButton.isSelected());
}
}
};
And after you've initalised your buttons, register it with each of them...
hamburgerJButton.addItemListener(il);
pizzaJButton.addItemListener(il);
saladJButton.addItemListener(il);
Take a look at How to use buttons for more details
I am creating a simple Tic Tac Toe Application in Swing using setBounds (null Layout).
My problem is that whichever component i add in the end, is not visible in the frame, or distorts the complete GUI.
My code would better explain this
import java.awt.*;
import javax.swing.*;
class ZeroKata
{
ButtonGroup p1group,p2group;
Font f;
JButton begin,b1,b2,b3,b4,b5,b6,b7,b8,b9;
JCheckBox p1K,p2K,p1Z,p2Z;
JFrame frame;
JLabel player1,player2,p1Name,p2Name,p1Symbol,p2Symbol,status,dummy; // dummy label for my problem
JPanel buttons;
JTextField name1,name2;
private void addComponents(Container parent,JComponent...c)
{
for(JComponent C:c)
parent.add(C);
}
public ZeroKata()
{
frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setResizable(true);
frame.setVisible(true);
buttons = new JPanel();
buttons.setLayout(new GridLayout(3,3,10,10));
begin = new JButton("START GAME");
b1 = new JButton(" ");
b2 = new JButton(" ");
b3 = new JButton(" ");
b4 = new JButton(" ");
b5 = new JButton(" ");
b6 = new JButton(" ");
b7 = new JButton(" ");
b8 = new JButton(" ");
b9 = new JButton(" ");
p1K = new JCheckBox("X");
p1Z = new JCheckBox("O");
p2K = new JCheckBox("X");
p2Z = new JCheckBox("O");
p1group = new ButtonGroup();
p2group = new ButtonGroup();
p1group.add(p1K);
p1group.add(p1Z);
p2group.add(p2K);
p2group.add(p2Z);
name1 = new JTextField(30);
name2 = new JTextField(30);
f = new Font("Georgia",Font.PLAIN,38);
player1 = new JLabel (" << PLAYER 1 >>");
p1Name = new JLabel ("NAME : ");
p1Symbol = new JLabel ("SYMBOL : ");
player2 = new JLabel ("<< PLAYER 2 >>");
p2Name = new JLabel ("NAME : ");
p2Symbol = new JLabel ("SYMBOL : ");
status = new JLabel ("GAME STATUS -->> ");
dummy = new JLabel (" ");
addComponents(buttons,b1,b2,b3,b4,b5,b6,b7,b8,b9);
player1.setBounds(100,100,100,30);
p1Name.setBounds(120,150,100,30);
p1Symbol.setBounds(120,200,60,30);
player2.setBounds(100,250,100,30);
p2Name.setBounds(120,300,100,30);
p2Symbol.setBounds(120,350,50,30);
name1.setBounds(200,150,150,30);
p1K.setBounds(200,200,50,30);
p1Z.setBounds(250,200,50,30);
name2.setBounds(200,300,150,30);
p2K.setBounds(200,350,50,30);
p2Z.setBounds(250,350,50,30);
buttons.setBounds(500,100,250,250);
dummy.setBounds(20,20,30,30);
begin.setBounds(200,500,150,30);
frame.add(player1);
frame.add(p1Name);
frame.add(p1Symbol);
frame.add(player2);
frame.add(p2Name);
frame.add(p2Symbol);
frame.add(name1);
frame.add(name2);
frame.add(begin);
frame.add(buttons);
frame.add(p1K);
frame.add(p1Z);
frame.add(p2K);
frame.add(p2Z);
/* u need to add a dummy label also to let GUI work correctly, dont know whyx !
frame.add(dummy); */
}
public static void main(String...args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ZeroKata();
}
});
}
}
It is a simple code, I just don't know where I am going wrong .
Thanks in advance !
The default layout manager is a BorderLayout (see JFrame overview), set it to null to allow for absolute positioning:
frame.setLayout(null);
My problem is that whichever component i add in the end, is not
visible in the frame, or distorts the complete GUI. My code would
better explain this
you added JComponents to the already visible JFrame,
move frame.setVisible(true); as last code line, after all JComponents are added
Swing GUI should be started on Initial Threads
I was trying to build the Font window of Notepad using Java using the code shown below. But, I'm facing a problem in setting the size of the text as specified inside listbox.
I'm trying to get the respective size corresponding to the index of the selected item but couldn't find any such method.
f = new Frame("Font");
f.setLayout(new GridLayout(3, 3));
b1 = new Button("OK");
l1 = new Label("Font :");
l2 = new Label("Size :");
l3 = new Label("Font Style :");
lb1 = new List(10, false);
lb2 = new List(10, false);
lb3 = new List(5, false);
String [] s = {"Times New Roman", "Arial", "Verdana", "Trebuchet MS", "Papyrus","Monotype Corsiva","Microsoft Sans Serif", "Courier", "Courier New"};
for(int i = 0; i < s.length; i++)
{
lb1.add(s[i]);
}
for(int i = 8; i <=72; i += 2)
{
lb2.add(i + "");
}
String [] s1 = {"BOLD", "ITALIC", "PLAIN"};
for(int i = 0; i < s1.length; i++)
{
lb3.add(s1[i]);
}
f.add(l1);
f.add(l2);
f.add(l3);
f.add(lb1);
f.add(lb2);
f.add(lb3);
f.add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(lb3.isIndexSelected(0))
fo = new Font(lb1.getSelectedItem(), Font.BOLD, **lb2.getSelectedIndex**());
else if(lb3.isIndexSelected(1))
fo = new Font(lb1.getSelectedItem(), Font.ITALIC, lb2.getSelectedIndex());
else
fo = new Font(lb1.getSelectedItem(), Font.PLAIN, lb2.getSelectedIndex());
ta1.setFont(fo);
MyFrame15.f.dispose();
}
});
f.setSize(300, 300);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int)((d.getWidth() / 2) - 200);
int y = (int)((d.getHeight() / 2) - 200);
f.setLocation(x, y);
f.setVisible(true);
}
To get the size as required by user we can use:
lb2.getSelectedItem();
which returns a String but the third argument of Font constructor requires an integer.Therefore, we use parseInt() method of Integer class to convert the string received to integer.The code is as follows:
Font(lb1.getSelectedItem(), Font.BOLD, Integer.parseInt(lb2.getSelectedItem()));
I would suggest you use Swing for this. You can start with the Swing tutorial on Text Component Features which already contains a working example that does what you want.