I want to create an array of JTextPane that it's size and values change through out the execution of my program, such as arrayList.
Is it possible to do it similar to an arrayList?
I've two JFrames. In the first frame I have a JList with about 100 items.
After selecting any of the items I want to paste them per Drag&Drop to the second frame.
The second frame has a GridBagLayout, hence I want to paste each selected item to an
array of JTextPane after dropping the items.
I want to use JTextPane because I want to format the selected text.
now I found a solution and my code seems to work:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class RefreshPanel {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JTextPane [] textPane;
private JScrollPane scrollbar;
private ArrayList arrayList = new ArrayList();
private JButton newItem = new JButton("new");
private int counter=0;
private GridBagLayout gbl = new GridBagLayout();
RefreshPanel() {
panel.setBackground(Color.WHITE);
panel.setLayout(gbl);
panel.setPreferredSize(new Dimension(100,50));
scrollbar = new JScrollPane(panel);
addButtonListener();
createFrame();
} //constructor
public void addButtonListener() {
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
arrayList.add("data");
textPane = new JTextPane[arrayList.size()];
for(int i=0;i<arrayList.size();i++) {
textPane[i]=new JTextPane();
textPane[i].setText((String) arrayList.get(i));
addComponent(panel, gbl, textPane[i], 1, counter, 1, 1,1,1);
counter++;
}
}
});
}
public void addComponent(Container cont,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbl.setConstraints( c, gbc );
cont.add( c );
}
public void createFrame() {
frame.getContentPane().setLayout(new FlowLayout());
frame.add(scrollbar);
frame.add(newItem);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300,300));
frame.setVisible(true);
}
public static void main(String [] args) {
new RefreshPanel();
}
}
But there is a little something which won't work: the items appears when I change the size of the frame, but I don't know why... any ideas?
thanks!
Related
I am using Dynamicreports4.1.1, whose chart based on Jfreechart.
I want to draw chart like image below:
It somewhat like Candlestickchart or stackedchart or layeredchart.
I choose the stackedchart to customize, it like this:
The code:
public class StackedBarChartReportTest {
public StackedBarChartReportTest() {
build();
}
private void build() {
FontBuilder boldFont = stl.fontArialBold().setFontSize(12);
TextColumnBuilder<String> itemColumn = col.column("Item", "item", type.stringType());
TextColumnBuilder<BigDecimal> bestColumn = col.column("Best", "best", type.bigDecimalType());
TextColumnBuilder<BigDecimal> worstColumn = col.column("Worst", "worst", type.bigDecimalType());
try {
report()
.setTemplate(Templates.reportTemplate)
.columns(itemColumn, bestColumn, worstColumn)
.title(Templates.createTitleComponent("StackedBarChart"))
.summary(
cht.stackedBarChart()
.customizers(new ChartCustomizer())
.setTitle("Stacked bar chart")
.setTitleFont(boldFont)
.setCategory(itemColumn)
.setShowValues(true)
.series(
cht.serie(bestColumn), cht.serie(worstColumn))
.setCategoryAxisFormat(
cht.axisFormat().setLabel("Item")))
.pageFooter(Templates.footerComponent)
.setDataSource(createDataSource())
.show();
} catch (DRException e) {
e.printStackTrace();
}
}
private class ChartCustomizer implements DRIChartCustomizer, Serializable {
private static final long serialVersionUID = 1L;
#Override
public void customize(JFreeChart chart, ReportParameters reportParameters) {
BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
// here customize,but have no idea...
}
}
private JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("item", "best", "worst");
dataSource.add("1Y", new BigDecimal(-10), new BigDecimal(-14.5));
dataSource.add("2Y", new BigDecimal(10), new BigDecimal(4));
dataSource.add("3Y", new BigDecimal(12), new BigDecimal(-2));
return dataSource;
}
public static void main(String[] args) {
new StackedBarChartReportTest();
}
Have no idea how to start or Is there a chart like this?
My question is very similar to this thread, however it was never properly answered.
I have an ImageAdapter setup as so;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
int[] mImages;
public ImageAdapter(Context c, int[] images) {
mContext = c;
mImages = images;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mImages[position]);
return imageView;
}
}
And I want the images to be from an XML;
<integer-array name="images">
<item>#drawable/image1</item>
<item>#drawable/image2</item>
<item>#drawable/image3</item>
</integer-array>
In my MainActivity class I have tried to get the image array and pass it into the ImageAdapter but I can't;
public class MainActivity extends AppCompatActivity {
private int images[] = getResources().getIntArray(R.array.images);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.setAdapter(new ImageAdapter(MainActivity.this, images));
}
}
I am currently getting an error message:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
with my app crashing on load up. I want to make my ImageAdapter display images from an XML in my GridView.
try to use
private int images[] = {R.drawable.image1, R.drawable.image3, R.drawable.image3};
instead of
private int images[] = getResources().getIntArray(R.array.images);
I'm new to Java and coding all together so I have hit a wall with my code. I've read nearly every post on this subject and still can't grasp it. Can somebody help?
Here is my code and permissions are already set in the manifest. Basically when I try to delete an item/file from a listview using onLongClick a file deletes, just not the one I want. The item first on the list deletes every attempt. I'm not sure how to solve this. I know that the code is half right considering the file does delete from the directory on the SD and from the listview. Getting the right file to delete is the problem. Any help would be appreciated.
public class ReadNoteMenu extends ActionBarActivity {
public static final String EXTRA_MESSAGE = "com.m4tchb0x87.rhinote.MESSAGE";
Context context;
public ReadNoteMenu() {
this.context = this;
}
ArrayAdapter mArrayAdapter;
ListView listView;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.setContentView(R.layout.activity_read_note_menu);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
listView = (ListView) this.findViewById(R.id.readListView);
String fileNames[] = new File(String.valueOf(Environment.getExternalStorageDirectory().getAbsolutePath()) + "/Rhinote").list();
mArrayAdapter = new ArrayAdapter<>(this, R.layout.list_item_1, fileNames);
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
String string = (String) listView.getItemAtPosition(i);
Intent intent = new Intent(ReadNoteMenu.this, (Class) ReadNote.class);
intent.putExtra(EXTRA_MESSAGE, string);
ReadNoteMenu.this.startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView adapterView, final View view, int position, long l) {
ContextThemeWrapper CTW = new ContextThemeWrapper( context, R.style.ADM_theme);
MaterialDialogCompat.Builder MDM1 = new MaterialDialogCompat.Builder(CTW);
MDM1.setMessage("Edit or delete file?");
MDM1.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
ContextThemeWrapper CTW = new ContextThemeWrapper( context, R.style.ADM_theme);
MaterialDialogCompat.Builder MDM2 = new MaterialDialogCompat.Builder(CTW);
MDM2.setMessage("Confirm delete file?");
MDM2.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
String str = (String) listView.getItemAtPosition(position);
Log.d(str,"Deleted" );
new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/RhiNote" + "/" + str).delete();
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_deleted,
(ViewGroup) findViewById(R.id.toast_layout_root_deleted));
TextView text = (TextView) layout.findViewById(R.id.text_deleted);
text.setText("Note deleted!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP, 250, 25);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
ReadNoteMenu.this.finish();
ReadNoteMenu.this.startActivity(ReadNoteMenu.this.getIntent());
}
});
MDM2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
ReadNoteMenu.this.startActivity(ReadNoteMenu.this.getIntent());
}
});
MDM2.show();
}
});
MDM1.setNegativeButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
ReadNoteMenu.this.startActivity(ReadNoteMenu.this.getIntent());
}
});
MDM1.show();
return true;
}
});
}
}
I figured out where I went wrong after a little debugging. It seems that the problem was that I hadn't declared the onItemLongClick int position final.
public boolean onItemLongClick(AdapterView adapterView, final View view, final int position, long l)
I've been working on this for a while but I can't seem to fix the one line that is giving me all the problems. This line "list = new JComboBox(measure);" underneath the array, seems to be giving me the error. I can suppress the error and it runs except the JComboBox does not work properly and gives the error
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JComboBox cannot be cast to javax.swing.JButton
at cube.actionPerformed(cube.java:132)"
Any help will be greatly appreciated!
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
//#SuppressWarnings("unchecked")
public class cube extends JFrame implements ActionListener{
public static JComboBox list;
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JTextField d;
public static String measureFinal;
public static String measurement;
//public static String [] measurement = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
public static JFrame main = new JFrame("Volume of Cube");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
cube object = new cube();
}
cube(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setPreferredSize(new Dimension(400,350));
main.add(myPanel);
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
d = new JTextField(3);
JButton button1 = new JButton("Solve!");
JButton button2 = new JButton("Back to shape selector");
myPanel.add(new JLabel ("Select the unit of measurement"));
String measure[] = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
list = new JComboBox(measure);
list.setSelectedIndex(0);
list.addActionListener(this);
myPanel.add(list);
myPanel.add(new JLabel ("Enter the height of the box"));
myPanel.add(a);
myPanel.add(new JLabel ("Enter the width of the box"));
myPanel.add(b);
myPanel.add(new JLabel ("Enter the length of the box"));
myPanel.add(c);
myPanel.add(button1);
button1.addActionListener(this);
myPanel.add(button2);
button2.addActionListener(this);
main.pack();
main.setLocation(600,200);
main.setVisible(true);
//tring [] measurement = {"Inches" , "Meters", "Feet"};
//double volume = height * width * length;
//String answer = "The volume of the box is " +volume+ measurement;
}
public void CBSelect(ActionEvent e){
int temp = 0;
temp = list.getSelectedIndex();
//Object temp = e.getSource();
/*
if (e.getSource() == list){
temp = list.getSelectedIndex();
switch(temp){
case 0:
measurement = "Inches";
break;
case 1:
measurement = "Meters";
break;
case 2:
measurement = "Feet";
break;
case 3:
measurement = "Centimeters";
break;
case 4:
measurement = "Millimeters";
break;
case 5:
measurement = "Yards";
break;
}
}
*/
if (temp == 0){
measurement = "Inches";
} else if (temp == 1){
measurement = "Meters";
}else if (temp == 2){
measurement = "Feet";
}else if (temp == 3){
measurement = "Centimeters";
}else if (temp == 4){
measurement = "Millimeters";
}else if (temp == 5){
measurement = "Yards";
}
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
//JComboBox cb = ((JComboBox) e.getSource());
//measureFinal = (String)cb.getSelectedItem();
if (actionCommand == "Solve!"){
double height = Double.parseDouble(a.getText());
double width = Double.parseDouble(b.getText());
double length = Double.parseDouble(c.getText());
double volume = height * width * length;
try{
final ImageIcon icon = new ImageIcon(new URL("http://wiki.fantasticcontraption.com/w/images/0/06/Solved.png"));
JOptionPane.showMessageDialog(this, ("The volume of the box is " +volume+" "+ measurement),"Volume", JOptionPane.PLAIN_MESSAGE, icon);
} catch (MalformedURLException ex){
System.out.println("Image Not Found!");
}
}
if (actionCommand == "Back to shape selector"){
main.dispose();
main.setVisible(false);
}
}
}
UPDATE: Looking back at it I'm now thinking the problem lies within the CBSelect Action Listener.
The thing is, since you do:
list.addActionListener(this);
// some other stuff...
button1.addActionListener(this);
button2.addActionListener(this);
Then source of the events passed to your method cube#actionPerformed can be list, button1 or button2.
So, you have you check the type of the source before casting it to anything and access its properties in the body of your actionPerformed method. You could do it like this:
final Object source = e.getSource();
String actionCommand = null;
if(source instanceof JButton) {
actionCommand = ((JButton) e.getSource()).getActionCommand();
} else if(source instanceof JComboBox<?>) {
actionCommand = ((JComboBox) e.getSource()).getSelectedItem().toString();
}
Cheers!
See if this works like you wanted:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
//#SuppressWarnings("unchecked")
public class cube extends JFrame implements ActionListener{
public static JComboBox list;
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JTextField d;
public static String measureFinal;
public static String [] measurement = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
public static JFrame main = new JFrame("Volume of Cube");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
cube object = new cube();
}
cube(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setPreferredSize(new Dimension(400,350));
main.add(myPanel);
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
d = new JTextField(3);
JButton button1 = new JButton("Solve!");
JButton button2 = new JButton("Back to shape selector");
myPanel.add(new JLabel ("Select the unit of measurement"));
String measure[] = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
list = new JComboBox(measure);
list.setSelectedIndex(0);
list.addActionListener(this);
myPanel.add(list);
myPanel.add(new JLabel ("Enter the height of the box"));
myPanel.add(a);
myPanel.add(new JLabel ("Enter the width of the box"));
myPanel.add(b);
myPanel.add(new JLabel ("Enter the length of the box"));
myPanel.add(c);
myPanel.add(button1);
button1.addActionListener(this);
myPanel.add(button2);
button2.addActionListener(this);
main.pack();
main.setLocation(600,200);
main.setVisible(true);
}
public void CBSelect(ActionEvent e){
int temp = 0;
temp = list.getSelectedIndex();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
measureFinal = (String)list.getSelectedItem();
if (actionCommand == "Solve!"){
double height = Double.parseDouble(a.getText());
double width = Double.parseDouble(b.getText());
double length = Double.parseDouble(c.getText());
double volume = height * width * length;
try{
final ImageIcon icon = new ImageIcon(new URL("http://wiki.fantasticcontraption.com/w/images/0/06/Solved.png"));
JOptionPane.showMessageDialog(this, ("The volume of the box is " +volume+" "+ measureFinal),"Volume", JOptionPane.PLAIN_MESSAGE, icon);
} catch (MalformedURLException ex){
System.out.println("Image Not Found!");
}
}
if (actionCommand == "Back to shape selector"){
main.dispose();
main.setVisible(false);
}
}
}
I'm using CombinedDomainXYPlot to plot the charts. I have another requirement where, I need to show the two charts horizontally.
Currently i'm having only one chart. what i need is, i need two charts in the first row.
like Chart1 Chart2
Code:
CombinedDomainXYPlot plot = new CombinedDomainXYPlot();
plot.add(getChart1(), 2);
plot.add(getChart2(), 2);
It is giving only one chart in the first row. and second chart2 in the another row.
Is there any way I can make these two charts into single row?
Edit: Actually I wanted it like your ThermometerDemo example. For that you have used JPanel, but here I'm using JFrame.
I wanted it like your ThermometerDemo example.
Based on this example, the code below adds two panels to a GridLayout(1, 0). Each panel includes it's own chart and control panel.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.*;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* #see https://stackoverflow.com/a/20243624/230513
* #see https://stackoverflow.com/q/11870416/230513
*/
public class CombinedPlot {
private static final int MAX = 3;
private static final Random rand = new Random();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
init();
}
});
}
private static void init() {
JFrame frame = new JFrame("Combined Plot Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(1, 0));
frame.add(createPanel());
frame.add(createPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JPanel createPanel() {
JPanel p = new JPanel(new BorderLayout());
XYItemRenderer renderer = new StandardXYItemRenderer();
XYPlot plot1 = new XYPlot(
generateData(), null, new NumberAxis("Range 1"), renderer);
XYPlot plot2 = new XYPlot(
generateData(), null, new NumberAxis("Range 2"), renderer);
final CombinedDomainXYPlot plot
= new CombinedDomainXYPlot(new NumberAxis("Domain"));
plot.add(plot1);
plot.add(plot2);
plot.setOrientation(PlotOrientation.VERTICAL);
JFreeChart chart = new JFreeChart(
"Combined Plots", JFreeChart.DEFAULT_TITLE_FONT, plot, false);
ChartPanel chartPanel = new ChartPanel(chart) {
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 320);
}
};
JPanel controlPanel = new JPanel();
controlPanel.add(new JButton(new UpdateAction(plot, 0)));
controlPanel.add(new JButton(new UpdateAction(plot, 1)));
p.add(chartPanel, BorderLayout.CENTER);
p.add(controlPanel, BorderLayout.SOUTH);
return p;
}
private static class UpdateAction extends AbstractAction {
private final XYPlot plot;
public UpdateAction(CombinedDomainXYPlot plot, int i) {
super("Update plot " + (i + 1));
this.plot = (XYPlot) plot.getSubplots().get(i);
}
#Override
public void actionPerformed(ActionEvent e) {
plot.setDataset(CombinedPlot.generateData());
}
}
private static XYSeriesCollection generateData() {
XYSeriesCollection data = new XYSeriesCollection();
for (int i = 0; i < MAX; i++) {
data.addSeries(generateSeries("Series " + (i + 1)));
}
return data;
}
private static XYSeries generateSeries(String key) {
XYSeries series = new XYSeries(key);
for (int i = 0; i < 16; i++) {
series.add(rand.nextGaussian(), rand.nextGaussian());
}
return series;
}
}