Highlight one specific row/line in JTextArea - java

I am trying to highlight just one specific row in JTextArea, but I have no idea as to going about it. I need to get the specific row and then highlight it. I've read the other posts, but I still do not understand how to bring it together to solve my problem...help would be much appreciated.

Try your hands on this code example, and do ask if something is not clear :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextHighlight
{
private JTextArea tarea;
private JComboBox cbox;
private JTextField lineField;
private String[] colourNames = {"RED", "ORANGE", "CYAN"};
private Highlighter.HighlightPainter painter;
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("Text HIGHLIGHT");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5), "Highlighter JTextArea"));
tarea = new JTextArea(10, 10);
JScrollPane scrollPane = new JScrollPane(tarea);
contentPane.add(scrollPane);
JButton button = new JButton("HIGHLIGHT TEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int selection = JOptionPane.showConfirmDialog(
frame, getOptionPanel(), "Highlighting Options : ", JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if (selection == JOptionPane.OK_OPTION)
{
System.out.println("OK Selected");
int lineNumber = Integer.parseInt(lineField.getText().trim());
try
{
int startIndex = tarea.getLineStartOffset(lineNumber);
int endIndex = tarea.getLineEndOffset(lineNumber);
String colour = (String) cbox.getSelectedItem();
if (colour == colourNames[0])
{
System.out.println("RED Colour");
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
tarea.getHighlighter().addHighlight(startIndex, endIndex, painter);
}
else if (colour == colourNames[1])
{
System.out.println("ORANGE Colour");
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE);
tarea.getHighlighter().addHighlight(startIndex, endIndex, painter);
}
else if (colour == colourNames[2])
{
System.out.println("CYAN Colour");
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);
tarea.getHighlighter().addHighlight(startIndex, endIndex, painter);
}
}
catch(BadLocationException ble)
{
ble.printStackTrace();
}
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
System.out.println("CANCEL Selected");
}
else if (selection == JOptionPane.CLOSED_OPTION)
{
System.out.println("JOptionPane closed deliberately.");
}
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getOptionPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 5, 5));
JLabel lineNumberLabel = new JLabel("Enter Line Number : ");
lineField = new JTextField(10);
JLabel colourLabel = new JLabel("Select One Colour : ");
cbox = new JComboBox(colourNames);
panel.add(lineNumberLabel);
panel.add(lineField);
panel.add(colourLabel);
panel.add(cbox);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextHighlight().createAndDisplayGUI();
}
});
}
}
Here is the output of it :

If you are unable to select TextArea to TextField reason is button click causes the JTextArea to lose focus and thus not show its selection.
on button click event use btnImport.transferFocusBackward(); to resolve issue.

do like that :
this is the text area swing of java
JTextArea area = new JTextArea();
int startIndex = area.getLineStartOffset(2);
int endIndex = area.getLineEndOffset(2);
painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
area.getHighlighter().addHighlight(startIndex, endIndex, painter);

Related

Java; Update second ComboBox after selection in first ComboBox

I've been trying to get te grips of Java (just because:)). At the moment I'm stuck on a 'calculator'. My intention is to select a overall subject through a ComboBox after which a second ComboBox shows which units can be calculated for said subject.
My problem is that the second ComboBox does not update and I'm having a hard time finding my oversight. Is anyone able to show my where I'm going wrong?
note: The terms for unitstring are placeholders for the time being:).
public class UserInterface implements Runnable{
String unitstring = "Select a subject";
#Override
public void run() {
JFrame frame = new JFrame("Radiation Calculator 2.0");
frame.setPreferredSize(new Dimension(350, 250));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public void createComponents(Container container) {
GridLayout layout = new GridLayout(4, 2);
container.setLayout(layout);
JLabel subject = new JLabel("Select a subject");
String[] subjectStrings = {"Wavelenght", "Radioactive Decay", "Radiation Dose"};
JComboBox subjectsel = new JComboBox(subjectStrings);
subjectsel.addActionListener(this::actionPerformed);
JLabel unit = new JLabel("Select a unit");
String[] unitStrings = {unitstring};
JComboBox unitsel = new JComboBox(unitStrings);
JLabel input = new JLabel("Select a input");
JTextField userinput = new JTextField("");
JButton calculate = new JButton("Calculate");
JTextArea result = new JTextArea("");
container.add(subject);
container.add(subjectsel);
container.add(unit);
container.add(unitsel);
container.add(input);
container.add(userinput);
container.add(calculate);
container.add(result);
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
int print = cb.getSelectedIndex();
System.out.println(print);
unitArray(print);
}
public void unitArray(int x) {
if (x == 0) {
unitstring = "Lambda";
}
if (x == 1) {
unitstring = "Bequerel";
}
if (x == 2) {
unitstring = "Gray";
}
System.out.println(unitstring);
}
}

Java swing: managing integers/doubles with Listeners and J*Fields

EDITED
I've probably just stared at the screen for WAYYY too long but I feel the need to submit this question prior to going to sleep incase my delirium remains true...
The problem I'm having is I'm trying to get an int/double from the JTextField textField and convert it to a(n) int/double to use later in a listener, after retrieving it from a listener... ListenForText implements KeyListener, specifically KeyTyped, to obtain, through toString(), and store it in a String txtFldAmnt. After which I will store the result of Integer.parseInt(txtFldAmnt) into fldAmnt (fldAmnt = Integer.pareseInt(txtFldAmnt)) LINE 99 if copied to an editor. Once it's converted into an int I want to be able to manipulate it and then use it again, at LINE 173, to display, in a new window, the fldAmnt. Honestly, I don't really care about whether it's an int or String displayed, but I know a String is required for JTextField. What magic am I missing? Answers are always welcome but I prefer a chance to learn. Also, as I'm fairly new to Java, off topic pointers, criticism, and better ways to implement this code is greatly welcomed :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame{
/**
* wtf is the serial version UID = 1L
*/
private static final long serialVersionUID = 1L;
private JButton wdBtn;
private JButton dpBtn;
private JButton xferBtn;
private JButton balBtn;
private JRadioButton chkRadio;
private JRadioButton savRadio;
private JTextField textField;
private static String txtFldAmnt;
private static int fldAmnt = 0;
private static Double chkBal = 0.00;
private static Double savBal = 0.00;
public static void main(String[] args){
new GUI();
}
public GUI() {
//default location and size
this.setSize(300,182);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("ATM Machine");
//add buttons
wdBtn = new JButton("Withdraw");
dpBtn = new JButton("Deposit");
xferBtn = new JButton("Transfer");
balBtn = new JButton("Show Balance");
chkRadio = new JRadioButton("Checking");
chkRadio.setSelected(false);
savRadio = new JRadioButton("Savings");
savRadio.setSelected(false);
textField = new JTextField("", 20);
final JLabel textLabel = new JLabel("Enter amount: ");
textField.setToolTipText("Enter amount");
//Listener class to pass button listeners
ListenForButton lForButton = new ListenForButton();
wdBtn.addActionListener(lForButton);
dpBtn.addActionListener(lForButton);
xferBtn.addActionListener(lForButton);
balBtn.addActionListener(lForButton);
chkRadio.addActionListener(lForButton);
savRadio.addActionListener(lForButton);
ListenForText textFieldListener = new ListenForText();
textField.addKeyListener(textFieldListener);
//Configure layouts
JPanel PANEL = new JPanel();
PANEL.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,2, 5, 10));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,2,10,10));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(2,1));
//add buttons to their panels
panel1.add(wdBtn);
panel1.add(dpBtn);
panel1.add(xferBtn);
panel1.add(balBtn);
panel2.add(chkRadio);
panel2.add(savRadio);
panel3.add(textLabel);
panel3.add(textField);
PANEL.add(panel1);
PANEL.add(panel2);
PANEL.add(panel3);
this.add(PANEL);
//this.setAlwaysOnTop(true);
this.setVisible(true);
}
//implement listeners
private class ListenForText implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
txtFldAmnt = (e.toString());
fldAmnt = Integer.parseInt(txtFldAmnt);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e){
//maybe do case/switch statements
if (e.getSource() == wdBtn) {
JFrame newFrame = new JFrame("Withdraw Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Withdraw Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == dpBtn) {
JFrame newFrame = new JFrame("Deposit Title");
/*
* Set the newFrame.setSize(300,182); to this comment in the if statement to place
* the window directly over current window
*/
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Deposit Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == xferBtn) {
JFrame newFrame = new JFrame("Transfer Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Transfer Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == balBtn){
JFrame newFrame = new JFrame("Balance Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JTextField newLbl = new JTextField(Integer.toString(fldAmnt));
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
}
}
}
-cheers
EDITED BELOW
Thank for the answers, and I'm sorry for the horrible description... but I found a work around, thoguh I'm not sure if it's appropriate.
with the above example:
fldAmnt = Integer.pareseInt(txtFldAmnt)
i just added a .getText() //Though I rewrote the entire source code
fldAmnt = Integer.pareseInt(txtFldAmnt.getText())
it's worked for me for my entire program.
I wish I didn't have to post my entire code below but I haven't decided on a great place to store all of my code yet.
(SUGGESTIONS ARE WELCOME :D)
but here it is:
import javax.swing.;
import java.awt.GridLayout;
import java.awt.event.;
import javax.swing.border.*;
public class ATM extends JFrame{
//buttons needed
JButton wBtn;
JButton dBtn;
JButton xBtn;
JButton bBtn;
//radios needed
JRadioButton cRadio;
JRadioButton sRadio;
//Text field needed
JTextField txt;
JLabel txtLabel;
static int withdraw = 0;
Double amount = 0.00;
Double cBal = 100.00;
Double sBal = 100.00;
double number1, number2, totalCalc;
public static void main(String[] args){
new Lesson22();
}
public ATM(){
this.setSize(400, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Third Frame");
wBtn = new JButton("Withdraw");
dBtn = new JButton("Deposit");
xBtn = new JButton("Transfer");
bBtn = new JButton("Show Balance");
cRadio = new JRadioButton("Checking");
sRadio = new JRadioButton("Savings");
txtLabel = new JLabel("Amount: $");
txt = new JTextField("", 10);
JPanel thePanel = new JPanel();
// Create an instance of ListenForEvents to handle events
ListenForButton lForButton = new ListenForButton();
wBtn.addActionListener(lForButton);
dBtn.addActionListener(lForButton);
xBtn.addActionListener(lForButton);
bBtn.addActionListener(lForButton);
// How to add a label --------------------------
// Creates a group that will contain radio buttons
// You do this so that when 1 is selected the others
// are deselected
ButtonGroup operation = new ButtonGroup();
// Add radio buttons to the group
operation.add(cRadio);
operation.add(sRadio);
// Create a new panel to hold radio buttons
JPanel operPanel = new JPanel();
JPanel btnPanel1 = new JPanel();
JPanel btnPanel2 = new JPanel();
btnPanel1.setLayout(new GridLayout(1,2));
btnPanel2.setLayout(new GridLayout(1,2));
Border btnBorder = BorderFactory.createEmptyBorder();
btnPanel1.setBorder(btnBorder);
btnPanel1.add(wBtn);
btnPanel1.add(dBtn);
btnPanel2.setBorder(btnBorder);
btnPanel2.add(xBtn);
btnPanel2.add(bBtn);
Border operBorder = BorderFactory.createBevelBorder(1);
// Set the border for the panel
operPanel.setBorder(operBorder);
// Add the radio buttons to the panel
operPanel.add(cRadio);
operPanel.add(sRadio);
// Selects the add radio button by default
cRadio.setSelected(true);
JPanel txtPanel = new JPanel();
txtPanel.add(txtLabel);
txtPanel.add(txt);
thePanel.add(btnPanel1);
thePanel.add(btnPanel2);
thePanel.add(operPanel);
thePanel.add(txtPanel);
thePanel.setLayout(new GridLayout(4,2));
this.add(thePanel);
this.setVisible(true);
txt.requestFocus();
}
private class ListenForButton implements ActionListener{
// This method is called when an event occurs
public void actionPerformed(ActionEvent e){
/******************************************************
* THIS IS FOR CHECKING
*****************************************************/
// Check if the source of the event was the button
if(cRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
cBal -= amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel cLabel = new JLabel(Double.toString(cBal));
JLabel CLBL = new JLabel("Checking: ");
panel.add(CLBL);
panel.add(cLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
amount = Double.parseDouble(txt.getText());
cBal += amount;
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (sBal >= 0 && sBal >= amount){
cBal += amount;
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
/******************************************************
* THIS IS FOR SAVINGS
*****************************************************/
if(sRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
if(sBal >= 0 && sBal >= amount){
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel sLabel = new JLabel(Double.toString(sBal));
JLabel SLBL = new JLabel("Savings: ");
panel.add(SLBL);
panel.add(sLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
try{
amount = Double.parseDouble(txt.getText());
sBal += amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (cBal >= 0 && cBal >= amount){
sBal += amount;
cBal -= amount;
}
else if (cBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
...and by the way can anyone explain this warning message:
The serializable class ATM does not declare a static final serialVersionUID field of type long
If not simply don't bother. I'll keep researching into it when I have time.
This is still not complete, but thank you all for your help!
KeyListener on any JTextComponent is a bad idea.
To monitor changes to a text component, use a DocumentListener, to filter the content that a text component can handle, use a DocumentFilter. See Listening for Changes on a Document, Implementing a Document Filter and DocumentFilter Examples for more details.
In your case, it'd probably better to use a JSpinner or JFormattedTextField as they are designed to handle (amongst other things) numbers
See How to Use Spinners and How to Use Formatted Text Fields for more details

Need help debugging, code compiles but won't run

Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png

Border Layout looping. JPanel/swing

I'm having trouble with my looping and 'BorderLayout'. When I compile and run this using the driver it seems that the add.west(etc) is being overwritten by the proceeding add.west. I am left only with the 9th component in the 'south' panel, with 'east' and 'west' being completely empty. If I change the "for (int i=0; i<8; i++){" to: "for (int i=0; i<2; i++){" I get ONLY the second element of the required 9 in the 'west' panel. Can anyone please tell me why. Forgive my ignorance. I'm a beginner.
Thankyou.
Joe
This is roughly what it should look like:
(WEST) (EAST)
btn0, label0, label0 btn4, label4, label4
btn1, label1, label1 btn5, label5, label5
btn2, label2, label2 btn6, label6, label6
btn3, label3, label3 btn7, label7, label7
(SOUTH)
btn8, label8, label8
//CODE STARTS HERE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
public class CoinPanel extends JPanel{
private JButton buttons[] = new JButton[9];
private JLabel multiplySign[] = new JLabel[9];
private JLabel coinCount[] = new JLabel[9];
String [] names= {"1c", "2c", "5c", "10c", "20c", "50c", "€1", "€2", "Reset"};
int [] values= {1, 2, 5, 10, 20, 50, 100, 200, 0};
public CoinPanel(){
for (int i=0; i<8; i++){
buttons[i] = new JButton(names[i]);
buttons[i].addActionListener(new BtnListener());
coinCount[i] = new JLabel("0", JLabel.CENTER);
coinCount[i].setBorder(BorderFactory.createLineBorder(Color.black));
multiplySign[i] = new JLabel ("x", JLabel.CENTER);
//Layout stuff from here:
setLayout (new BorderLayout());
JPanel west= new JPanel();
west.setBackground(Color.BLACK);
JPanel east= new JPanel();
east.setBackground(Color.RED);
JPanel south= new JPanel();
south.setBackground(Color.BLUE);
if(i<4){
west.add (buttons[i]);
west.add (multiplySign[i]);
west.add (coinCount[i]);
}
else if(i<8){
east.add (buttons[i]);
east.add (multiplySign[i]);
east.add (coinCount[i]);
}
else{
multiplySign[i].setText("TOTAL");
south.add (multiplySign[i]);
south.add (coinCount[i]);
south.add (buttons[i]);
}
add(west, BorderLayout.WEST);
add(east, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
}
setPreferredSize (new Dimension(450,300));
}
//To here^^^
private class BtnListener implements ActionListener{
public void actionPerformed (ActionEvent event){
String [] text = new String[9];
int [] intArray = new int [9];
double sum =0;
for (int i=0; i<(intArray.length-1); i++){
if(event.getSource() == buttons[i]){
text[i] = coinCount[i].getText();
intArray[i]=Integer.parseInt(text[i]);
intArray[i] = ((intArray[i]) +1);
coinCount[i].setText(intArray[i] + "");
}
if(event.getSource() == buttons[8]){
coinCount[i].setText("0");
}
sum += (Integer.parseInt(coinCount[i].getText())*values[i]);
NumberFormat nf = NumberFormat.getCurrencyInstance();
coinCount[8].setText(nf.format(sum/100)+"");
}
}
}
}
//AND THIS IS THE DRIVER:
import javax.swing.*;
public class CoinSorter{
public static void main(String[] args){
JFrame frame = new JFrame ("Coin Counter Example");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
CoinPanel panel = new CoinPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Am I not only adding a single Panel to the three locations?
No, you have too much code in your loop.
1) You are creating 3 new panels every time you execute the loop.
the creation of your 3 west, east and south panels should be done before the loop starts.
2) Then at the end of the loop you are adding each of these panels to your main panel.
the three panels should be added to the main panel outside of the loop.
You can only have 1 component at which location at a time.
By adding another component to the same location (e.g. BorderLayout.WEST), you remove previous one. This is code from BorderLayout class that clearly shows that every time you add a WEST component, member variable west gets new value and old one is lost:
if ("Center".equals(name)) {
center = comp;
} else if ("North".equals(name)) {
north = comp;
} else if ("South".equals(name)) {
south = comp;
} else if ("East".equals(name)) {
east = comp;
} else if ("West".equals(name)) {
west = comp;
} else if (BEFORE_FIRST_LINE.equals(name)) {
firstLine = comp;
} else if (AFTER_LAST_LINE.equals(name)) {
lastLine = comp;
} else if (BEFORE_LINE_BEGINS.equals(name)) {
firstItem = comp;
} else if (AFTER_LINE_ENDS.equals(name)) {
lastItem = comp;
} else {
throw new IllegalArgumentException("cannot add to layout: unknown constraint: " + name);
}
}
}
Same goes for other placements.

Add components to JDialog

When I run this, an empty title bar is displayed. I just want to be able to see the components and work from there, but nothing is displayed. The dialog is designed to allow the user to select a color by moving sliders, then return to color to the main page.
import java.awt.*;
import javax.swing.*;
public class ColourDialog extends JDialog
{
String colorNames[] = {"Red: ", "Green: ", "Blue: "};
Label labels[] = new Label[3];
JSlider slider[]= new JSlider[3];
Label lb;
static ColourDialog d;
public void ColourDialog()
{
setModal(true);
Container c = getContentPane();
c.setLayout(new BorderLayout());
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++)
{
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
//slider[i].addChangeListener(this);
}
lb = new Label("Colour");
c.add(sliderPanel, BorderLayout.CENTER);
c.add(lb, BorderLayout.SOUTH);
setSize(500, 450);
setLocation(200,200);
setTitle("Colour Dialog");
}
public static Color showDialog()
{
if (d == null)
d = new ColourDialog();
d.show();
//return new Color(red,green,blue);
return new Color(0,0,0);
}
public static void main(String args[])
{
ColourDialog.showDialog();
}
}
I think that you have look at JColorChooser, this JComponent can returns selected Color
there I can't fout out correct definitions and initializations for JSlider
EDIT
there are lots of mistakes starting with extends JDialog end with public static Color showDialog(), that returns empty container typos with initializations for ColourDialog()
import java.awt.*;
import javax.swing.*;
public class ColourDialog {
private JDialog dialog = new JDialog();
private String colorNames[] = {"Red: ", "Green: ", "Blue: "};
private Label labels[] = new Label[3];
private JSlider slider[] = new JSlider[3];
private Label lb;
public ColourDialog() {
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(0, 1));
for (int i = 0; i < slider.length; i++) {
labels[i] = new Label(colorNames[i] + 255);
sliderPanel.add(labels[i]);
slider[i] = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 255);
slider[i].setMinorTickSpacing(10);
slider[i].setMajorTickSpacing(50);
slider[i].setPaintTicks(true);
slider[i].setPaintLabels(true);
sliderPanel.add(slider[i]);
}
lb = new Label("Colour");
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setModal(true);
dialog.add(sliderPanel, BorderLayout.CENTER);
dialog.add(lb, BorderLayout.SOUTH);
dialog.pack();
dialog.setLocation(200, 200);
dialog.setTitle("Colour Dialog");
dialog.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ColourDialog colourDialog = new ColourDialog();
}
});
}
}
I think it might be because you say "public void ColourDialog()" this is an invalid constructor. Try getting rid of the "void" and try again.
You never call the method ColorDialog(). This is a good spot to mention "start methods with a lower case letter). To fix you code:
Change:
d = new ColourDialog();
To:
d = new ColourDialog();
d.ColourDialog();

Categories