How to get proper alignment of Title border over the Jtable - java

Im trying to build small application in java swings. I started using this link: Creating a Grid in Java.
Everything was good. I finished that task but onething is left that I'm trying to remove extra title border. I tried to reduce the border of title border still its not affect. Any one with good suggestion try to share with me.
package swings.application.framework;
import java.awt.*;
import java.awt.event.ActionEvent
;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Inf3rNix
*/
public class KidsProblemTable {
private static JButton okbtn;
private static JFrame frame;
public static void main(String[] args) {
Runnable runner = new Runnable() {
#Override
public void run() {
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Kids Table");
Border border = LineBorder.createGrayLineBorder();
frame.setLayout(null);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
JLabel Heading = new JLabel("My Result");
Heading.setFont(new Font("Gabriola", Font.ITALIC, 56));
Heading.setForeground(Color.BLUE);
Heading.setBounds(550, -60, 300, 200);
JLabel Heading2 = new JLabel("Nice Job! Here are your results...");
Heading2.setFont(new Font("Buxton Sketch", Font.ITALIC, 26));
Heading2.setForeground(Color.BLUE);
Heading2.setBounds(500, 10, 600, 200);
JLabel Heading3 = new JLabel();
String str = "You got 5 correct answer out of 7 question";
Heading3.setText("<html><a href=' ' style='color:rgb(248,116,49);'>" + str + "</a></html>");
Heading3.setFont(new Font("Andy", Font.PLAIN, 20));
Heading3.setBounds(500, 70, 600, 200);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
Border border1 = BorderFactory.createTitledBorder("Exercise");
panel1.setBounds(150, 200, 1000, 190);
String column = "Questions".toUpperCase();
// AttributedString as = new AttributedString(column);
// Font plainFont = new Font("Times New Roman", Font.PLAIN, 24);
// as.addAttribute(TextAttribute.FONT, plainFont);
// as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON,0,8 );
String column1 = "Problem".toUpperCase();
String column2 = "Answer".toUpperCase();
String column3 = "Answer".toUpperCase();
String results = "results".toUpperCase();
Object rowData[][] = {{"1", "3+9", "12", "12", "Correct !"},
{"2", "4+3", "7", "7", "Correct !"},
{"3", "10+8", "17", "18", "Sorry :("},
{"4", "5+1", "6", "6", "Correct !"},
{"5", "10+8", "18", "18", "Correct !"},
{"6", "8+2", "10", "10", "Correct !"},
{"7", "5+6", "4", "11", "Sorry :("}
};
Object columnNames[] = {column, column1, column2, column3, results};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable tb1 = new JTable(model) {
//when checking if a cell is editable always return false
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
//JTable table1 = new JTable(rowData, columnNames1);
tb1.setBackground(Color.getHSBColor(153, 0, 91));
JScrollPane scrollPane1 = new JScrollPane(tb1);
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
// ImageIcon icon = createImageIcon("images/wavy.gif", "wavy-line border icon");
okbtn=new JButton("Press Ok to Exit");
okbtn.setBorder(raisedbevel);
okbtn.setFont(new Font("Vani", Font.BOLD, 12));
okbtn.setBounds(575, 390, 150, 50);
panel2.add(scrollPane1, BorderLayout.CENTER);
okbtn.addActionListener(new buttonActionListener());
frame.add(Heading);
frame.add(Heading2);
frame.add(Heading3);
frame.add(okbtn);
frame.add(panel1);
panel2.setBorder(border1);
panel1.add(panel2);
frame.setSize(500, 500);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
private static class buttonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==okbtn){
JOptionPane.showMessageDialog(null, "All the best !!!");
WindowEvent winClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING );
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
}
}
}
}

maybe
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Inf3rNix
*/
public class KidsProblemTable {
private JFrame frame;
private JPanel panel1 = new JPanel();
private JLabel Heading = new JLabel("My Result", JLabel.CENTER);
private JLabel Heading2 = new JLabel("Nice Job! Here are your results...", JLabel.CENTER);
private JLabel Heading3 = new JLabel();
private String str = "You got 5 correct answer out of 7 question";
private JPanel panel2 = new JPanel();
private JButton okbtn;
private Object rowData[][] = {{"1", "3+9", "12", "12", "Correct !"},
{"2", "4+3", "7", "7", "Correct !"},
{"3", "10+8", "17", "18", "Sorry :("},
{"4", "5+1", "6", "6", "Correct !"},
{"5", "10+8", "18", "18", "Correct !"},
{"6", "8+2", "10", "10", "Correct !"},
{"7", "5+6", "4", "11", "Sorry :("}
};
private String column = "Questions".toUpperCase();
private String column1 = "Problem".toUpperCase();
private String column2 = "Answer".toUpperCase();
private String column3 = "Answer".toUpperCase();
private String results = "results".toUpperCase();
private Object columnNames[] = {column, column1, column2, column3, results};
private DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
private JTable tb1 = new JTable(model) {
private static final long serialVersionUID = 1L;
//when checking if a cell is editable always return false
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
private JScrollPane scrollPane1 = new JScrollPane(tb1);
public KidsProblemTable() {
Border border1 = BorderFactory.createTitledBorder("Exercise");
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
tb1.setBackground(Color.getHSBColor(153, 0, 91));
tb1.setPreferredScrollableViewportSize(tb1.getPreferredSize());
Heading.setFont(new Font("Gabriola", Font.ITALIC, 56));
Heading.setForeground(Color.BLUE);
Heading2.setFont(new Font("Buxton Sketch", Font.ITALIC, 26));
Heading2.setForeground(Color.BLUE);
Heading3.setText("<html><a href=' ' style='color:rgb(248,116,49);'>" + str + "</a></html>");
Heading3.setFont(new Font("Andy", Font.PLAIN, 20));
panel1.setLayout(new GridLayout(3, 1));
panel1.add(Heading);
panel1.add(Heading2);
panel1.add(Heading3);
// ImageIcon icon = createImageIcon("images/wavy.gif", "wavy-line border icon");
okbtn = new JButton(" Press Ok to Exit ");
okbtn.setBorder(raisedbevel);
okbtn.setFont(new Font("Vani", Font.BOLD, 12));
okbtn.addActionListener(new buttonActionListener());
panel2.add(okbtn);
panel2.setBorder(border1);
frame = new JFrame("Kids Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1, BorderLayout.NORTH);
frame.add(scrollPane1, BorderLayout.CENTER);
frame.add(panel2, BorderLayout.SOUTH);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
private class buttonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == okbtn) {
JOptionPane.showMessageDialog(null, "All the best !!!");
WindowEvent winClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
}
}
public static void main(String[] args) {
Runnable runner = new Runnable() {
#Override
public void run() {
new KidsProblemTable();
}
};
EventQueue.invokeLater(runner);
}
}

I found your problem,
You added the scrollPane to panel2 as
panel2.add(scrollPane1, BorderLayout.CENTER);
but you didn't setLayout as BorderLayout for panel2.
and you set the Layout of panel1 as null
see this code
JPanel panel1 = new JPanel();
panel1.setLayout(null);//add to your code
JPanel panel2 = new JPanel();
panel2.setLayout(new BorderLayout());//add to your code
panel2.setBounds(0,0,800,120);//add to your code
out put:
may this image will remove after some hours
out put image

Related

Adding new comboboxes Java

I have a problem with Swing interface on java. Explaination: I have a Combobox with 1, 2, 3, 4, 5 items. When an exact item is selected I need to create some more comboboxes the number of which depends on the selected item. So, if number 5 is selected, 5 more comboboxes must appear in the frame. I used ActionListener but it did not work properly. However, the same code but outside Actionlistener works well. What a problem can it be?
public class FrameClass extends JFrame {
JPanel panel;
JComboBox box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox adults = new JComboBox(s);
JComboBox children = new JComboBox(s1);
panel.add(box, BorderLayout.CENTER);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i <= box.getSelectedIndex(); i++) {
panel.add(adults, BorderLayout.WEST);
panel.add(children, BorderLayout.WEST);
}
}
});
add(panel);
}
}
public class MainClass {
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(Color.WHITE);
frame.setVisible(true);
}
}
The problem that you don't inform the layout manager about new elements in your panel.
Here is the correct variant of your action listener:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class FrameClass extends JFrame {
JPanel panel;
JComboBox<String> box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox[] adults = new JComboBox[5];
JComboBox[] children = new JComboBox[5];
for (int i = 0; i < 5; i++) {
adults[i] = new JComboBox<>(s);
children[i] = new JComboBox<>(s1);
}
panel.add(box, BorderLayout.CENTER);
JPanel nested = new JPanel();
add(nested, BorderLayout.EAST);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nested.removeAll();
nested.setLayout(new GridLayout(box.getSelectedIndex() + 1, 2));
for (int i = 0; i <= box.getSelectedIndex(); i++) {
nested.add(adults[i]);
nested.add(children[i]);
}
getContentPane().revalidate();
getContentPane().repaint();
pack();
}
});
add(panel);
}
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.getContentPane().setBackground(Color.WHITE);
frame.setLocationRelativeTo(null); // center the window
frame.setVisible(true);
}
}

Java: multiple ActionListeners in the same class?

I am currently working on a simulated stock market for my Software Engineering class. I am using the actionlistener to open up new windows for each one of my current menu items. However, it seems that I can only use one ActionListener per class so I can only have one set window for all of my menu options. Is there any other way to implement multiple action listeners? Is there another way to do this.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.table.DefaultTableModel;
public class GUIroughdraft implements Runnable, ActionListener
{
private JFrame frame;
private JMenuBar menuBar;
private JMenu FileMenu;
private JMenu ActionMenu;
private JMenu HelpMenu;
private JMenuItem SaveMenuItem;
private JMenuItem LoadMenuItem;
private JMenuItem ExitMenuItem;
private JMenuItem BuyMenuItem;
private JMenuItem SellMenuItem;
private JMenuItem AboutMenuItem;
private JMenuItem UserManualMenuItem;
public static void main(String[] args)
{
// needed on mac os x
System.setProperty("apple.laf.useScreenMenuBar", "true");
// the proper way to show a jframe (invokeLater)
SwingUtilities.invokeLater(new GUIroughdraft());
}
private JFrame frmBgszStockSimulator;
/**
* #wbp.nonvisual location=53,14
*/
//private final JLabel lblBgszStockSimulator = DefaultComponentFactory.getInstance().createTitle("BGSZ Stock Simulator");
private JTextField searchBar;
private JTable table;
/**
* Launch the application. Testing Comment
*/
/*
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
GUIroughdraft window = new GUIroughdraft();
window.frmBgszStockSimulator.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
*/
/**
* Create the application.
*/
/*
public GUIroughdraft()
{
run();
}
*/
/**
* Initialize the contents of the frame.
*/
public void run()
{
frmBgszStockSimulator = new JFrame("BGSZ Stock Simulator");
frmBgszStockSimulator.getContentPane().setBackground(Color.GRAY);
frmBgszStockSimulator.setTitle("BGSZ Stock Simulator");
frmBgszStockSimulator.setBounds(100, 100, 775, 510);
frmBgszStockSimulator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmBgszStockSimulator.setVisible(true);
//Builds menu bar
menuBar = new JMenuBar();
//Builds the File menu
FileMenu = new JMenu("File");
SaveMenuItem = new JMenuItem("Save");
LoadMenuItem = new JMenuItem("Load");
ExitMenuItem = new JMenuItem("Exit");
SaveMenuItem.addActionListener(this);
LoadMenuItem.addActionListener(this);
ExitMenuItem.addActionListener(this);
FileMenu.add(SaveMenuItem);
FileMenu.add(LoadMenuItem);
FileMenu.add(ExitMenuItem);
//Builds the Actions menu
ActionMenu = new JMenu("Actions");
BuyMenuItem = new JMenuItem("Buy");
SellMenuItem = new JMenuItem("Sell");
ActionMenu.add(BuyMenuItem);
ActionMenu.add(SellMenuItem);
//Builds the Help menu
HelpMenu = new JMenu("Help");
AboutMenuItem = new JMenuItem("About");
UserManualMenuItem = new JMenuItem("User Manual");
HelpMenu.add(AboutMenuItem);
HelpMenu.add(UserManualMenuItem);
menuBar.add(FileMenu);
menuBar.add(ActionMenu);
menuBar.add(HelpMenu);
frmBgszStockSimulator.setJMenuBar(menuBar);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBackground(Color.LIGHT_GRAY);
scrollBar.setBounds(323, 47, 21, 317);
frmBgszStockSimulator.getContentPane().add(scrollBar);
JTextArea displayBox = new JTextArea();
displayBox.setEditable(false);
displayBox.setLineWrap(true);
displayBox.setWrapStyleWord(true);
displayBox.setText("This will be a text field that displays all your actions and information about stocks, purchases, sales, errors, etc.");
//when the user clicks the search button that is not there anymore
//create a new instance of the getStockData class
//get the data from the input line something like String userInput = searchBar.getText()
//pass that to the getData(userInput);
//set the displayBox.setText(the return from getData());
displayBox.setBounds(12, 47, 312, 317);
frmBgszStockSimulator.getContentPane().add(displayBox);
searchBar = new JTextField();
searchBar.setText("Enter your text here");
searchBar.setBounds(12, 377, 733, 22);
frmBgszStockSimulator.getContentPane().add(searchBar);
searchBar.setColumns(10);
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setValue(75);
progressBar.setBounds(78, 412, 586, 14);
frmBgszStockSimulator.getContentPane().add(progressBar);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
{"Stock Name", "Stock Value", "Amount Owned", "Total Value"},
{" BAC", "$13.48", "4", "$53.92"},
{" RIG", "$8.89", "0", "$0.00"},
{" SUNE", "$0.59", "12", "$7.08"},
{" FCX", "$10.29", "2", "$20.58"},
{" PBR", "$5.86", "0", "$0.00"},
{" GE", "$31.83", "0", "$0.00"},
{" VALE", "$4.24", "24", "$101.76"},
{" VRX", "$27.07", "0", "$0.00"},
{" PFE", "$30.07", "0", "$0.00"},
{" CRC", "$1.05", "8", "$8.40"},
{" GGB", "$1.82", "0", "$0.00"},
{" CHK", "$4.01", "6", "$24.06"},
{" T", "$39.37", "0", "$0.00"},
{" F", "$13.35", "5", "$66.75"},
{" WLL", "$7.66", "0", "$0.00"},
},
new String[] {
"New column", "New column", "New column", "New column"
}
));
table.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
table.setBounds(350, 51, 395, 313);
frmBgszStockSimulator.getContentPane().add(table);
JTextArea txtrValue = new JTextArea();
txtrValue.setText("Displays Cash Value");
txtrValue.setLineWrap(true);
txtrValue.setEditable(false);
txtrValue.setBounds(99, 12, 172, 22);
frmBgszStockSimulator.getContentPane().add(txtrValue);
JTextArea txtrCurrentPortfolioValue = new JTextArea();
txtrCurrentPortfolioValue.setText("Display Portfolio Value");
txtrCurrentPortfolioValue.setLineWrap(true);
txtrCurrentPortfolioValue.setEditable(false);
txtrCurrentPortfolioValue.setBounds(376, 12, 206, 22);
frmBgszStockSimulator.getContentPane().add(txtrCurrentPortfolioValue);
JLabel lblCashValue = new JLabel("Cash Value:");
lblCashValue.setBounds(24, 15, 111, 16);
frmBgszStockSimulator.getContentPane().add(lblCashValue);
JLabel lblPortfolioValue = new JLabel("Portfolio Value:");
lblPortfolioValue.setBounds(283, 15, 123, 16);
frmBgszStockSimulator.getContentPane().add(lblPortfolioValue);
}
public void actionPerformed(ActionEvent ev)
{
SaveDialog dialog = new SaveDialog();
dialog.setModal(true);
dialog.setVisible(true);
}
private class SaveDialog extends JDialog implements ActionListener
{
private JButton okButton = new JButton("Your File has been saved!");
private SaveDialog()
{
super(frame, "Save", true);
JPanel panel = new JPanel(new FlowLayout());
panel.add(okButton);
getContentPane().add(panel);
okButton.addActionListener(this);
setPreferredSize(new Dimension(250, 75));
pack();
setLocationRelativeTo(frame);
}
public void actionPerformed(ActionEvent ev)
{
setVisible(false);
}
}
public void actionPerformed2(ActionEvent ev)
{
LoadDialog dialog = new LoadDialog();
dialog.setModal(true);
dialog.setVisible(true);
}
private class LoadDialog extends JDialog implements ActionListener
{
private JButton LoadButton = new JButton("Your File has successfully loaded!");
private LoadDialog()
{
super(frame, "Load", true);
JPanel panel = new JPanel(new FlowLayout());
panel.add(LoadButton);
getContentPane().add(panel);
LoadButton.addActionListener(this);
setPreferredSize(new Dimension(250, 75));
pack();
setLocationRelativeTo(frame);
}
public void actionPerformed(ActionEvent ev)
{
setVisible(false);
}
}
}
You don't need to implement the ActionListener interface, instead, create anonymous classes that provide the different functionality you need for any JButton or other object. An example would look like this:
myButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do whatever you want in here
}
});
In GUIroughdraft class, place this code inside actionPerformed method
public void actionPerformed(ActionEvent ev)
{
if(ev.getActionCommand().equalsIgnoreCase("Save"){
SaveDialog dialog = new SaveDialog();
dialog.setModal(true);
dialog.setVisible(true);
}
else if(ev.getActionCommand().equalsIgnoreCase("Load")){
LoadDialog dialog = new LoadDialog();
dialog.setModal(true);
dialog.setVisible(true);
}
else if(ev.getActionCommand().equalsIgnoreCase("Exit")){
// Do whatever you like
}
}
And also as per coding standards variable names should start with lower case letter.
private JMenuItem SaveMenuItem; ---wrong
private JMenuItem saveMenuItem; ---correct

Setting the font of a JTextArea

I want to create a Text Editor in Java. Here is what I've written so far:
package com.thundercrust.applications;
import java.awt.BorderLayout;
public class TextEditor implements ActionListener{
private static String[] fontOptions = {"Serif", "Agency FB", "Arial", "Calibri", "Cambrian", "Century Gothic", "Comic Sans MS", "Courier New", "Forte", "Garamond", "Monospaced", "Segoe UI", "Times New Roman", "Trebuchet MS", "Serif"};
private static String[] sizeOptions = {"8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28"};
ImageIcon newIcon = new ImageIcon("res/NewIcon.png");
ImageIcon saveIcon = new ImageIcon("res/SaveIcon.png");
ImageIcon openIcon = new ImageIcon("res/OpenIcon.png");
ImageIcon fontIcon = new ImageIcon("res/FontIcon.png");
ImageIcon changeFontIcon = new ImageIcon("res/ChangeFontIcon.png");
JButton New = new JButton(newIcon);
JButton Save = new JButton(saveIcon);
JButton Open = new JButton(openIcon);
JButton changeFont = new JButton(changeFontIcon);
JLabel fontLabel = new JLabel(fontIcon);
JLabel fontLabelText = new JLabel("Font: ");
JLabel fontSizeLabel = new JLabel("Size: ");
JComboBox <String> fontName = new JComboBox<>(fontOptions);
JComboBox <String> fontSize = new JComboBox<>(sizeOptions);
JToolBar tool = new JToolBar();
JTextArea texty = new JTextArea();
JScrollPane scroll = new JScrollPane(texty);
private static final int WIDTH = 1366;
private static final int HEIGHT = WIDTH / 16 * 9;
private static String name = "Text Editor";
private static JFrame frame = new JFrame();
public void Display() {
frame.setTitle(name);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
New.addActionListener(this);
New.setToolTipText("Creates a new File");
Save.addActionListener(this);
Save.setToolTipText("Saves the current File");
Open.addActionListener(this);
Open.setToolTipText("Opens a file");
changeFont.addActionListener(this);
changeFont.setToolTipText("Change the Font");
fontLabel.setToolTipText("Font");
fontLabelText.setToolTipText("Set the kind of Font");
fontSizeLabel.setToolTipText("Set the size of the Font");
tool.add(New);
tool.addSeparator();
tool.add(Save);
tool.addSeparator();
tool.add(Open);
tool.addSeparator();
tool.addSeparator();
tool.addSeparator();
tool.add(fontLabel);
tool.addSeparator();
tool.add(fontLabelText);
tool.add(fontName);
tool.addSeparator();
tool.add(fontSizeLabel);
tool.add(fontSize);
tool.addSeparator();
tool.add(changeFont);
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.add(tool, "North");
pane.add(scroll, "Center");
frame.setContentPane(pane);
}
public static void main(String args[]) {
TextEditor editor = new TextEditor();
editor.Display();
}
public void actionPerformed(ActionEvent evt) {
String fontNameSet;
String fontSizeSetTemp;
int fontSizeSet;
Object source = evt.getSource();
if(source == New) {
texty.setText("");
}
else if(source == changeFont) {
fontNameSet = (String) fontName.getSelectedItem();
fontSizeSetTemp = (String) fontSize.getSelectedItem();
fontSizeSet = Integer.parseInt(fontSizeSetTemp);
System.out.println(fontNameSet + fontSizeSet);
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
}
}
}
My problem is with setting fonts for the JTextArea. When I click the changeFont button on my actual program, nothing happens. What do I do?
new Font(fontNameSet, fontSizeSet, Font.PLAIN)
This has the arguments in the wrong order. It should be:
new Font(fontNameSet, Font.PLAIN, fontSizeSet)
Also, as mentioned in a comment:
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
Should be:
texty.setFont(new Font(fontNameSet, Font.PLAIN, fontSizeSet));

Retriving the String accosiated with a JCheckBox

I have a lottery game problem and I am able to count the number of checked boxes correctly but I do not understand how to get the String number assigned to the JcheckBox. I thought I could use .getText but that did not work. I am not sure if I am using the proper listener.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JLottery2 extends JFrame implements ItemListener {
private String[] lotteryNumbers = { "1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30" };
private JPanel jp1 = new JPanel();
private JPanel jp2 = new JPanel();
private JPanel jp3 = new JPanel(new GridLayout(3, 10, 5, 5));
private JLabel jl1 = new JLabel("The Lottery Game!!!!!");
private JLabel jl2 = new JLabel(
"To play, pick six number that match the randomly selected numbers.");
private FlowLayout layout = new FlowLayout();
private GridLayout gridBase = new GridLayout(3, 1, 5, 5);
private GridLayout grid = new GridLayout(3, 10, 5, 5);
private Font heading = new Font("Palatino Linotype", Font.BOLD, 24);
private Font bodyText = new Font("Palatino Linotype", Font.BOLD, 14);
private Color color1 = new Color(4, 217, 225);
private Color color2 = new Color(4, 225, 129);
private int maxNumber = 6;
private int counter = 0;
private int[] randomNum;
private String[] userPickedNumbers;
Container con = getContentPane();
public JLottery2() {
super("The Lottery Game");
con.setLayout(gridBase);
con.add(jp1);
jp1.setLayout(layout);
jp1.add(jl1);
jl1.setFont(heading);
jp1.setBackground(color1);
con.add(jp2);
jp2.setLayout(layout);
jp2.add(jl2);
jl2.setFont(bodyText);
jp2.setBackground(color1);
con.add(jp3);
jp3.setLayout(grid);
for (int i = 0; i < lotteryNumbers.length; i++) {
JCheckBox checkBox[] = new JCheckBox[lotteryNumbers.length];
checkBox[i] = new JCheckBox(lotteryNumbers[i]);
jp3.add(checkBox[i]);
jp3.setBackground(color2);
checkBox[i].addItemListener(this);
}
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void randNumber() {
randomNum = new int[maxNumber];
for (int i = 0; i < maxNumber; i++) {
randomNum[i] = ((int) (Math.random() * 100) % lotteryNumbers.length + 1);
System.out.println(randomNum[i]);
}
}
public static void main(String[] args) {
JLottery2 frame = new JLottery2();
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED && counter < maxNumber) {
counter++;
System.out.println("add");
System.out.println(counter);
} else if (e.getStateChange() == ItemEvent.DESELECTED
&& counter < maxNumber) {
counter--;
System.out.println("deduct");
System.out.println(counter);
}
if (counter == maxNumber) {
System.out.println("max");
jp3.setVisible(false);
randNumber();
System.out.println(userPickedNumbers);
}
}
}
((JCheckBox)e.getSource()).getText()
works fine for me with your code.

using scrollpane

I'm trying to get scrollbars to work.
The code displays the images I choose. And I've just read (on stackoverflow) about adding the image to a panel, then the panel to the scrollpane, and the scrollpane to the frame. So I tried doing that.
But I still can't get the scrollbars to show. Even when the image is bigger than the JFrame window.
Can anyone help? I've tried revalidate, but it didn't work so I took it out.
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MakeResizedImage {
private JFrame frame;
private JFileChooser fc;
private File file;
private int r;
private JTextField textField;
private Image img;
JScrollPane scrollPane;
ImagePanel panel_2;
public static void main(String[] args) {
MakeResizedImage MRI = new MakeResizedImage();
MRI.BuildJFrameGui();
}
private MakeResizedImage() {
}
private void BuildJFrameGui() {
JPanel panel = new JPanel();
panel.setLayout(null);
frame = new JFrame("View/Resize a png, jpg or gif image");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("Image:");
lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
panel_1.add(lblNewLabel);
textField = new JTextField();
panel_1.add(textField);
textField.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Width:");
panel_1.add(lblNewLabel_1);
Dimension Dim = new Dimension(45, 20);
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0),
null, new Integer(1)));
spinner.setPreferredSize(Dim);
panel_1.add(spinner);
JLabel lblHeight = new JLabel("Height:");
panel_1.add(lblHeight);
JSpinner spinner_1 = new JSpinner();
spinner_1.setModel(new SpinnerNumberModel(new Integer(0),
new Integer(0), null, new Integer(1)));
spinner_1.setPreferredSize(Dim);
panel_1.add(spinner_1);
JPanel panel_3 = new JPanel();
JButton btnNewButton = new JButton("Open");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
chooseFile();
}
});
panel_3.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Cancel");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
panel_3.add(btnNewButton_1);
JButton btnSave = new JButton("Save");
panel_3.add(btnSave);
frame.getContentPane().add(panel_3, BorderLayout.SOUTH);
scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
panel_2 = new ImagePanel();
scrollPane.setViewportView(panel_2);
frame.setVisible(true);
}
public void chooseFile() {
if (aFileChosen()) {
file = fc.getSelectedFile();
if (file.exists()) {
textField.setText(fc.getName());
try {
img = ImageIO.read(file);
panel_2.setImg(img);
} catch (IOException e) {
}
}
} else
JOptionPane.showMessageDialog(frame, "No file was chosen");
}
public boolean aFileChosen() {
fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"PNG, JPG & GIF Images", "png", "jpg", "gif");
fc.setFileFilter(filter);
fc.setApproveButtonText("Choose");
fc.setApproveButtonToolTipText("Selects the image you want to resize");
r = fc.showOpenDialog(frame);
if (r == JFileChooser.APPROVE_OPTION)
return true;
return false;
}
class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image img;
ImagePanel() {
};
ImagePanel(Image img) {
this.img = img;
}
public void setImg(Image img) {
this.img = img;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(300, 300));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Clears the previously drawn image.
g.clearRect(0, 0, getWidth(), getHeight());
//and draws the new one...
g.drawImage(img, 0, 0, this);
}
}
}
Use the other constructor, the one that wraps another component: JScrollPane(Component).
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
/**
* This Swing program demonstrates how to scroll a table row to visible area
* programmatically.
* #author www.codejava.net
*
*/
public class JTableRowScrollingExample extends JFrame implements ActionListener {
private JTable table = new JTable();
private JLabel label = new JLabel("Row number: ");
private JTextField fieldRowNumber = new JTextField(5);
private JButton buttonScroll = new JButton("Scroll to");
public JTableRowScrollingExample() {
super("JTable Row Scrolling Example");
String columnNames[] = {"No#", "Name", "Age", "Job"};
String[][] data = {
{"1", "John", "30", "Developer"},
{"2", "Jane", "31", "Designer"},
{"3", "Peter", "28", "Programmer"},
{"4", "Mary", "35", "Consultant"},
{"5", "Kim", "27", "Developer"},
{"6", "Geogre", "32", "Leader"},
{"7", "Dash", "36", "Analyst"},
{"8", "Tim", "25", "Designer"},
{"9", "Ana", "29", "Developer"},
{"10", "Tom", "41", "Manager"},
{"11", "Sam", "40", "Consultant"},
{"12", "Patrick", "38", "Manager"},
{"13", "Jeremy", "24", "Programmer"},
{"14", "David", "25", "Programmer"},
{"15", "Steve", "26", "Designer"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setPreferredSize(new Dimension(300, 150));
add(scrollpane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(label);
panel.add(fieldRowNumber);
panel.add(buttonScroll);
add(panel, BorderLayout.NORTH);
buttonScroll.addActionListener(this);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JTableRowScrollingExample().setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent event) {
int rowNumber = Integer.parseInt(fieldRowNumber.getText());
Rectangle cellRect = table.getCellRect(rowNumber, 0, false);
System.out.println(cellRect);
table.scrollRectToVisible(cellRect);
}
}

Categories

Resources